nomosprotocol 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ """nomosprotocol: NOMOS for Python.
2
+
3
+ The reference implementation of the NOMOS specifications and the developer layer on top of it.
4
+ The verifiers here are the same code the specification's published vectors are generated and
5
+ checked with, so there is no second implementation to drift from the reference.
6
+
7
+ verify_act(act, ...) NOMOS-SPEC-008 0.6.0: may this exact change be committed here?
8
+ chain.resolve(...) NOMOS-SPEC-007 rev. 1.9: resolve a key to a pinned root, for a purpose
9
+ chain.verify_revocation_list(...) NOMOS-SPEC-007 rev. 1.10: which revocations count, and since when
10
+ accept(...) be the relying party: verify, commit exactly once, receipt (NOMOS-SPEC-009)
11
+ act(...) be the carrier: discover, gather testimony, submit, get approval
12
+ witness(...) be a witness: sign one fact about one subject on request
13
+ issuer(...) publish authorities, the version in force, certificates and revocations
14
+ local_signer, generate_signer keys in this process (development); pass your own Signer for a KMS
15
+
16
+ Modules: jcs (RFC 8785), suites (NOMOS-SPEC-010), chain (NOMOS-SPEC-007), act (NOMOS-SPEC-008),
17
+ statements, accept, carrier, witness, issuer.
18
+ """
19
+ from .act import verify_act, evaluate, binding_digest
20
+ from .chain import resolve, verify_revocation_list, fingerprint
21
+ from .jcs import jcs, sha256_hex
22
+ from .statements import (
23
+ Signer, LocalSigner, local_signer, generate_signer, seeded_signer,
24
+ certify, seal, sign_testimony, sign_consent, sign_in_force, sign_revocation, sign_revocation_list,
25
+ build_act, presented_certificates, relied_kids, MAX_PRESENTED,
26
+ )
27
+ from .accept import accept, RelyingParty, MemoryStore, postgres_store, RevocationUnavailable, status_for, ACT_MEDIA_TYPE
28
+ from .carrier import act, NomosActError, fetch_document
29
+ from .witness import witness, Witness
30
+ from .issuer import issuer, Issuer
31
+
32
+ __version__ = "0.1.0"
33
+ SPECIFICATIONS = {
34
+ "NOMOS-SPEC-001": "2.2.0 + amendment 2.3.0", "NOMOS-SPEC-007": "rev. 1.10.0", "NOMOS-SPEC-008": "0.6.0",
35
+ "NOMOS-SPEC-009": "0.2.0", "NOMOS-SPEC-010": "0.2.0",
36
+ }
@@ -0,0 +1,312 @@
1
+ """accept(): the relying party, the system that makes the change.
2
+
3
+ rp = accept(relying_party_id="orders.acme.example", root=ROOT_PEM, act_endpoint="https://orders.acme.example/nomos/acts",
4
+ authorities=[{"artifact_id": "acme-purchasing", "issuer": "https://policy.acme.example",
5
+ "actions": ["purchase"], "currency_policy": "record", "in_force_seal_hash": SEAL_HASH}],
6
+ local_facts=lambda act, tx=None: {"vendor_blocked": is_blocked(act["action"]["params"]["vendor"])},
7
+ commit=lambda action, tx, act_id: create_order(tx, action),
8
+ store=postgres_store(pool.connection)) # a psycopg_pool ConnectionPool
9
+ app = rp.wsgi # Flask, Django, any WSGI server
10
+ app = rp.asgi # FastAPI/Starlette mount, any ASGI server
11
+
12
+ For every Act it runs NOMOS-SPEC-008 §6 locally (nomosprotocol.act, the reference verifier) and on
13
+ AUTHORIZED applies §8 in one transaction: record the nonce, re-read its own facts (re-verifying if
14
+ they moved), hand `commit` exactly the verified action, store the receipt and the Act. It answers
15
+ with the NOMOS-SPEC-009 §6.2 statuses and serves its discovery document (§3.1), generated from
16
+ this same configuration.
17
+
18
+ The same behaviour as @nomosprotocol/sdk's accept(), including: a duplicate that loses the race for
19
+ the nonce reads the winner's receipt only after its own transaction has ended (so a burst of
20
+ duplicates cannot exhaust a connection pool), and revocations that cannot be read are refused
21
+ with 503, never treated as "nothing revoked" (NOMOS-SPEC-007 rev. 1.10 §5.6).
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import copy
26
+ import json
27
+ import threading
28
+ from contextlib import contextmanager
29
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Protocol, Tuple
30
+
31
+ from .act import verify_act
32
+ from .chain import ts
33
+ from .statements import iso, now_utc
34
+ from . import suites
35
+
36
+ ACT_MEDIA_TYPE = "application/nomos-act+json"
37
+ STATUS = {"AUTHORIZED": 201, "ESCALATED": 202, "INCOMPLETE": 422, "DENIED": 403, "REPLAYED": 409}
38
+ WELL_KNOWN = "/.well-known/nomos-relying-party"
39
+
40
+
41
+ def status_for(decision: str) -> int:
42
+ return STATUS.get(decision, 400)
43
+
44
+
45
+ class RevocationUnavailable(Exception):
46
+ """Raise from `revocations()` when current revocation status cannot be established."""
47
+ def __init__(self, message: str, retry_after_seconds: int = 60):
48
+ super().__init__(message); self.retry_after_seconds = retry_after_seconds
49
+
50
+
51
+ class Transaction(Protocol):
52
+ tx: Any
53
+ def claim_nonce(self, nonce: str) -> bool: ...
54
+ def put_receipt(self, nonce: str, receipt: dict, act: dict) -> None: ...
55
+
56
+
57
+ class Store(Protocol):
58
+ def has_nonce(self, nonce: str) -> bool: ...
59
+ def receipt_for(self, nonce: str) -> Optional[dict]: ...
60
+ def transaction(self): ... # a context manager yielding a Transaction; rolls back on exception
61
+
62
+
63
+ class MemoryStore:
64
+ """Nonces and receipts in memory, one transaction at a time. Lost on restart, single process:
65
+ development and tests only. Use postgres_store() in production."""
66
+ def __init__(self):
67
+ self._lock = threading.Lock(); self.nonces: set = set(); self.receipts: Dict[str, dict] = {}; self.acts: Dict[str, dict] = {}
68
+
69
+ def has_nonce(self, nonce): return nonce in self.nonces
70
+ def receipt_for(self, nonce): return self.receipts.get(nonce)
71
+
72
+ @contextmanager
73
+ def transaction(self):
74
+ with self._lock:
75
+ staged, receipts, acts = set(), {}, {}
76
+ class T:
77
+ tx = None
78
+ def claim_nonce(s, n):
79
+ if n in self.nonces or n in staged: return False
80
+ staged.add(n); return True
81
+ def put_receipt(s, n, r, a): receipts[n] = r; acts[n] = a
82
+ yield T()
83
+ self.nonces |= staged; self.receipts.update(receipts); self.acts.update(acts) # only if the block completed
84
+
85
+
86
+ def postgres_store(connection: Callable[[], Any], table: str = "nomos_acts"):
87
+ """Nonces, receipts and Acts in your own Postgres, in the same transaction as your change.
88
+
89
+ `connection()` returns a context manager that yields a DB-API connection and releases it on
90
+ exit: a psycopg_pool pool's `pool.connection`, or `lambda: psycopg.connect(url)`. This store never
91
+ closes a connection itself, so a pool keeps its connections. `tx` passed to `commit` is that
92
+ connection, so your writes and the nonce commit together. The nonce is the primary key: any
93
+ number of concurrent duplicates commit exactly once."""
94
+ import re
95
+ if not re.match(r"^[a-z_][a-z0-9_]{0,62}$", table): raise ValueError(f'"{table}" is not a plain lower-case table name')
96
+ schema = f"""CREATE TABLE IF NOT EXISTS {table} (
97
+ nonce text PRIMARY KEY, act_id text NOT NULL, receipt json NOT NULL, act json NOT NULL, committed_at timestamptz NOT NULL DEFAULT now())"""
98
+
99
+ class PgStore:
100
+ def migrate(self):
101
+ with connection() as c:
102
+ with c.cursor() as cur: cur.execute(schema)
103
+ c.commit()
104
+ def _one(self, sql, args):
105
+ with connection() as c:
106
+ with c.cursor() as cur: cur.execute(sql, args); row = cur.fetchone()
107
+ c.rollback(); return row
108
+ def has_nonce(self, nonce): return self._one(f"SELECT 1 FROM {table} WHERE nonce = %s", (nonce,)) is not None
109
+ def receipt_for(self, nonce):
110
+ row = self._one(f"SELECT receipt::text FROM {table} WHERE nonce = %s", (nonce,))
111
+ return json.loads(row[0]) if row else None
112
+ @contextmanager
113
+ def transaction(self):
114
+ with connection() as c:
115
+ claimed = {"nonce": None, "done": False}
116
+ class T:
117
+ tx = c
118
+ def claim_nonce(s, n):
119
+ with c.cursor() as cur:
120
+ cur.execute(f"INSERT INTO {table} (nonce, act_id, receipt, act) VALUES (%s, '', '{{}}', '{{}}') ON CONFLICT (nonce) DO NOTHING RETURNING nonce", (n,))
121
+ won = cur.fetchone() is not None
122
+ if won: claimed["nonce"] = n
123
+ return won
124
+ def put_receipt(s, n, r, a):
125
+ if n != claimed["nonce"]: raise RuntimeError("put_receipt for a nonce this transaction did not claim")
126
+ with c.cursor() as cur:
127
+ cur.execute(f"UPDATE {table} SET act_id = %s, receipt = %s::json, act = %s::json WHERE nonce = %s",
128
+ (r["act_id"], json.dumps(r, separators=(",", ":")), json.dumps(a, separators=(",", ":")), n))
129
+ claimed["done"] = True
130
+ try:
131
+ yield T()
132
+ if claimed["nonce"] and not claimed["done"]: raise RuntimeError("the transaction claimed a nonce but stored no receipt")
133
+ c.commit()
134
+ except BaseException:
135
+ c.rollback(); raise
136
+ s = PgStore(); s.schema = schema
137
+ return s
138
+
139
+
140
+ class _LostRace(Exception): pass
141
+ class _Rollback(Exception):
142
+ def __init__(self, answer): super().__init__("rollback"); self.answer = answer
143
+
144
+
145
+ HINTS: Dict[str, Callable[[dict], str]] = {
146
+ "INCOMPLETE": lambda v: f"Missing facts that could change the outcome: {', '.join(v.get('open_facts') or [])}. Bring them as testimony from a witness certified for each claim, or as the channel the authority declares.",
147
+ "ESCALATED": lambda v: f"Needs {v.get('consents_required')} approval(s) from role {v.get('role')}. Request consent over act_digest {v.get('act_digest')} and resubmit this same Act before {v.get('retry_until')}.",
148
+ "DENIED": lambda v: f"Rule {v.get('rule') or '(default)'} refuses this action. No approval can change a denial.",
149
+ "WRONG_RELYING_PARTY": lambda v: "The Act is addressed to another system. Build it with this relying_party_id.",
150
+ "EXPIRED": lambda v: "The Act's window has passed. Build a new Act.",
151
+ "REPLAYED": lambda v: "This Act was already committed; the original receipt is attached.",
152
+ }
153
+
154
+
155
+ def _answer(verdict: dict, **extra) -> Tuple[int, Dict[str, str], dict]:
156
+ body = {k: v for k, v in verdict.items() if k != "detail"}
157
+ body.update(extra)
158
+ hint = HINTS.get(verdict["decision"])
159
+ if hint: body["hint"] = hint({**verdict, **extra})
160
+ return status_for(verdict["decision"]), {"content-type": "application/json"}, body
161
+
162
+
163
+ class RelyingParty:
164
+ def __init__(self, *, relying_party_id: str, root: str, authorities: List[dict], commit: Callable[..., Any], act_endpoint: str,
165
+ local_facts: Optional[Callable[..., dict]] = None, store: Optional[Store] = None,
166
+ max_window_seconds: int = 900, max_act_bytes: int = 1024 * 1024,
167
+ revocations: Optional[Callable[[], dict]] = None, mode: str = "enforce",
168
+ on_verdict: Optional[Callable[[dict, dict], None]] = None, document_ttl_seconds: int = 86400,
169
+ now: Callable[[], Any] = now_utc):
170
+ for a in authorities:
171
+ if a.get("currency_policy") not in ("record", "record_or_statement"): raise ValueError(f"{a.get('artifact_id')}: currency_policy must be record or record_or_statement (no default)")
172
+ if a["currency_policy"] == "record" and not a.get("in_force_seal_hash"): raise ValueError(f"{a['artifact_id']}: currency_policy record needs in_force_seal_hash")
173
+ if store is None:
174
+ import warnings
175
+ warnings.warn("nomosprotocol accept(): using the in-memory store. Nonces and receipts are lost on restart. Development only; use postgres_store() in production.")
176
+ self.relying_party_id, self.root, self.authorities, self.commit = relying_party_id, root, authorities, commit
177
+ self.act_endpoint, self.local_facts, self.store = act_endpoint, local_facts, store or MemoryStore()
178
+ self.max_window_seconds, self.max_act_bytes, self.revocations, self.mode = max_window_seconds, max_act_bytes, revocations, mode
179
+ self.on_verdict, self.document_ttl_seconds, self.now = on_verdict, document_ttl_seconds, now
180
+ from urllib.parse import urlparse
181
+ self.endpoint_path = urlparse(act_endpoint).path
182
+ self.root_kid = suites.compute_kid(root)
183
+
184
+ def document(self) -> dict:
185
+ from datetime import timedelta
186
+ return {
187
+ "nomos_document": "relying-party", "version": "1", "relying_party_id": self.relying_party_id, "act_endpoint": self.act_endpoint,
188
+ "roots": [{"kid": self.root_kid, "public_key_pem": self.root}],
189
+ "authorities": [{"artifact_id": a["artifact_id"], **({"issuer": a["issuer"]} if a.get("issuer") else {}), "actions": a["actions"],
190
+ "currency_policy": a["currency_policy"], **({"in_force_seal_hash": a["in_force_seal_hash"]} if a.get("in_force_seal_hash") else {})}
191
+ for a in self.authorities],
192
+ "max_window_seconds": self.max_window_seconds, "max_act_bytes": self.max_act_bytes,
193
+ "consent_suites": ["Ed25519", "ES256", "WebAuthn-ES256"],
194
+ "valid_until": iso(self.now() + timedelta(seconds=self.document_ttl_seconds)),
195
+ }
196
+
197
+ def _verify(self, act, authority, facts, at, seen, rev) -> dict:
198
+ return verify_act(act, relying_party_id=self.relying_party_id, root_pem=self.root, now=at,
199
+ seen_nonces={act["nonce"]} if seen else set(), currency_policy=authority["currency_policy"], local_facts=facts,
200
+ revoked_kids=rev.get("kids"), revoked_certs=rev.get("certs"), revoked_artifacts=rev.get("artifacts"),
201
+ in_force={authority["artifact_id"]: authority["in_force_seal_hash"]} if authority.get("in_force_seal_hash") else {},
202
+ max_window_seconds=self.max_window_seconds)
203
+
204
+ def handle(self, method: str, content_type: str, body: bytes) -> Tuple[int, Dict[str, str], dict]:
205
+ """The framework-neutral core: one Act in, one NOMOS-SPEC-009 §6.2 answer out."""
206
+ if method.upper() != "POST": return 405, {"allow": "POST", "content-type": "application/json"}, {"error": "POST an Act here."}
207
+ if (content_type or "").split(";")[0].strip().lower() != ACT_MEDIA_TYPE:
208
+ return 415, {"content-type": "application/json"}, {"error": f"Content-Type must be {ACT_MEDIA_TYPE}."}
209
+ if len(body) > self.max_act_bytes: return 413, {"content-type": "application/json"}, {"error": f"The Act is larger than {self.max_act_bytes} bytes."}
210
+ try: act = json.loads(body.decode("utf-8"))
211
+ except (ValueError, UnicodeDecodeError): return _answer({"decision": "MALFORMED", "reason_code": "bad_json"})
212
+ artifact_id = (((act or {}).get("authority") or {}).get("artifact") or {}).get("meta", {}).get("artifact_id") if isinstance(act, dict) else None
213
+ authority = next((a for a in self.authorities if a["artifact_id"] == artifact_id), None)
214
+ if not authority: return _answer({"decision": "NOT_ACCEPTED", "reason_code": "authority_not_accepted", "artifact_id": artifact_id})
215
+ if (act.get("action") or {}).get("type") not in authority["actions"]:
216
+ return _answer({"decision": "NOT_ACCEPTED", "reason_code": "action_not_accepted", "action_type": (act.get("action") or {}).get("type")})
217
+ try: rev = (self.revocations() if self.revocations else None) or {}
218
+ except Exception as e:
219
+ retry = e.retry_after_seconds if isinstance(e, RevocationUnavailable) else 60
220
+ return 503, {"content-type": "application/json", "retry-after": str(retry)}, {
221
+ "error": "Revocation status is not current, so nothing is committed. Resubmit this same Act later.", "detail": str(e), "retry_after": retry}
222
+ at = self.now()
223
+ facts = self.local_facts(act) if self.local_facts else {}
224
+ verdict = self._verify(act, authority, facts, at, self.store.has_nonce(act["nonce"]), rev)
225
+
226
+ def receipt_of(v, f, committed_at=None):
227
+ r = {"act_id": act["act_id"], "act_digest": v.get("act_digest", ""), "decision": v["decision"], "rule": v.get("rule"),
228
+ **({"by_consent": True} if v.get("by_consent") else {}), "verified_at": iso(at),
229
+ **({"committed_at": iso(committed_at)} if committed_at else {}), "relying_party_facts": f,
230
+ **({"in_force_source": v["in_force_source"]} if v.get("in_force_source") else {}), "currency_policy": authority["currency_policy"]}
231
+ return r
232
+
233
+ if verdict["decision"] == "REPLAYED":
234
+ return _answer(verdict, act_id=act["act_id"], receipt=self.store.receipt_for(act["nonce"]))
235
+ if verdict["decision"] != "AUTHORIZED" or self.mode == "shadow":
236
+ if self.on_verdict: self.on_verdict(verdict, receipt_of(verdict, facts))
237
+ if verdict["decision"] == "ESCALATED":
238
+ esc = next((e for e in ((act["authority"]["artifact"].get("governance") or {}).get("escalations") or []) if e.get("id") == verdict.get("escalation_id")), None)
239
+ return _answer(verdict, role=(esc or {}).get("role_required"), retry_until=act["expires_at"])
240
+ if self.mode == "shadow":
241
+ s, h, b = _answer(verdict); return 200, h, {**b, "shadow": True}
242
+ return _answer(verdict)
243
+
244
+ # SPEC-008 §8, one atomic operation.
245
+ try:
246
+ with self.store.transaction() as t:
247
+ if not t.claim_nonce(act["nonce"]): raise _LostRace()
248
+ final, final_facts = verdict, facts
249
+ if self.local_facts:
250
+ fresh = self.local_facts(act, t.tx)
251
+ if fresh != facts: # step 3: our state moved since verification
252
+ final_facts = fresh
253
+ final = self._verify(act, authority, fresh, at, False, rev)
254
+ if final["decision"] != "AUTHORIZED": raise _Rollback(_answer(final))
255
+ a = act["action"]
256
+ action = copy.deepcopy({"type": a["type"], **({"subject": a["subject"]} if "subject" in a else {}), "params": a.get("params") or {}})
257
+ result = self.commit(action, t.tx, act["act_id"])
258
+ receipt = receipt_of(final, final_facts, self.now())
259
+ t.put_receipt(act["nonce"], receipt, act)
260
+ if self.on_verdict: self.on_verdict(final, receipt)
261
+ return _answer(final, receipt=receipt, **({"result": result} if result is not None else {}))
262
+ except _Rollback as r:
263
+ return r.answer
264
+ except _LostRace:
265
+ # Read only now, after the losing transaction has ended and released its connection.
266
+ return _answer({"decision": "REPLAYED"}, act_id=act["act_id"], receipt=self.store.receipt_for(act["nonce"]))
267
+ except Exception as e:
268
+ return 500, {"content-type": "application/json"}, {"error": "The commit failed and was rolled back; nothing was applied.", "detail": str(e)}
269
+
270
+ # ── WSGI and ASGI ──────────────────────────────────────────────────────────────────────
271
+ def wsgi(self, environ, start_response):
272
+ path, method = environ.get("PATH_INFO", ""), environ.get("REQUEST_METHOD", "GET")
273
+ def send(status, headers, body):
274
+ data = json.dumps(body).encode()
275
+ start_response(f"{status} {_REASON.get(status, '')}", [*headers.items(), ("content-length", str(len(data)))])
276
+ return [data]
277
+ if method == "GET" and path == WELL_KNOWN:
278
+ return send(200, {"content-type": "application/json", "cache-control": "max-age=300"}, self.document())
279
+ if path != self.endpoint_path: return send(404, {"content-type": "application/json"}, {"error": "Not found"})
280
+ try: length = int(environ.get("CONTENT_LENGTH") or 0)
281
+ except ValueError: length = 0
282
+ body = environ["wsgi.input"].read(min(length, self.max_act_bytes + 1)) if length else b""
283
+ if length > self.max_act_bytes: body = b"x" * (self.max_act_bytes + 1)
284
+ return send(*self.handle(method, environ.get("CONTENT_TYPE", ""), body))
285
+
286
+ async def asgi(self, scope, receive, send):
287
+ if scope["type"] != "http": return
288
+ path, method = scope["path"], scope["method"]
289
+ async def reply(status, headers, body):
290
+ data = json.dumps(body).encode()
291
+ await send({"type": "http.response.start", "status": status, "headers": [(k.encode(), v.encode()) for k, v in {**headers, "content-length": str(len(data))}.items()]})
292
+ await send({"type": "http.response.body", "body": data})
293
+ if method == "GET" and path == WELL_KNOWN:
294
+ return await reply(200, {"content-type": "application/json", "cache-control": "max-age=300"}, self.document())
295
+ if path != self.endpoint_path: return await reply(404, {"content-type": "application/json"}, {"error": "Not found"})
296
+ chunks, size = [], 0
297
+ while True:
298
+ m = await receive(); b = m.get("body", b""); size += len(b)
299
+ if size <= self.max_act_bytes: chunks.append(b)
300
+ if not m.get("more_body"): break
301
+ body = b"".join(chunks) if size <= self.max_act_bytes else b"x" * (self.max_act_bytes + 1)
302
+ ctype = next((v.decode() for k, v in scope.get("headers", []) if k.decode().lower() == "content-type"), "")
303
+ import asyncio
304
+ return await reply(*(await asyncio.get_running_loop().run_in_executor(None, self.handle, method, ctype, body)))
305
+
306
+
307
+ _REASON = {200: "OK", 201: "Created", 202: "Accepted", 400: "Bad Request", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
308
+ 409: "Conflict", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Entity", 500: "Internal Server Error", 503: "Service Unavailable"}
309
+
310
+
311
+ def accept(**options) -> RelyingParty:
312
+ return RelyingParty(**options)