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.
- nomosprotocol/__init__.py +36 -0
- nomosprotocol/accept.py +312 -0
- nomosprotocol/act.py +462 -0
- nomosprotocol/carrier.py +178 -0
- nomosprotocol/chain.py +421 -0
- nomosprotocol/issuer.py +73 -0
- nomosprotocol/jcs.py +46 -0
- nomosprotocol/statements.py +191 -0
- nomosprotocol/suites.py +252 -0
- nomosprotocol/witness.py +72 -0
- nomosprotocol-0.1.0.dist-info/METADATA +121 -0
- nomosprotocol-0.1.0.dist-info/RECORD +14 -0
- nomosprotocol-0.1.0.dist-info/WHEEL +5 -0
- nomosprotocol-0.1.0.dist-info/top_level.txt +1 -0
nomosprotocol/chain.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
"""NOMOS-SPEC-007 revision 1.9 (resolution) and 1.10 (revocation sources).
|
|
2
|
+
|
|
3
|
+
One resolver for every signed object a relying party accepts: an artifact's seal (§4), and the
|
|
4
|
+
testimony, consent and in-force statements of NOMOS-SPEC-008 (§4.6). Pure: no network, no clock
|
|
5
|
+
other than the `now` it is given, no state other than the revocation sets it is given.
|
|
6
|
+
|
|
7
|
+
resolve(target_kid, pool, root_pem, now, admit, revoked_kids, revoked_certs) -> verdict
|
|
8
|
+
|
|
9
|
+
`admit` is the purpose of the resolution (§4.2a step 4): `for_artifact(...)` or
|
|
10
|
+
`for_statement(...)`. A candidate path whose effective scope the purpose does not admit is a
|
|
11
|
+
failed candidate, exactly like one with a bad signature, and the next candidate is tried.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple
|
|
18
|
+
|
|
19
|
+
from . import suites
|
|
20
|
+
from .jcs import jcs, sha256_hex
|
|
21
|
+
|
|
22
|
+
MAX_CHAIN = 20 # §4.5
|
|
23
|
+
CERT_SUITES = ("Ed25519", "ES256") # §3.1: a certificate or staple is never WebAuthn-signed
|
|
24
|
+
SEAL_SUITES = ("Ed25519", "ES256") # NOMOS-SPEC-010 §6
|
|
25
|
+
ARTIFACT_DIMS = ("artifact", "industry", "jurisdiction")
|
|
26
|
+
STATEMENT_DIMS = ("claim", "consent")
|
|
27
|
+
SET_DIMS = ("claim", "consent", "suite")
|
|
28
|
+
KNOWN_DIMS = ARTIFACT_DIMS + STATEMENT_DIMS + ("suite", "approver")
|
|
29
|
+
CERT_FIELDS = ("parent_kid", "child_kid", "child_public_key_pem", "issued_at", "expires_at", "algorithm", "signature")
|
|
30
|
+
STAPLE_FIELDS = ("child_kid", "parent_kid", "as_of", "valid_until", "algorithm", "signature")
|
|
31
|
+
ISO_3166 = re.compile(r"^[A-Z]{2}(-[A-Z0-9]{1,3})?$")
|
|
32
|
+
|
|
33
|
+
Verdict = Dict[str, Any]
|
|
34
|
+
Effective = Dict[str, str]
|
|
35
|
+
Admit = Callable[[Effective], Optional[str]]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def ts(s: str) -> datetime:
|
|
39
|
+
return datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone(timezone.utc)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ── certificates (§3) ────────────────────────────────────────────────────────────────────────
|
|
43
|
+
def cert_payload(c: dict) -> dict:
|
|
44
|
+
"""§3.2: the signed payload. `algorithm` and `signature` are not signed; `scope` is null when absent."""
|
|
45
|
+
return {k: c.get(k) for k in ("parent_kid", "child_kid", "child_public_key_pem", "issued_at", "expires_at")} | {"scope": c.get("scope")}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def fingerprint(c: dict) -> str:
|
|
49
|
+
"""§5.4: SHA-256 over the canonical signed payload, hex. Never over the signature."""
|
|
50
|
+
return sha256_hex(jcs(cert_payload(c)))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def staple_payload(s: dict) -> dict:
|
|
54
|
+
return {k: s.get(k) for k in ("child_kid", "parent_kid", "as_of", "valid_until")}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def check_pool(pool: Any) -> Optional[str]:
|
|
58
|
+
"""§4.4-4.5 shape gates, applied before any cryptographic work. Returns a reason or None."""
|
|
59
|
+
if not isinstance(pool, list): return "bad_chain"
|
|
60
|
+
if len(pool) > MAX_CHAIN: return "chain_over_length_cap"
|
|
61
|
+
for c in pool:
|
|
62
|
+
if not isinstance(c, dict) or not all(isinstance(c.get(k), str) and c.get(k) for k in CERT_FIELDS):
|
|
63
|
+
return "bad_certificate"
|
|
64
|
+
if c["algorithm"] not in CERT_SUITES: return "bad_certificate"
|
|
65
|
+
if c.get("scope") is not None and not isinstance(c.get("scope"), str): return "bad_certificate"
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def check_staples(staples: Any) -> Optional[str]:
|
|
70
|
+
if staples is None: return None
|
|
71
|
+
if not isinstance(staples, list) or len(staples) > MAX_CHAIN: return "bad_staples"
|
|
72
|
+
for s in staples:
|
|
73
|
+
if not isinstance(s, dict) or not all(isinstance(s.get(k), str) and s.get(k) for k in STAPLE_FIELDS):
|
|
74
|
+
return "bad_staple"
|
|
75
|
+
if s["algorithm"] not in CERT_SUITES: return "bad_staple"
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# ── scope (§3.4, §3.4.1, §3.6, §3.7) ─────────────────────────────────────────────────────────
|
|
80
|
+
class ScopeError(Exception):
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _set(v: str) -> Set[str]: return set(v.split(","))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def parse_scope(s: Optional[str]) -> List[Tuple[str, str]]:
|
|
88
|
+
"""A scope string, parsed whole or rejected whole. Never partially applied."""
|
|
89
|
+
if s is None or not s.strip(): return []
|
|
90
|
+
out, seen = [], set()
|
|
91
|
+
for term in s.split():
|
|
92
|
+
d, sep, v = term.partition(":")
|
|
93
|
+
if not sep or not d or not v or d in seen: raise ScopeError(term)
|
|
94
|
+
seen.add(d)
|
|
95
|
+
if d in SET_DIMS:
|
|
96
|
+
members = v.split(",")
|
|
97
|
+
if "" in members or len(set(members)) != len(members): raise ScopeError(term)
|
|
98
|
+
if d == "suite":
|
|
99
|
+
if any(m not in suites.SUITES for m in members): raise ScopeError(term)
|
|
100
|
+
# §3.6: a key permitted WebAuthn-ES256 is permitted nothing else, so an enrolled
|
|
101
|
+
# passkey can only ever approve.
|
|
102
|
+
if "WebAuthn-ES256" in members and len(members) > 1: raise ScopeError(term)
|
|
103
|
+
if d == "approver" and "," in v: raise ScopeError(term)
|
|
104
|
+
out.append((d, v))
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def contains(dim: str, outer: str, inner: str) -> bool:
|
|
109
|
+
"""Does the grant `outer` cover `inner` on this dimension? Used for both narrowing and matching."""
|
|
110
|
+
if dim == "artifact": return outer == inner
|
|
111
|
+
if dim == "industry": return inner == outer or inner.startswith(outer + "/")
|
|
112
|
+
if dim == "jurisdiction": return inner == outer or (len(outer) == 2 and inner.startswith(outer + "-"))
|
|
113
|
+
if dim in SET_DIMS: return _set(inner) <= _set(outer)
|
|
114
|
+
if dim == "approver": return outer == inner
|
|
115
|
+
return False # unknown dimension: never narrows, never matches
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def meta_matches(dim: str, val: str, meta: dict) -> bool:
|
|
119
|
+
if dim == "artifact": return meta.get("artifact_id") == val
|
|
120
|
+
if dim == "industry":
|
|
121
|
+
ind = meta.get("industry")
|
|
122
|
+
return isinstance(ind, str) and bool(ind) and contains("industry", val, ind)
|
|
123
|
+
if dim == "jurisdiction":
|
|
124
|
+
cs = meta.get("jurisdiction_codes")
|
|
125
|
+
if not isinstance(cs, list) or not cs or not all(isinstance(c, str) and ISO_3166.match(c) for c in cs): return False
|
|
126
|
+
return all(contains("jurisdiction", val, c) for c in cs)
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def suite_permitted(effective: Effective, suite: str) -> bool:
|
|
131
|
+
"""§3.6: without a `suite` term a key may use any suite but WebAuthn-ES256."""
|
|
132
|
+
if "suite" in effective: return suite in _set(effective["suite"])
|
|
133
|
+
return suite != "WebAuthn-ES256"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def format_scope(effective: Effective) -> str:
|
|
137
|
+
return " ".join(f"{d}:{v}" for d, v in effective.items())
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ── purposes (§4.2a step 4) ──────────────────────────────────────────────────────────────────
|
|
141
|
+
# Each term of the effective scope is examined in effective-scope order and the first that does
|
|
142
|
+
# not admit the purpose is the reported dimension (§3.8). A statement checks its own kind first.
|
|
143
|
+
def _term_fails(d: str, v: str, meta: dict, suite: str, allowed: Tuple[str, ...]) -> bool:
|
|
144
|
+
if d in ARTIFACT_DIMS: return not meta_matches(d, v, meta)
|
|
145
|
+
if d == "suite": return suite not in _set(v)
|
|
146
|
+
return d not in allowed # statement dimensions off-purpose, or unknown: fail closed
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _default_suite_fails(effective: Effective, suite: str) -> bool:
|
|
150
|
+
return "suite" not in effective and not suite_permitted(effective, suite)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def for_artifact(meta: dict, suite: str) -> Admit:
|
|
154
|
+
"""§3.4, §3.5, §3.6: may this key seal this artifact, under this suite?"""
|
|
155
|
+
def admit(effective: Effective) -> Optional[str]:
|
|
156
|
+
for d, v in effective.items():
|
|
157
|
+
if _term_fails(d, v, meta, suite, ()): return d
|
|
158
|
+
return "suite" if _default_suite_fails(effective, suite) else None
|
|
159
|
+
return admit
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def for_statement(kind: str, name: str, meta: dict, suite: str, required: Tuple[str, ...] = ()) -> Admit:
|
|
163
|
+
"""§3.4.1, §3.6, §3.7: may this key sign a `kind` statement about `name`, under this suite,
|
|
164
|
+
for an act whose authority artifact carries `meta`? `required` names dimensions the calling
|
|
165
|
+
specification requires on the key (NOMOS-SPEC-008 0.6.0 requires `approver` on consent keys);
|
|
166
|
+
a path whose scope lacks one is refused on that dimension, like any other refusal."""
|
|
167
|
+
allowed = (kind, "approver") if kind == "consent" else (kind,)
|
|
168
|
+
def admit(effective: Effective) -> Optional[str]:
|
|
169
|
+
if kind not in effective or name not in _set(effective[kind]): return kind
|
|
170
|
+
for d in required:
|
|
171
|
+
if d not in effective: return d
|
|
172
|
+
for d, v in effective.items():
|
|
173
|
+
if _term_fails(d, v, meta, suite, allowed): return d
|
|
174
|
+
return "suite" if _default_suite_fails(effective, suite) else None
|
|
175
|
+
return admit
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ── resolution (§4.2a) ───────────────────────────────────────────────────────────────────────
|
|
179
|
+
def _candidates(target: str, root: str, pool: list, on_path: frozenset, depth: int = 0) -> Iterator[list]:
|
|
180
|
+
"""Root-to-target certificate lists, enumerated from the target, in fingerprint order."""
|
|
181
|
+
if target == root:
|
|
182
|
+
yield []
|
|
183
|
+
return
|
|
184
|
+
if depth >= MAX_CHAIN or target in on_path: return
|
|
185
|
+
for c in sorted((c for c in pool if c.get("child_kid") == target), key=fingerprint):
|
|
186
|
+
for head in _candidates(c.get("parent_kid"), root, pool, on_path | {target}, depth + 1):
|
|
187
|
+
yield head + [c]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _fail(decision: str, **kw) -> Verdict:
|
|
191
|
+
return {"decision": decision, **kw}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _sig_ok(cert: dict, parent_pem: str, memo: Optional[dict]) -> Tuple[bool, Optional[str]]:
|
|
195
|
+
"""A certificate's signature under its parent, verified once per resolution (§4.5 bounds the
|
|
196
|
+
candidates; this bounds the cost of each)."""
|
|
197
|
+
k = (fingerprint(cert), cert["signature"], cert["algorithm"], parent_pem)
|
|
198
|
+
if memo is not None and k in memo: return memo[k]
|
|
199
|
+
r = suites.verify(cert["algorithm"], parent_pem, jcs(cert_payload(cert)), {"signature": cert["signature"]})
|
|
200
|
+
if memo is not None: memo[k] = r
|
|
201
|
+
return r
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _validate(path: list, root_pem: str, now: datetime, admit: Admit,
|
|
205
|
+
revoked_kids: Set[str], revoked_certs: Set[str], memo: Optional[dict] = None) -> Verdict:
|
|
206
|
+
cur_pem, effective = root_pem, {}
|
|
207
|
+
hops = []
|
|
208
|
+
for cert in path:
|
|
209
|
+
ktype, _, reason = suites.load_key(cert["child_public_key_pem"])
|
|
210
|
+
if reason: return _fail("ISSUER_NOT_RECOGNIZED", reason_code="invalid_key")
|
|
211
|
+
if suites.compute_kid(cert["child_public_key_pem"]) != cert["child_kid"]:
|
|
212
|
+
return _fail("ISSUER_NOT_RECOGNIZED", reason_code="kid_mismatch")
|
|
213
|
+
if not suite_permitted(effective, cert["algorithm"]):
|
|
214
|
+
return _fail("OUT_OF_SCOPE", dimension="suite", reason_code="suite_not_permitted")
|
|
215
|
+
ok, why = _sig_ok(cert, cur_pem, memo)
|
|
216
|
+
if not ok: return _fail("ISSUER_NOT_RECOGNIZED", reason_code=why)
|
|
217
|
+
try:
|
|
218
|
+
issued, expires = ts(cert["issued_at"]), ts(cert["expires_at"])
|
|
219
|
+
except (ValueError, TypeError):
|
|
220
|
+
return _fail("ISSUER_NOT_RECOGNIZED", reason_code="bad_time")
|
|
221
|
+
if now > expires: return _fail("ISSUER_NOT_RECOGNIZED", reason_code="expired")
|
|
222
|
+
if now < issued: return _fail("ISSUER_NOT_RECOGNIZED", reason_code="not_yet_valid")
|
|
223
|
+
fp = fingerprint(cert)
|
|
224
|
+
if fp in revoked_certs: return _fail("CERTIFICATE_REVOKED", revoked_fingerprint=fp)
|
|
225
|
+
if cert["child_kid"] in revoked_kids: return _fail("KEY_REVOKED", revoked_kid=cert["child_kid"])
|
|
226
|
+
try:
|
|
227
|
+
terms = parse_scope(cert.get("scope"))
|
|
228
|
+
except ScopeError:
|
|
229
|
+
return _fail("OUT_OF_SCOPE", reason_code="malformed_scope")
|
|
230
|
+
narrowed = dict(effective)
|
|
231
|
+
for d, v in terms:
|
|
232
|
+
if d in effective and not contains(d, effective[d], v):
|
|
233
|
+
return _fail("OUT_OF_SCOPE", dimension=d, reason_code="widening")
|
|
234
|
+
narrowed[d] = v
|
|
235
|
+
hops.append({"cert": cert, "parent_pem": cur_pem, "parent_effective": effective})
|
|
236
|
+
cur_pem, effective = cert["child_public_key_pem"], narrowed
|
|
237
|
+
dim = admit(effective)
|
|
238
|
+
if dim is not None: return _fail("OUT_OF_SCOPE", dimension=dim)
|
|
239
|
+
return {"decision": "RESOLVED", "key": cur_pem, "effective": effective, "hops": hops}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def resolve(target_kid: str, pool: list, root_pem: str, now: datetime, admit: Admit,
|
|
243
|
+
revoked_kids: Optional[Set[str]] = None, revoked_certs: Optional[Set[str]] = None,
|
|
244
|
+
all_paths: bool = False) -> Verdict:
|
|
245
|
+
"""§4.2a. `pool` must already have passed check_pool. On success the verdict carries the
|
|
246
|
+
resolved key, its effective scope, the kids on the path (root first) and the hops. With
|
|
247
|
+
`all_paths`, every candidate is tried and `admitted` lists the effective scope of each one
|
|
248
|
+
that validates (NOMOS-SPEC-008 0.6.0 §4.4 reads it to make the approver path-independent);
|
|
249
|
+
the first, in fingerprint order, is still the one reported."""
|
|
250
|
+
revoked_kids = revoked_kids or set()
|
|
251
|
+
revoked_certs = revoked_certs or set()
|
|
252
|
+
_, _, reason = suites.load_key(root_pem)
|
|
253
|
+
if reason: return _fail("MALFORMED", reason_code="bad_root")
|
|
254
|
+
root_kid = suites.compute_kid(root_pem)
|
|
255
|
+
if root_kid in revoked_kids: return _fail("KEY_REVOKED", revoked_kid=root_kid)
|
|
256
|
+
first_failure, first_resolved, admitted = None, None, []
|
|
257
|
+
memo: dict = {}
|
|
258
|
+
for path in _candidates(target_kid, root_kid, pool, frozenset()):
|
|
259
|
+
r = _validate(path, root_pem, now, admit, revoked_kids, revoked_certs, memo)
|
|
260
|
+
if r["decision"] == "RESOLVED":
|
|
261
|
+
r["path"] = [root_kid] + [c["child_kid"] for c in path]
|
|
262
|
+
if not all_paths: return r
|
|
263
|
+
first_resolved = first_resolved or r
|
|
264
|
+
admitted.append(r["effective"])
|
|
265
|
+
continue
|
|
266
|
+
first_failure = first_failure or r
|
|
267
|
+
if first_resolved:
|
|
268
|
+
first_resolved["admitted"] = admitted # the effective scope of every admitted path
|
|
269
|
+
return first_resolved
|
|
270
|
+
if first_failure: return first_failure
|
|
271
|
+
from_root = any(c.get("parent_kid") == root_kid for c in pool)
|
|
272
|
+
return _fail("ISSUER_NOT_RECOGNIZED", reason_code="chain_broken" if from_root else "no_certificate_for_root")
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
# ── the artifact's own seal (NOMOS-SPEC-001 §8, NOMOS-SPEC-010 §6) ──────────────────────────
|
|
276
|
+
def check_seal_shape(artifact: Any) -> Optional[str]:
|
|
277
|
+
if not isinstance(artifact, dict): return "bad_artifact"
|
|
278
|
+
seal = artifact.get("seal")
|
|
279
|
+
if not isinstance(seal, dict) or seal.get("status") != "sealed" or not all(isinstance(seal.get(k), str) for k in ("hash", "signature", "kid")):
|
|
280
|
+
return "unsealed_artifact"
|
|
281
|
+
if seal.get("signature_algorithm") not in SEAL_SUITES: return "seal_algorithm"
|
|
282
|
+
return None
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def seal_failure(artifact: dict, key_pem: str) -> Optional[Verdict]:
|
|
286
|
+
"""None if the seal verifies under the resolved key; otherwise the SEAL_INVALID verdict."""
|
|
287
|
+
seal = artifact["seal"]
|
|
288
|
+
body = {k: v for k, v in artifact.items() if k not in ("seal", "attestations")}
|
|
289
|
+
if sha256_hex(jcs(body)) != seal["hash"]: return _fail("SEAL_INVALID", reason_code="hash_mismatch")
|
|
290
|
+
ok, why = suites.verify(seal["signature_algorithm"], key_pem,
|
|
291
|
+
jcs({"hash": seal["hash"], "signed_by": seal.get("signed_by")}), {"signature": seal["signature"]})
|
|
292
|
+
return None if ok else _fail("SEAL_INVALID", reason_code=why)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# ── freshness staples (§5.5) ─────────────────────────────────────────────────────────────────
|
|
296
|
+
def staple_confidence(resolved: Verdict, staples: Optional[list], now: datetime) -> str:
|
|
297
|
+
"""§5.5 for a verifier with no revocation source of its own: the weakest link along the
|
|
298
|
+
resolved path. The root is never staple-coverable and is not counted (§5.5, FINDINGS)."""
|
|
299
|
+
levels = []
|
|
300
|
+
for hop in resolved["hops"]:
|
|
301
|
+
cert = hop["cert"]
|
|
302
|
+
covered = False
|
|
303
|
+
for s in staples or []:
|
|
304
|
+
if s["child_kid"] != cert["child_kid"] or s["parent_kid"] != cert["parent_kid"]: continue
|
|
305
|
+
if not suite_permitted(hop["parent_effective"], s["algorithm"]): continue
|
|
306
|
+
try:
|
|
307
|
+
if not ts(s["as_of"]) <= now <= ts(s["valid_until"]): continue
|
|
308
|
+
except (ValueError, TypeError):
|
|
309
|
+
continue
|
|
310
|
+
if suites.verify(s["algorithm"], hop["parent_pem"], jcs(staple_payload(s)), {"signature": s["signature"]})[0]:
|
|
311
|
+
covered = True
|
|
312
|
+
break
|
|
313
|
+
levels.append("staple" if covered else "unchecked")
|
|
314
|
+
return "unchecked" if not levels or "unchecked" in levels else "staple"
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
# ── revocation sources (rev. 1.10 §5.1, §5.1a, §5.3, §5.3a) ──────────────────────────────────
|
|
318
|
+
REVOCATION_SUITES = ("Ed25519", "ES256")
|
|
319
|
+
MAX_LIST_CERTS = 1000
|
|
320
|
+
_FP = re.compile(r"^[0-9a-f]{64}$")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def revocation_payload(st: dict) -> dict:
|
|
324
|
+
"""§5.1: the field name says what is revoked, so one kind can never be read as the other."""
|
|
325
|
+
if "revoked_fingerprint" in st:
|
|
326
|
+
return {"revoked_fingerprint": st["revoked_fingerprint"], "reason": st["reason"], "issued_at": st["issued_at"]}
|
|
327
|
+
return {"revoked_kid": st["revoked_kid"], "reason": st["reason"], "issued_at": st["issued_at"]}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def revocation_list_payload(lst: dict) -> dict:
|
|
331
|
+
return {"generated_at": lst["generated_at"], "statements": lst["statements"]}
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def for_signing(suite: str) -> Admit:
|
|
335
|
+
"""The purpose of a key that signs a revocation statement or a list: any effective scope that
|
|
336
|
+
permits the suite (§3.6). Authority to revoke is authority to certify."""
|
|
337
|
+
def admit(effective: Effective) -> Optional[str]:
|
|
338
|
+
return None if suite_permitted(effective, suite) else "suite"
|
|
339
|
+
return admit
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _unique(certs: list) -> list:
|
|
343
|
+
seen, out = set(), []
|
|
344
|
+
for c in certs:
|
|
345
|
+
fp = fingerprint(c)
|
|
346
|
+
if fp not in seen: seen.add(fp); out.append(c)
|
|
347
|
+
return out
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _signer_pem(kid: str, pool: list, root_pem: str, at: datetime, suite: str,
|
|
351
|
+
revoked_kids: Set[str], revoked_certs: Set[str]) -> Optional[str]:
|
|
352
|
+
"""The signer's key if it is the root or resolves to it (§4.2a) at `at`, else None."""
|
|
353
|
+
r = resolve(kid, pool, root_pem, at, for_signing(suite), revoked_kids, revoked_certs)
|
|
354
|
+
return r["key"] if r["decision"] == "RESOLVED" else None
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def evaluate_statement(st: Any, pool: list, root_pem: str, now: datetime) -> Optional[str]:
|
|
358
|
+
"""§5.1a. None if the statement counts, else the first rule it fails."""
|
|
359
|
+
if not isinstance(st, dict): return "bad_statement"
|
|
360
|
+
has_kid, has_fp = "revoked_kid" in st, "revoked_fingerprint" in st
|
|
361
|
+
if has_kid == has_fp: return "bad_statement"
|
|
362
|
+
target = st.get("revoked_kid") if has_kid else st.get("revoked_fingerprint")
|
|
363
|
+
if not isinstance(target, str) or not target: return "bad_statement"
|
|
364
|
+
if has_fp and not _FP.match(target): return "bad_statement"
|
|
365
|
+
if not isinstance(st.get("reason"), str): return "bad_statement"
|
|
366
|
+
if not all(isinstance(st.get(f), str) and st.get(f) for f in ("issued_at", "kid", "algorithm", "signature")): return "bad_statement"
|
|
367
|
+
if st["algorithm"] not in REVOCATION_SUITES: return "bad_statement"
|
|
368
|
+
try:
|
|
369
|
+
issued = ts(st["issued_at"])
|
|
370
|
+
except (ValueError, TypeError):
|
|
371
|
+
return "bad_statement"
|
|
372
|
+
if issued > now: return "bad_statement"
|
|
373
|
+
# rule 2: the revoked object, certified by this parent
|
|
374
|
+
certs = [c for c in pool if c.get("parent_kid") == st["kid"] and
|
|
375
|
+
(c.get("child_kid") == target if has_kid else fingerprint(c) == target)]
|
|
376
|
+
if not certs: return "no_certificate"
|
|
377
|
+
# rule 3: the parent is recognized from the root, at issued_at, revocation not consulted
|
|
378
|
+
parent = _signer_pem(st["kid"], pool, root_pem, issued, st["algorithm"], set(), set())
|
|
379
|
+
if parent is None: return "signer_not_recognized"
|
|
380
|
+
# rule 4: the parent made the certificate
|
|
381
|
+
if not any(suites.verify(c["algorithm"], parent, jcs(cert_payload(c)), {"signature": c["signature"]})[0] for c in certs):
|
|
382
|
+
return "bad_certificate_signature"
|
|
383
|
+
# rule 5: the parent signed the statement
|
|
384
|
+
ok, _ = suites.verify(st["algorithm"], parent, jcs(revocation_payload(st)), {"signature": st["signature"]})
|
|
385
|
+
return None if ok else "bad_signature"
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def verify_revocation_list(lst: Any, root_pem: str, now: datetime, own_certs: Optional[list] = None) -> dict:
|
|
389
|
+
"""§5.3a. Returns {decision, revoked_kids, revoked_certs, as_of?, ignored} with sorted lists."""
|
|
390
|
+
if (not isinstance(lst, dict) or not all(isinstance(lst.get(f), str) for f in ("generated_at", "kid", "algorithm", "signature"))
|
|
391
|
+
or not isinstance(lst.get("statements"), list)):
|
|
392
|
+
return {"decision": "MALFORMED", "reason_code": "bad_list"}
|
|
393
|
+
extra = lst.get("key_certs", [])
|
|
394
|
+
if not isinstance(extra, list) or len(extra) > MAX_LIST_CERTS: return {"decision": "MALFORMED", "reason_code": "bad_list_certs"}
|
|
395
|
+
if extra and check_pool_unbounded(extra) is not None: return {"decision": "MALFORMED", "reason_code": "bad_list_certs"}
|
|
396
|
+
pool = _unique(list(extra) + list(own_certs or []))
|
|
397
|
+
kids, fps, ignored = set(), set(), []
|
|
398
|
+
for i, st in enumerate(lst["statements"]):
|
|
399
|
+
why = evaluate_statement(st, pool, root_pem, now)
|
|
400
|
+
if why: ignored.append({"index": i, "reason": why}); continue
|
|
401
|
+
(kids if "revoked_kid" in st else fps).add(st.get("revoked_kid") or st.get("revoked_fingerprint"))
|
|
402
|
+
out = {"decision": "OK", "revoked_kids": sorted(kids), "revoked_certs": sorted(fps), "ignored": ignored}
|
|
403
|
+
try:
|
|
404
|
+
generated = ts(lst["generated_at"])
|
|
405
|
+
except (ValueError, TypeError):
|
|
406
|
+
return out
|
|
407
|
+
if generated > now or lst["algorithm"] not in REVOCATION_SUITES: return out
|
|
408
|
+
signer = _signer_pem(lst["kid"], pool, root_pem, generated, lst["algorithm"], kids, fps)
|
|
409
|
+
if signer and suites.verify(lst["algorithm"], signer, jcs(revocation_list_payload(lst)), {"signature": lst["signature"]})[0]:
|
|
410
|
+
out["as_of"] = lst["generated_at"]
|
|
411
|
+
return out
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def check_pool_unbounded(pool: list) -> Optional[str]:
|
|
415
|
+
"""check_pool's shape rules without the 20-certificate presentation bound (a list's own bound
|
|
416
|
+
is MAX_LIST_CERTS)."""
|
|
417
|
+
for c in pool:
|
|
418
|
+
if not isinstance(c, dict) or not all(isinstance(c.get(f), str) and c.get(f) for f in CERT_FIELDS) or c.get("algorithm") not in CERT_SUITES:
|
|
419
|
+
return "bad_certificate"
|
|
420
|
+
if c.get("scope") is not None and not isinstance(c.get("scope"), str): return "bad_certificate"
|
|
421
|
+
return None
|
nomosprotocol/issuer.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""issuer(): publish your sealed authorities, the version of each in force, your certificate pool
|
|
2
|
+
and your revocation list (NOMOS-SPEC-009 §3.2, NOMOS-SPEC-008 §5.4, NOMOS-SPEC-007 rev. 1.10 §5.3).
|
|
3
|
+
|
|
4
|
+
acme = issuer(origin="https://policy.acme.example", issuer_id="acme", signer=sealing_key,
|
|
5
|
+
authorities=[policy], key_certs=lambda: registry_pool(),
|
|
6
|
+
witnesses=["https://finance.acme.example"], approvals=[{"role": "MANAGER", "endpoint": "https://approve.acme.example/nomos/approvals"}],
|
|
7
|
+
revocations=lambda: current_list)
|
|
8
|
+
app = acme.wsgi
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from datetime import timedelta
|
|
14
|
+
from typing import Any, Callable, List, Optional, Union
|
|
15
|
+
from urllib.parse import quote, unquote
|
|
16
|
+
|
|
17
|
+
from .statements import Signer, iso, now_utc, sign_in_force
|
|
18
|
+
|
|
19
|
+
WELL_KNOWN = "/.well-known/nomos-issuer"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Issuer:
|
|
23
|
+
def __init__(self, *, origin: str, issuer_id: str, signer: Signer, authorities: List[dict],
|
|
24
|
+
key_certs: Union[List[dict], Callable[[], List[dict]]], witnesses: Optional[List[str]] = None,
|
|
25
|
+
approvals: Optional[List[dict]] = None, revocations: Optional[Callable[[], dict]] = None,
|
|
26
|
+
revocations_url: Optional[str] = None):
|
|
27
|
+
self.base, self.issuer_id, self.signer = origin.rstrip("/"), issuer_id, signer
|
|
28
|
+
self.by_id = {a["meta"]["artifact_id"]: a for a in authorities}
|
|
29
|
+
self.key_certs, self.witnesses, self.approvals, self.revocations = key_certs, witnesses, approvals, revocations
|
|
30
|
+
self.revocations_url = f"{self.base}/nomos/revocations" if revocations else revocations_url
|
|
31
|
+
|
|
32
|
+
def document(self) -> dict:
|
|
33
|
+
pool = self.key_certs() if callable(self.key_certs) else self.key_certs
|
|
34
|
+
return {
|
|
35
|
+
"nomos_document": "issuer", "version": "1", "issuer_id": self.issuer_id,
|
|
36
|
+
"authorities": [{"artifact_id": i, "version": a["meta"]["version"], "seal_hash": a["seal"]["hash"],
|
|
37
|
+
"artifact_url": f"{self.base}/nomos/authorities/{quote(i, safe='')}.nomos",
|
|
38
|
+
"in_force_url": f"{self.base}/nomos/authorities/{quote(i, safe='')}/in-force"} for i, a in self.by_id.items()],
|
|
39
|
+
"key_certs": pool, **({"witnesses": self.witnesses} if self.witnesses else {}),
|
|
40
|
+
**({"approvals": self.approvals} if self.approvals else {}),
|
|
41
|
+
**({"revocations_url": self.revocations_url} if self.revocations_url else {}),
|
|
42
|
+
"valid_until": iso(now_utc() + timedelta(days=1)),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
def handle(self, method: str, path: str):
|
|
46
|
+
if method != "GET": return 404, {"error": "Not found"}
|
|
47
|
+
if path == WELL_KNOWN: return 200, self.document()
|
|
48
|
+
if path == "/nomos/revocations" and self.revocations: return 200, self.revocations()
|
|
49
|
+
prefix = "/nomos/authorities/"
|
|
50
|
+
if path.startswith(prefix):
|
|
51
|
+
rest = path[len(prefix):]
|
|
52
|
+
if rest.endswith(".nomos") and unquote(rest[:-6]) in self.by_id: return 200, self.by_id[unquote(rest[:-6])]
|
|
53
|
+
if rest.endswith("/in-force") and unquote(rest[:-9]) in self.by_id:
|
|
54
|
+
art = self.by_id[unquote(rest[:-9])]
|
|
55
|
+
return 200, sign_in_force(self.signer, art, valid_until=now_utc() + timedelta(days=1))
|
|
56
|
+
return 404, {"error": "Not found"}
|
|
57
|
+
|
|
58
|
+
def wsgi(self, environ, start_response):
|
|
59
|
+
status, body = self.handle(environ.get("REQUEST_METHOD", "GET"), environ.get("PATH_INFO", ""))
|
|
60
|
+
data = json.dumps(body).encode()
|
|
61
|
+
start_response(f"{status} {'OK' if status == 200 else 'Not Found'}", [("content-type", "application/json"), ("content-length", str(len(data)))])
|
|
62
|
+
return [data]
|
|
63
|
+
|
|
64
|
+
async def asgi(self, scope, receive, send):
|
|
65
|
+
if scope["type"] != "http": return
|
|
66
|
+
status, body = self.handle(scope["method"], scope["path"])
|
|
67
|
+
data = json.dumps(body).encode()
|
|
68
|
+
await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(data)).encode())]})
|
|
69
|
+
await send({"type": "http.response.body", "body": data})
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def issuer(**options) -> Issuer:
|
|
73
|
+
return Issuer(**options)
|
nomosprotocol/jcs.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""RFC 8785 JSON Canonicalization Scheme, sufficient for NOMOS objects (JSON-native types).
|
|
2
|
+
|
|
3
|
+
A non-finite number has no canonical form: canonicalizing one raises ValueError, and a caller
|
|
4
|
+
treats that object as malformed rather than signing or hashing some other encoding of it.
|
|
5
|
+
"""
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _es_number(v: float) -> str:
|
|
12
|
+
"""ECMAScript Number::toString (RFC 8785 §3.2.2.3), from Python's shortest round-trip digits."""
|
|
13
|
+
if v == 0: return "0"
|
|
14
|
+
if v < 0: return "-" + _es_number(-v)
|
|
15
|
+
mant, _, exp = repr(v).partition("e")
|
|
16
|
+
whole, _, frac = mant.partition(".")
|
|
17
|
+
digits = (whole + frac).lstrip("0")
|
|
18
|
+
n = len(whole.lstrip("0")) + int(exp or 0) if whole.lstrip("0") else int(exp or 0) - (len(frac) - len(frac.lstrip("0")))
|
|
19
|
+
digits = digits.rstrip("0") or "0"
|
|
20
|
+
k = len(digits)
|
|
21
|
+
if k <= n <= 21: return digits + "0" * (n - k)
|
|
22
|
+
if 0 < n <= 21: return digits[:n] + "." + digits[n:]
|
|
23
|
+
if -6 < n <= 0: return "0." + "0" * (-n) + digits
|
|
24
|
+
e = n - 1
|
|
25
|
+
return (digits[0] + ("." + digits[1:] if k > 1 else "")) + "e" + ("+" if e >= 0 else "-") + str(abs(e))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _jcs(v: Any) -> str:
|
|
29
|
+
if v is None: return "null"
|
|
30
|
+
if v is True: return "true"
|
|
31
|
+
if v is False: return "false"
|
|
32
|
+
if isinstance(v, int): return str(v)
|
|
33
|
+
if isinstance(v, float):
|
|
34
|
+
if v != v or v in (float("inf"), float("-inf")): raise ValueError("non-finite number")
|
|
35
|
+
return _es_number(v)
|
|
36
|
+
if isinstance(v, str): return json.dumps(v, ensure_ascii=False)
|
|
37
|
+
if isinstance(v, list): return "[" + ",".join(_jcs(x) for x in v) + "]"
|
|
38
|
+
if isinstance(v, dict):
|
|
39
|
+
ks = sorted(v, key=lambda k: k.encode("utf-16-be")) # JCS sorts by UTF-16 code units
|
|
40
|
+
return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + _jcs(v[k]) for k in ks) + "}"
|
|
41
|
+
raise TypeError(type(v))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def jcs_text(o: Any) -> str: return _jcs(o)
|
|
45
|
+
def jcs(o: Any) -> bytes: return _jcs(o).encode("utf-8")
|
|
46
|
+
def sha256_hex(b: bytes) -> str: return hashlib.sha256(b).hexdigest()
|