pregen-registry 0.2.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.
Files changed (30) hide show
  1. pregen_registry-0.2.0/LICENSE +202 -0
  2. pregen_registry-0.2.0/PKG-INFO +102 -0
  3. pregen_registry-0.2.0/README.md +84 -0
  4. pregen_registry-0.2.0/pregen_registry/__init__.py +2 -0
  5. pregen_registry-0.2.0/pregen_registry/app.py +97 -0
  6. pregen_registry-0.2.0/pregen_registry/check.py +129 -0
  7. pregen_registry-0.2.0/pregen_registry/cli.py +281 -0
  8. pregen_registry-0.2.0/pregen_registry/protocol.py +126 -0
  9. pregen_registry-0.2.0/pregen_registry/registry.py +601 -0
  10. pregen_registry-0.2.0/pregen_registry/schemas/anchors.json +70 -0
  11. pregen_registry-0.2.0/pregen_registry/schemas/answer.json +191 -0
  12. pregen_registry-0.2.0/pregen_registry/schemas/envelope.json +34 -0
  13. pregen_registry-0.2.0/pregen_registry/schemas/grant.json +98 -0
  14. pregen_registry-0.2.0/pregen_registry/schemas/keyset.json +237 -0
  15. pregen_registry-0.2.0/pregen_registry/schemas/proof.json +64 -0
  16. pregen_registry-0.2.0/pregen_registry/schemas/registry-document.json +71 -0
  17. pregen_registry-0.2.0/pregen_registry/schemas/report.json +164 -0
  18. pregen_registry-0.2.0/pregen_registry/schemas/report_ack.json +96 -0
  19. pregen_registry-0.2.0/pregen_registry/schemas/request.json +57 -0
  20. pregen_registry-0.2.0/pregen_registry.egg-info/PKG-INFO +102 -0
  21. pregen_registry-0.2.0/pregen_registry.egg-info/SOURCES.txt +28 -0
  22. pregen_registry-0.2.0/pregen_registry.egg-info/dependency_links.txt +1 -0
  23. pregen_registry-0.2.0/pregen_registry.egg-info/entry_points.txt +2 -0
  24. pregen_registry-0.2.0/pregen_registry.egg-info/requires.txt +9 -0
  25. pregen_registry-0.2.0/pregen_registry.egg-info/top_level.txt +1 -0
  26. pregen_registry-0.2.0/pyproject.toml +25 -0
  27. pregen_registry-0.2.0/setup.cfg +4 -0
  28. pregen_registry-0.2.0/tests/test_directory.py +130 -0
  29. pregen_registry-0.2.0/tests/test_identity_market.py +286 -0
  30. pregen_registry-0.2.0/tests/test_registry.py +577 -0
@@ -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,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: pregen-registry
3
+ Version: 0.2.0
4
+ Summary: Reference PRE-GEN registry: ask before you generate, get a signed answer anyone can check.
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: pregen>=0.11.0
10
+ Requires-Dist: fastapi>=0.110
11
+ Requires-Dist: uvicorn>=0.29
12
+ Requires-Dist: cryptography>=42
13
+ Requires-Dist: jsonschema>=4.21
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest>=8; extra == "test"
16
+ Requires-Dist: httpx>=0.27; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # pregen-registry
20
+
21
+ The reference PRE-GEN registry. **Ask before you generate; get a signed answer anyone can
22
+ check.** It implements `spec/PRE-GEN-CORE.md`, the profile `likeness/1` and these extensions:
23
+ `reports`, `provider-keys`, `limits`, `jobs`, `grants`, `licensee`, `observe`, `lookup` and,
24
+ in sandbox mode, `sandbox`.
25
+
26
+ It is a registry, not a marketplace: it has no prices, payments or dashboards. Those belong to
27
+ each registry's own business.
28
+
29
+ ## Run a sandbox in a minute
30
+
31
+ ```bash
32
+ pip install pregen-registry
33
+ pregen-registry init --dir ./data --prefix TEST --name "My sandbox" --api http://127.0.0.1:8000 --sandbox
34
+ pregen-registry serve --dir ./data
35
+ curl -X POST http://127.0.0.1:8000/v2/sandbox/access # a provider id and token, no account
36
+ ```
37
+
38
+ The sandbox holds the standard test subjects `PG-TEST-000001…` to `…000008`. Each one
39
+ answers as `spec/extensions/sandbox.md` says.
40
+
41
+ ## Run a real registry
42
+
43
+ 1. **Pick a prefix.** Four letters from `ABCDEFGHJKMNPQRSTVWXYZ`, then apply for it
44
+ (`pregen.org/registries`).
45
+ 2. **Create the registry:**
46
+ `pregen-registry init --dir ./data --prefix ABCD --name "…" --api https://registry.example --policy https://… --complaints mailto:…`
47
+ 3. **Give the steward the operator key.** Hand over the key id and public key printed by
48
+ `init`, out of band. Back up `data/operator.key` offline; it is created with mode 600.
49
+ 4. **Add subjects, grants, providers and end users:**
50
+ - `pregen-registry subject add --name "…" --level verified`
51
+ - `pregen-registry grant add --subject PG-ABCD-… --purposes commercial --days 365 --max-uses 100`
52
+ - `pregen-registry provider add --id frame-ai` — prints the credential once
53
+ - `pregen-registry connect --provider frame-ai --licensee frame-ai:user-1`
54
+ 5. **Serve it behind TLS:** `pregen-registry serve --dir ./data --host 0.0.0.0 --port 8000`, or HTTPS directly with
55
+ `--ssl-certfile cert.pem --ssl-keyfile key.pem`.
56
+ 6. **Anchor public people:** `pregen-registry subject anchor --code PG-ABCD-… --anchor wikidata:Q… --proof-url https://…`
57
+ 7. **Check yourself:** `pregen-registry check --api https://registry.example [--directory URL]` ends `OK: all checks
58
+ passed` when your document, key set and listing are right.
59
+
60
+ The whole path, step by step with what each command prints: `docs/registry.md`.
61
+
62
+ `PREGEN_OPERATOR_KEY_HEX` may hold the operator key instead of the file.
63
+
64
+ **Rotating the operator key.**
65
+ 1. `pregen-registry key next --dir ./data` makes the next key and prints it. Give the key id and public key to the
66
+ steward to announce in the directory.
67
+ 2. Once the directory lists it, run `pregen-registry key rotate --dir ./data` and restart.
68
+
69
+ The old key stays in `GET /keys` as `retired`, so every answer and proof it signed still verifies. A retired key
70
+ never signs again. Move its private key file offline.
71
+
72
+ ## HTTP interface
73
+
74
+ | Method and path | What |
75
+ |---|---|
76
+ | `GET /.well-known/pregen-registry.json` | who this registry is |
77
+ | `GET /keys` | its signed operator key set: every key it ever signed with, current and retired |
78
+ | `POST /v2/requests` | ask → `{"answer": <signed pg.answer.v1>}` |
79
+ | `POST /v2/reports` | report → `{"ack": <signed pg.report_ack.v1>}` |
80
+ | `POST /v2/keys`, `GET /v2/keys/{provider_id}` | provider keysets |
81
+ | `GET /v2/grants/{id}` | a signed grant |
82
+ | `GET /v2/codes/{code}` | public lookup |
83
+ | `POST /v2/sandbox/access` | sandbox credentials (sandbox mode only) |
84
+
85
+ ## Limits of this version
86
+
87
+ - **One process, SQLite, one write lock.** Correct and simple; move to Postgres with per-row
88
+ locks when throughput matters.
89
+ - **Managed subject keys are stored in the database.** Encrypt them, or use a KMS, before
90
+ holding real people.
91
+ - **Provider key recovery** (a keyset co-signed by the registry) is not implemented yet.
92
+
93
+ ## Tests
94
+
95
+ ```bash
96
+ pip install -e ".[test]" && pytest
97
+ ```
98
+
99
+ The tests cover:
100
+ - every rule of the core and of the extensions above;
101
+ - twenty concurrent jobs racing for a grant's last use;
102
+ - the byte vectors in `spec/test-vectors/messages.json`.
@@ -0,0 +1,84 @@
1
+ # pregen-registry
2
+
3
+ The reference PRE-GEN registry. **Ask before you generate; get a signed answer anyone can
4
+ check.** It implements `spec/PRE-GEN-CORE.md`, the profile `likeness/1` and these extensions:
5
+ `reports`, `provider-keys`, `limits`, `jobs`, `grants`, `licensee`, `observe`, `lookup` and,
6
+ in sandbox mode, `sandbox`.
7
+
8
+ It is a registry, not a marketplace: it has no prices, payments or dashboards. Those belong to
9
+ each registry's own business.
10
+
11
+ ## Run a sandbox in a minute
12
+
13
+ ```bash
14
+ pip install pregen-registry
15
+ pregen-registry init --dir ./data --prefix TEST --name "My sandbox" --api http://127.0.0.1:8000 --sandbox
16
+ pregen-registry serve --dir ./data
17
+ curl -X POST http://127.0.0.1:8000/v2/sandbox/access # a provider id and token, no account
18
+ ```
19
+
20
+ The sandbox holds the standard test subjects `PG-TEST-000001…` to `…000008`. Each one
21
+ answers as `spec/extensions/sandbox.md` says.
22
+
23
+ ## Run a real registry
24
+
25
+ 1. **Pick a prefix.** Four letters from `ABCDEFGHJKMNPQRSTVWXYZ`, then apply for it
26
+ (`pregen.org/registries`).
27
+ 2. **Create the registry:**
28
+ `pregen-registry init --dir ./data --prefix ABCD --name "…" --api https://registry.example --policy https://… --complaints mailto:…`
29
+ 3. **Give the steward the operator key.** Hand over the key id and public key printed by
30
+ `init`, out of band. Back up `data/operator.key` offline; it is created with mode 600.
31
+ 4. **Add subjects, grants, providers and end users:**
32
+ - `pregen-registry subject add --name "…" --level verified`
33
+ - `pregen-registry grant add --subject PG-ABCD-… --purposes commercial --days 365 --max-uses 100`
34
+ - `pregen-registry provider add --id frame-ai` — prints the credential once
35
+ - `pregen-registry connect --provider frame-ai --licensee frame-ai:user-1`
36
+ 5. **Serve it behind TLS:** `pregen-registry serve --dir ./data --host 0.0.0.0 --port 8000`, or HTTPS directly with
37
+ `--ssl-certfile cert.pem --ssl-keyfile key.pem`.
38
+ 6. **Anchor public people:** `pregen-registry subject anchor --code PG-ABCD-… --anchor wikidata:Q… --proof-url https://…`
39
+ 7. **Check yourself:** `pregen-registry check --api https://registry.example [--directory URL]` ends `OK: all checks
40
+ passed` when your document, key set and listing are right.
41
+
42
+ The whole path, step by step with what each command prints: `docs/registry.md`.
43
+
44
+ `PREGEN_OPERATOR_KEY_HEX` may hold the operator key instead of the file.
45
+
46
+ **Rotating the operator key.**
47
+ 1. `pregen-registry key next --dir ./data` makes the next key and prints it. Give the key id and public key to the
48
+ steward to announce in the directory.
49
+ 2. Once the directory lists it, run `pregen-registry key rotate --dir ./data` and restart.
50
+
51
+ The old key stays in `GET /keys` as `retired`, so every answer and proof it signed still verifies. A retired key
52
+ never signs again. Move its private key file offline.
53
+
54
+ ## HTTP interface
55
+
56
+ | Method and path | What |
57
+ |---|---|
58
+ | `GET /.well-known/pregen-registry.json` | who this registry is |
59
+ | `GET /keys` | its signed operator key set: every key it ever signed with, current and retired |
60
+ | `POST /v2/requests` | ask → `{"answer": <signed pg.answer.v1>}` |
61
+ | `POST /v2/reports` | report → `{"ack": <signed pg.report_ack.v1>}` |
62
+ | `POST /v2/keys`, `GET /v2/keys/{provider_id}` | provider keysets |
63
+ | `GET /v2/grants/{id}` | a signed grant |
64
+ | `GET /v2/codes/{code}` | public lookup |
65
+ | `POST /v2/sandbox/access` | sandbox credentials (sandbox mode only) |
66
+
67
+ ## Limits of this version
68
+
69
+ - **One process, SQLite, one write lock.** Correct and simple; move to Postgres with per-row
70
+ locks when throughput matters.
71
+ - **Managed subject keys are stored in the database.** Encrypt them, or use a KMS, before
72
+ holding real people.
73
+ - **Provider key recovery** (a keyset co-signed by the registry) is not implemented yet.
74
+
75
+ ## Tests
76
+
77
+ ```bash
78
+ pip install -e ".[test]" && pytest
79
+ ```
80
+
81
+ The tests cover:
82
+ - every rule of the core and of the extensions above;
83
+ - twenty concurrent jobs racing for a grant's last use;
84
+ - the byte vectors in `spec/test-vectors/messages.json`.
@@ -0,0 +1,2 @@
1
+ """pregen-registry: the reference PRE-GEN registry (spec/PRE-GEN-CORE.md)."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,97 @@
1
+ """HTTP interface (PRE-GEN-CORE.md and extensions/*.md)."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+
6
+ from fastapi import Body, FastAPI, Header, Request
7
+ from fastapi.responses import JSONResponse, PlainTextResponse
8
+
9
+ from . import __version__
10
+ from .protocol import ProtocolError
11
+ from .registry import Registry
12
+
13
+ SANDBOX_ACCESS_PER_HOUR = 10
14
+
15
+
16
+ def create_app(registry: Registry, policy_file=None) -> FastAPI:
17
+ """`policy_file`: a published policy page, served at GET /policy (text/markdown) when it exists."""
18
+ app = FastAPI(title=f"PRE-GEN registry — {registry.config.name}", version=__version__,
19
+ docs_url="/docs", redoc_url=None)
20
+ issued: dict[str, list[float]] = {} # sandbox credentials per client address, last hour
21
+
22
+ @app.exception_handler(ProtocolError)
23
+ def protocol_error(_: Request, e: ProtocolError):
24
+ return JSONResponse({"error": e.code, "error_description": e.detail, **e.extra}, status_code=e.status)
25
+
26
+ @app.get("/.well-known/pregen-registry.json")
27
+ def document():
28
+ return registry.document()
29
+
30
+ @app.get("/keys")
31
+ def keys():
32
+ return registry.key_set()
33
+
34
+ @app.get("/policy")
35
+ def policy():
36
+ if not (policy_file and policy_file.exists()):
37
+ raise ProtocolError("PG_NOT_FOUND", "no policy.md in this registry's data folder", status=404)
38
+ return PlainTextResponse(policy_file.read_text(encoding="utf-8"), media_type="text/markdown; charset=utf-8")
39
+
40
+ @app.post("/v2/requests")
41
+ def requests(env=Body(...), x_provider_id: str = Header(""), authorization: str | None = Header(None)):
42
+ return registry.request(x_provider_id, authorization, env)
43
+
44
+ @app.post("/v2/reports")
45
+ def reports(env=Body(...), x_provider_id: str = Header(""), authorization: str | None = Header(None)):
46
+ return registry.report(x_provider_id, authorization, env)
47
+
48
+ @app.post("/v2/keys")
49
+ def post_keys(env=Body(...), x_provider_id: str = Header(""), authorization: str | None = Header(None)):
50
+ return registry.post_keyset(x_provider_id, authorization, env)
51
+
52
+ @app.get("/v2/keys/{provider_id}")
53
+ def get_keys(provider_id: str):
54
+ return registry.get_keysets(provider_id)
55
+
56
+ @app.get("/v2/grants/{grant_id}")
57
+ def grant(grant_id: str, x_provider_id: str = Header(""), authorization: str | None = Header(None)):
58
+ if not registry.config.sandbox:
59
+ registry.authenticate(x_provider_id, authorization)
60
+ return registry.grant(grant_id)
61
+
62
+ @app.get("/v2/codes/{code}")
63
+ def lookup(code: str):
64
+ return registry.lookup(code)
65
+
66
+ @app.get("/v2/anchors")
67
+ def anchors():
68
+ return registry.anchors()
69
+
70
+ @app.get("/v2/catalog")
71
+ def catalog():
72
+ return registry.catalog()
73
+
74
+ @app.get("/v2/statement")
75
+ def statement(x_provider_id: str = Header(""), authorization: str | None = Header(None)):
76
+ return registry.statement(x_provider_id, authorization)
77
+
78
+ @app.get("/v2/proofs/{short_id}")
79
+ def proof(short_id: str):
80
+ return registry.proof(short_id)
81
+
82
+ @app.post("/v2/sandbox/access")
83
+ def sandbox_access(request: Request):
84
+ """extensions/sandbox.md: credentials without an account — only in a sandbox, which holds no real people."""
85
+ if not registry.config.sandbox:
86
+ raise ProtocolError("PG_NOT_FOUND", "this registry is not a sandbox", status=404)
87
+ who, now = request.client.host if request.client else "?", time.time()
88
+ recent = [t for t in issued.get(who, []) if now - t < 3600]
89
+ if len(recent) >= SANDBOX_ACCESS_PER_HOUR:
90
+ raise ProtocolError("PG_RATE_LIMITED", "too many sandbox credentials from this address; try later",
91
+ status=429)
92
+ issued[who] = [*recent, now]
93
+ provider_id, token = registry.add_provider()
94
+ return {"provider_id": provider_id, "token": token, "registry": registry.document()["api"],
95
+ "note": "Sandbox only: test subjects, no real people. Keep the token secret; it is shown once."}
96
+
97
+ return app
@@ -0,0 +1,129 @@
1
+ """pregen-registry check: a registry's live self-test, from the outside, as a provider and a verifier see it.
2
+
3
+ It checks the registry document, the signed key set, the error shape of an unauthenticated request and, given the
4
+ directory and its steward key, that the steward lists this registry with its current key. With a provider credential
5
+ and a subject code, it also asks and checks the answer as a provider must (core rule 5). It changes nothing.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import secrets
11
+ import time
12
+ import urllib.error
13
+ import urllib.request
14
+ from email.utils import parsedate_to_datetime
15
+
16
+ import pregen
17
+
18
+ EXTENSIONS_NEEDED = ("reports", "provider-keys")
19
+
20
+
21
+ def _get(url, headers=None):
22
+ with urllib.request.urlopen(urllib.request.Request(url, headers={"Accept": "application/json"}), timeout=10) as r:
23
+ if headers is not None:
24
+ headers["Date"] = r.headers.get("Date") # HTTPMessage looks names up in any case
25
+ return json.loads(r.read())
26
+
27
+
28
+ def _post(url, env, headers):
29
+ req = urllib.request.Request(url, data=json.dumps(env).encode(), method="POST",
30
+ headers={"Content-Type": "application/json", **headers})
31
+ try:
32
+ with urllib.request.urlopen(req, timeout=10) as r:
33
+ return r.status, json.loads(r.read())
34
+ except urllib.error.HTTPError as e:
35
+ return e.code, json.loads(e.read() or b"{}")
36
+
37
+
38
+ def check(api: str, directory_url: str | None = None, steward: str | None = None, provider_id: str | None = None,
39
+ token: str | None = None, subject: str | None = None, purpose: str = "commercial", licensee: str = ""):
40
+ """Yields (ok, what) lines."""
41
+ api = api.rstrip("/")
42
+ served = {}
43
+ try:
44
+ doc = _get(api + "/.well-known/pregen-registry.json", served)
45
+ except Exception as e: # noqa: BLE001 — any failure to reach it is the finding
46
+ yield False, f"GET {api}/.well-known/pregen-registry.json: {e}"
47
+ return
48
+ if served.get("Date"): # answers and give-back windows are timed by its clock
49
+ skew = round(parsedate_to_datetime(served["Date"]).timestamp() - time.time())
50
+ yield abs(skew) <= 60, f"the registry's clock is {abs(skew)} s {'ahead of' if skew > 0 else 'behind'} this one"
51
+ missing = [k for k in ("prefix", "name", "api", "keys", "profiles", "extensions", "policy", "complaints", "sandbox")
52
+ if k not in doc]
53
+ yield not missing, "registry document" + (f": missing {missing}" if missing else
54
+ f": prefix {doc['prefix']}, profiles {doc['profiles']}")
55
+ yield doc.get("api", "").rstrip("/") == api, f"document api is {doc.get('api')!r}"
56
+ yield "likeness/1" in doc.get("profiles", []), "answers under likeness/1"
57
+ yield all(x in doc.get("extensions", []) for x in EXTENSIONS_NEEDED), f"declares {', '.join(EXTENSIONS_NEEDED)}"
58
+ try:
59
+ with urllib.request.urlopen(doc.get("policy", ""), timeout=10) as r:
60
+ yield r.status == 200, f"the policy page answers: {doc.get('policy')}"
61
+ except Exception as e: # noqa: BLE001
62
+ yield False, f"the policy page does not answer: {doc.get('policy')!r} ({e})"
63
+ try:
64
+ ks = _get(doc["keys"])
65
+ except Exception as e: # noqa: BLE001
66
+ yield False, f"GET {doc.get('keys')}: {e}"
67
+ return
68
+ keys = ks.get("keys") or []
69
+ current = next((k for k in keys if k.get("key_id") == ks.get("current_key_id")), None)
70
+ yield current is not None, f"key set: current key {ks.get('current_key_id')}, {len(keys)} key(s) in its history"
71
+ if current is None:
72
+ return
73
+ good = True
74
+ for k in keys:
75
+ try:
76
+ pregen.check_public_key(k["public_key_hex"])
77
+ good &= pregen.fingerprint(k["public_key_hex"]) == k["key_id"]
78
+ except (pregen.PregenError, KeyError):
79
+ good = False
80
+ yield good, "every key id is its key's fingerprint, and no key is small-order"
81
+ yield pregen.verify_signed(ks, current["public_key_hex"], "signature"), "key set signed by its current key"
82
+ from .registry import mint_code
83
+ probe = {"subject_ref": mint_code(doc.get("prefix", "TEST"), 1), "provider_id": "pregen-check-nobody",
84
+ "profile": "likeness/1", "use": {"purpose": "commercial"}, "job_id": "pregen-check", "job_hash": "0" * 64}
85
+ status, err = _post(api + "/v2/requests", pregen.sign_envelope("pg.request.v1", probe),
86
+ {"X-Provider-ID": "pregen-check-nobody", "Authorization": "Bearer " + secrets.token_hex(8)})
87
+ yield status == 401 and err.get("error") == "PG_NOT_AUTHENTICATED", \
88
+ f"a request with an unknown credential is refused: HTTP {status} {err.get('error')}"
89
+ if "identity" in doc.get("extensions", []): # a hidden list would hide an opt-out from every provider
90
+ try:
91
+ env = _get(api + "/v2/anchors")
92
+ b = env.get("body") or {}
93
+ signed = env.get("type") == "pg.anchors.v1" and b.get("registry") == doc.get("prefix") and \
94
+ [s.get("key_id") for s in b.get("signers", [])] == [current["key_id"]] and \
95
+ pregen.verify_bytes(current["public_key_hex"], (env.get("signatures") or [""])[0],
96
+ pregen.signing_input(env["type"], b))
97
+ yield signed, f"anchors list signed by the current key: {len(b.get('anchors') or [])} public person(s)"
98
+ except Exception as e: # noqa: BLE001
99
+ yield False, f"GET {api}/v2/anchors: {e}"
100
+ directory = None
101
+ if directory_url:
102
+ try:
103
+ directory = pregen.load_directory(directory_url, **({"steward_public_key_hex": steward} if steward else {}))
104
+ except Exception as e: # noqa: BLE001
105
+ yield False, f"directory {directory_url}: {e}"
106
+ return
107
+ entry = next((r for r in directory.registries if r["prefix"] == doc.get("prefix")), None)
108
+ yield entry is not None, f"the directory (sequence {directory.sequence}) lists prefix {doc.get('prefix')}" + (
109
+ f" with keys {', '.join(entry['key_fingerprints'])}" if entry else "")
110
+ if entry:
111
+ yield entry["api"].rstrip("/") == api and entry["keys"] == doc["keys"], "listed with this api and keys URL"
112
+ yield current["key_id"] in entry["key_fingerprints"], "listed with the current key"
113
+ if provider_id and token and subject:
114
+ body = {"subject_ref": subject, "provider_id": provider_id, "profile": "likeness/1",
115
+ "use": {"purpose": purpose}, "job_id": "pregen-check-" + secrets.token_hex(4), "job_hash": "0" * 64,
116
+ **({"licensee_id": licensee} if licensee else {})}
117
+ request = pregen.sign_envelope("pg.request.v1", body)
118
+ status, res = _post(api + "/v2/requests", request, {"X-Provider-ID": provider_id,
119
+ "Authorization": "Bearer " + token})
120
+ answer = res.get("answer")
121
+ yield status == 200 and answer is not None, f"POST /v2/requests for {subject}, purpose {purpose}" + (
122
+ f", licensee {licensee}" if licensee else "") + f": HTTP {status}" + (
123
+ f", {answer['body']['status']} {answer['body'].get('reason') or ''}".rstrip() if answer else f" {res}")
124
+ if answer and directory:
125
+ try:
126
+ pregen.verify_answer(answer, request, directory, testing=bool(doc.get("sandbox")))
127
+ yield True, "the answer verifies through the directory (core rule 5)"
128
+ except pregen.PregenError as e:
129
+ yield False, f"the answer does not verify: {e}"