nomosprotocol 0.1.0__tar.gz → 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 (22) hide show
  1. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/PKG-INFO +3 -3
  2. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/README.md +1 -1
  3. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/__init__.py +8 -5
  4. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/act.py +298 -6
  5. nomosprotocol-0.2.0/nomosprotocol/bindings.py +145 -0
  6. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/chain.py +9 -2
  7. nomosprotocol-0.2.0/nomosprotocol/registrar.py +279 -0
  8. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol.egg-info/PKG-INFO +3 -3
  9. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol.egg-info/SOURCES.txt +2 -0
  10. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/pyproject.toml +2 -2
  11. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/accept.py +0 -0
  12. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/carrier.py +0 -0
  13. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/issuer.py +0 -0
  14. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/jcs.py +0 -0
  15. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/statements.py +0 -0
  16. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/suites.py +0 -0
  17. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol/witness.py +0 -0
  18. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol.egg-info/dependency_links.txt +0 -0
  19. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol.egg-info/requires.txt +0 -0
  20. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/nomosprotocol.egg-info/top_level.txt +0 -0
  21. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/setup.cfg +0 -0
  22. {nomosprotocol-0.1.0 → nomosprotocol-0.2.0}/tests/test_sdk.py +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nomosprotocol
3
- Version: 0.1.0
4
- Summary: NOMOS for Python: the reference verifiers for NOMOS-SPEC-007, -008 and -010, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs.
3
+ Version: 0.2.0
4
+ Summary: NOMOS for Python: the reference verifiers for NOMOS-SPEC-007 (rev. 1.11), -008 and -010, NOMOS-SPEC-014 registrar logs, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs.
5
5
  Author-email: NOMOS Protocol <hello@nomosprotocol.com>
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://www.computableauthority.com
@@ -109,7 +109,7 @@ chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
109
109
  ## Conformance
110
110
 
111
111
  This package is checked against:
112
- - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.9, rev. 1.10 revocation sources), NOMOS-SPEC-008
112
+ - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.11, rev. 1.10 revocation sources), NOMOS-SPEC-008
113
113
  0.6.0 and NOMOS-SPEC-010 0.2.0;
114
114
  - the NOMOS-SPEC-009 selection vectors;
115
115
  - the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
@@ -89,7 +89,7 @@ chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
89
89
  ## Conformance
90
90
 
91
91
  This package is checked against:
92
- - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.9, rev. 1.10 revocation sources), NOMOS-SPEC-008
92
+ - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.11, rev. 1.10 revocation sources), NOMOS-SPEC-008
93
93
  0.6.0 and NOMOS-SPEC-010 0.2.0;
94
94
  - the NOMOS-SPEC-009 selection vectors;
95
95
  - the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
@@ -5,7 +5,7 @@ The verifiers here are the same code the specification's published vectors are g
5
5
  checked with, so there is no second implementation to drift from the reference.
6
6
 
7
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
8
+ chain.resolve(...) NOMOS-SPEC-007 rev. 1.11: resolve a key to a pinned root, for a purpose
9
9
  chain.verify_revocation_list(...) NOMOS-SPEC-007 rev. 1.10: which revocations count, and since when
10
10
  accept(...) be the relying party: verify, commit exactly once, receipt (NOMOS-SPEC-009)
11
11
  act(...) be the carrier: discover, gather testimony, submit, get approval
@@ -14,7 +14,8 @@ checked with, so there is no second implementation to drift from the reference.
14
14
  local_signer, generate_signer keys in this process (development); pass your own Signer for a KMS
15
15
 
16
16
  Modules: jcs (RFC 8785), suites (NOMOS-SPEC-010), chain (NOMOS-SPEC-007), act (NOMOS-SPEC-008),
17
- statements, accept, carrier, witness, issuer.
17
+ statements, accept, carrier, witness, issuer, bindings (NOMOS-SPEC-011 tool bindings: parse, apply, digest),
18
+ registrar (NOMOS-SPEC-014 0.4.0 registrar logs: verify, fold, DNS discovery, world assembly).
18
19
  """
19
20
  from .act import verify_act, evaluate, binding_digest
20
21
  from .chain import resolve, verify_revocation_list, fingerprint
@@ -28,9 +29,11 @@ from .accept import accept, RelyingParty, MemoryStore, postgres_store, Revocatio
28
29
  from .carrier import act, NomosActError, fetch_document
29
30
  from .witness import witness, Witness
30
31
  from .issuer import issuer, Issuer
32
+ from . import registrar
33
+ from .registrar import verify_registrar_log, fold_registrar_log, load_registrar_world, discover as discover_registrar_log
31
34
 
32
- __version__ = "0.1.0"
35
+ __version__ = "0.2.0"
33
36
  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",
37
+ "NOMOS-SPEC-001": "2.2.0 + amendment 2.3.0", "NOMOS-SPEC-007": "rev. 1.11.0", "NOMOS-SPEC-008": "0.6.0",
38
+ "NOMOS-SPEC-009": "0.2.0", "NOMOS-SPEC-010": "0.2.0", "NOMOS-SPEC-014": "0.4.0 (registrar logs)",
36
39
  }
@@ -97,6 +97,10 @@ def binding_core(act: dict) -> dict:
97
97
  "relying_party": act.get("relying_party"), "action": act.get("action"),
98
98
  "artifact_hash": (art.get("seal") or {}).get("hash"),
99
99
  "testimony_digest": sha256_hex(jcs(sorted((act.get("testimony") or []), key=lambda t: _jcs(t)))),
100
+ # rev. 0.8.0 §4.3: an Act under several laws binds the exact set; a one-law Act is unchanged
101
+ **({"artifact_hashes": sorted(((a.get("artifact") or {}).get("seal") or {}).get("hash")
102
+ for a in [act.get("authority") or {}] + list(act.get("further_authorities") or []))}
103
+ if act.get("further_authorities") else {}),
100
104
  }
101
105
 
102
106
  def binding_digest(act: dict) -> str: return sha256_hex(jcs(binding_core(act)))
@@ -254,6 +258,7 @@ def eval_when(expr: str, facts: dict, decided_absent=()) -> str:
254
258
  return eval_when_detail(expr, facts, decided_absent)[0]
255
259
 
256
260
  RANK = {"block": 3, "escalate": 2, "allow": 1}
261
+ # SPEC-008 §6.0 (0.7.0): emit, and action naming a declared execution action, are obligations
257
262
  TIE_ORDERS = {"deny_wins": RANK, "allow_wins": {"allow": 3, "escalate": 2, "block": 1}, "escalate_wins": {"escalate": 3, "block": 2, "allow": 1}}
258
263
 
259
264
  def evaluate(artifact: dict, facts: dict) -> dict:
@@ -261,7 +266,19 @@ def evaluate(artifact: dict, facts: dict) -> dict:
261
266
  order = TIE_ORDERS[res.get("tie_breaker", "deny_wins")]
262
267
  inputs = artifact.get("data_contract", {}).get("inputs", {})
263
268
  decided_absent = {"action_type"} | {n for n, i in inputs.items() if (i or {}).get("source") in ABSENCE_AUTHORITATIVE}
264
- detail = [(d, *eval_when_detail(d["when"], facts, decided_absent)) for d in logic["decisions"]]
269
+ # SPEC-008 §6.1 (0.7.0): a decision whose outcome is `emit` or `action` (NOMOS-SPEC-001 §4.3) is an
270
+ # obligation, not a ruling, and takes no part in resolution. `set` and unknown types stay unevaluable.
271
+ declared = set((artifact.get("execution") or {}).get("actions") or {})
272
+ def is_obligation(d) -> bool:
273
+ t = ((d.get("then") or [{}])[0] or {})
274
+ return t.get("type") == "emit" or (t.get("type") == "action" and t.get("action_name") in declared)
275
+ rulings = [d for d in logic["decisions"] if not is_obligation(d)]
276
+ # §6.0: any other kind of decision makes the whole artifact unevaluable, whatever the facts —
277
+ # checked before evaluation, not only when such a rule happens to be reached.
278
+ for d in rulings:
279
+ if ((d.get("then") or [{}])[0] or {}).get("type") not in order:
280
+ raise ValueError("unevaluable rule %r" % d.get("id"))
281
+ detail = [(d, *eval_when_detail(d["when"], facts, decided_absent)) for d in rulings]
265
282
  results = [(d, r) for d, r, _ in detail]
266
283
  undecided_by = {d["id"]: u for d, _, u in detail}
267
284
  matched = [d for d, r in results if r == T]
@@ -293,19 +310,66 @@ def evaluate(artifact: dict, facts: dict) -> dict:
293
310
  return ev
294
311
 
295
312
 
313
+ # ── rev. 0.9.0: intake questions (gates) ────────────────────────────────────────────────────
314
+ def gates_of(art: dict):
315
+ """The authority's sealed intake questions, `data_contract.gates`: (gates, None) or (None, reason).
316
+ A gate is answered through the channel it declares and is never a fact the rules read."""
317
+ dc = art.get("data_contract") or {}
318
+ g = dc.get("gates")
319
+ if g is None: return {}, None
320
+ inputs = dc.get("inputs") or {}
321
+ if not isinstance(g, dict): return None, "bad_gates"
322
+ for f, v in g.items():
323
+ if not isinstance(v, dict) or not isinstance(v.get("when_false"), dict) or f in inputs or f == "action_type" \
324
+ or any(k in g for k in v["when_false"]):
325
+ return None, "bad_gates"
326
+ return g, None
327
+
328
+ def declarations(art: dict, gates: dict) -> dict:
329
+ """Every name an Act may supply: the declared inputs, and each gate as a boolean answered
330
+ through the source it declares."""
331
+ out = dict(art.get("data_contract", {}).get("inputs", {}) or {})
332
+ for f, g in gates.items(): out[f] = {"type": "boolean", "source": g.get("source"), "gate": True}
333
+ return out
334
+
335
+ def apply_gates(gates: dict, facts: dict):
336
+ """§6.5: every gate answered false settles the facts it covers. A covered fact supplied with
337
+ another value contradicts the answer. Returns (facts the rules read, failure or None)."""
338
+ out = {k: v for k, v in facts.items() if k not in gates}
339
+ for gf in sorted(gates):
340
+ if facts.get(gf) is not False: continue
341
+ for f, v in gates[gf]["when_false"].items():
342
+ if out.get(f) is not None and jcs(out[f]) != jcs(v):
343
+ return None, {"decision": "FACT_SOURCE_VIOLATION", "field": f, "reason_code": "contradicts_gate", "gate": gf}
344
+ out[f] = v
345
+ return out, None
346
+
347
+ def open_gates(gates: dict, facts: dict, open_facts: list) -> list:
348
+ """The questions left unanswered that would settle at least one open fact."""
349
+ need = set(open_facts)
350
+ return sorted(gf for gf, g in gates.items() if facts.get(gf) is None and need & set(g["when_false"]))
351
+
352
+
296
353
  # ── the Act verifier (SPEC-008 §6) ──────────────────────────────────────────────────────
297
354
  def verify_act(act: Any, *, relying_party_id: str, root_pem: str, now: datetime,
298
355
  seen_nonces: Set[str], currency_policy: str, local_facts: Optional[dict] = None,
299
356
  revoked_kids: Optional[Set[str]] = None, revoked_certs: Optional[Set[str]] = None,
300
357
  in_force: Optional[Dict[str, str]] = None, revoked_artifacts: Optional[Set[str]] = None,
301
- max_window_seconds: int = MAX_WINDOW_SECONDS) -> dict:
302
- """`in_force` is the relying party's own record of the version in force, artifact_id -> seal hash
358
+ max_window_seconds: int = MAX_WINDOW_SECONDS, evaluate_only: Optional[Set[str]] = None) -> dict:
359
+ """`evaluate_only` (rev. 0.8.0 §6.4): the artifact ids of the resolved applicable set; carried
360
+ authorities outside it are not evaluated. None (no resolution) evaluates every carried authority.
361
+ `in_force` is the relying party's own record of the version in force, artifact_id -> seal hash
303
362
  (§5.4); `revoked_artifacts` the seal hashes its revocation source lists (NOMOS-SPEC-006);
304
363
  `currency_policy` the policy it declares for establishing currency (§5.5): "record" or
305
364
  "record_or_statement". There is no default: the choice is the relying party's to declare.
306
365
  `max_window_seconds` is the relying party's own maximum Act window (§5.1), 300 unless it
307
366
  configures otherwise, for example to leave a human time to approve (NOMOS-SPEC-009 §6.3)."""
308
367
  if currency_policy not in CURRENCY_POLICIES: raise ValueError(f"currency_policy must be one of {CURRENCY_POLICIES}")
368
+ if isinstance(act, dict) and ("further_authorities" in act or evaluate_only is not None):
369
+ return verify_act_multi(act, relying_party_id=relying_party_id, root_pem=root_pem, now=now, seen_nonces=seen_nonces,
370
+ currency_policy=currency_policy, local_facts=local_facts, revoked_kids=revoked_kids,
371
+ revoked_certs=revoked_certs, in_force=in_force, revoked_artifacts=revoked_artifacts,
372
+ max_window_seconds=max_window_seconds, evaluate_only=evaluate_only)
309
373
  revoked_kids = revoked_kids or set(); revoked_certs = revoked_certs or set(); local_facts = local_facts or {}
310
374
  in_force = in_force or {}; revoked_artifacts = revoked_artifacts or set()
311
375
  # 1. structure
@@ -377,6 +441,8 @@ def verify_act(act: Any, *, relying_party_id: str, root_pem: str, now: datetime,
377
441
  in_force_source = "statement"
378
442
  # 5b. an authority whose verdict would depend on listing order cannot authorize (SPEC-001 2.3.0)
379
443
  if ambiguous_escalation(art): return {"decision": "MALFORMED", "reason_code": "ambiguous_escalation"}
444
+ gates, bad_g = gates_of(art)
445
+ if bad_g: return {"decision": "MALFORMED", "reason_code": bad_g}
380
446
  # 6. testimony
381
447
  facts: Dict[str, Any] = {}; channel: Dict[str, str] = {}
382
448
  def put(name, value, src):
@@ -409,7 +475,7 @@ def verify_act(act: Any, *, relying_party_id: str, root_pem: str, now: datetime,
409
475
  for k, v in local_facts.items(): put(k, v, "relying_party")
410
476
  except KeyError as e:
411
477
  return {"decision": "FACT_SOURCE_VIOLATION", "field": e.args[0], "reason_code": "duplicate"}
412
- inputs = art.get("data_contract", {}).get("inputs", {})
478
+ inputs = declarations(art, gates)
413
479
  for name, src in channel.items():
414
480
  if name == "action_type": continue
415
481
  declared = (inputs.get(name) or {}).get("source")
@@ -422,6 +488,10 @@ def verify_act(act: Any, *, relying_party_id: str, root_pem: str, now: datetime,
422
488
  if name == "action_type" or value is None: continue
423
489
  if not type_ok(value, inputs[name]):
424
490
  return {"decision": "FACT_TYPE_VIOLATION", "field": name, "declared": inputs[name].get("type"), "supplied_via": channel[name]}
491
+ # 7c. rev. 0.9.0 §6.5: an intake question answered "no" settles the facts it covers
492
+ answers = facts
493
+ facts, contradiction = apply_gates(gates, facts)
494
+ if contradiction: return contradiction
425
495
  # 8. evaluate the sealed rules over exactly these facts
426
496
  try:
427
497
  ev = evaluate(art, facts)
@@ -430,8 +500,10 @@ def verify_act(act: Any, *, relying_party_id: str, root_pem: str, now: datetime,
430
500
  digest = binding_digest(act)
431
501
  base = {"rule": ev["rule"], "act_digest": digest, "in_force_source": in_force_source, "currency_policy": currency_policy}
432
502
  if ev["outcome"] == "undecided": # §6.2: no consent can stand in for a missing fact
433
- return {"decision": "INCOMPLETE", "commit": False, "reason_code": "undecided_rules",
434
- "open_rules": ev["open_rules"], "open_facts": ev["open_facts"], **base}
503
+ out = {"decision": "INCOMPLETE", "commit": False, "reason_code": "undecided_rules",
504
+ "open_rules": ev["open_rules"], "open_facts": ev["open_facts"], **base}
505
+ if gates: out["open_gates"] = open_gates(gates, answers, ev["open_facts"])
506
+ return out
435
507
  if ev.get("reason_code"): base["reason_code"] = ev["reason_code"]
436
508
  if ev["outcome"] == "allow": return {"decision": "AUTHORIZED", "commit": True, **base}
437
509
  if ev["outcome"] == "block": return {"decision": "DENIED", "commit": False, **base}
@@ -460,3 +532,223 @@ def verify_act(act: Any, *, relying_party_id: str, root_pem: str, now: datetime,
460
532
  if len(approvers) >= need_n:
461
533
  return {"decision": "AUTHORIZED", "commit": True, "by_consent": True, "escalation_id": ev["escalation_id"], "consents_valid": len(approvers), "consents_required": need_n, **base}
462
534
  return {"decision": "ESCALATED", "commit": False, "escalation_id": ev["escalation_id"], "consents_valid": len(approvers), "consents_required": need_n, **base}
535
+
536
+
537
+ # ── rev. 0.8.0: an Act under several laws (§6.3, §6.4) ─────────────────────────────────────────
538
+ MAX_FURTHER_AUTHORITIES = 7
539
+
540
+ def _check_authority(entry: dict, pool: list, root_pem: str, now: datetime, currency_policy: str,
541
+ in_force: Dict[str, str], revoked_artifacts: Set[str], revoked_kids: Set[str], revoked_certs: Set[str]):
542
+ """§6 step 5, §5.4-5.5 and SPEC-001 2.3.0 for one carried authority: (failure, None) or (None, its record)."""
543
+ art = entry["artifact"]; seal = art["seal"]; meta = art.get("meta", {}); art_id = meta.get("artifact_id")
544
+ r = chain.resolve(seal["kid"], pool, root_pem, now, chain.for_artifact(meta, seal["signature_algorithm"]), revoked_kids, revoked_certs)
545
+ if r["decision"] != "RESOLVED": return {**r, "artifact_id": art_id}, None
546
+ failure = chain.seal_failure(art, r["key"])
547
+ if failure: return {**failure, "artifact_id": art_id}, None
548
+ if seal["hash"] in revoked_artifacts: return {"decision": "ARTIFACT_REVOKED", "artifact_id": art_id}, None
549
+ def unverified(reason): return {"decision": "VERSION_UNVERIFIED", "artifact_id": art_id, "reason_code": reason}, None
550
+ if art_id in in_force:
551
+ if in_force[art_id] != seal["hash"]:
552
+ return {"decision": "SUPERSEDED", "artifact_id": art_id, "in_force_seal_hash": in_force[art_id]}, None
553
+ source = "record"
554
+ elif currency_policy == "record":
555
+ return unverified("not_in_record")
556
+ else:
557
+ st = entry.get("in_force")
558
+ if st is None: return unverified("no_in_force_evidence")
559
+ if not isinstance(st, dict) or not all(isinstance(st.get(k), str) for k in ("artifact_id", "version", "seal_hash", "as_of", "valid_until", "kid", "signature")) \
560
+ or st.get("algorithm") not in TESTIMONY_SUITES:
561
+ return unverified("bad_statement")
562
+ if st["artifact_id"] != art_id or st["seal_hash"] != seal["hash"] or st["version"] != meta.get("version"):
563
+ return unverified("statement_mismatch")
564
+ if st["kid"] != seal["kid"] or not chain.suite_permitted(r["effective"], st["algorithm"]) \
565
+ or not statement_sig(r["key"], st, in_force_payload(st))[0]:
566
+ return unverified("bad_signature")
567
+ try:
568
+ sa, su = ts(st["as_of"]), ts(st["valid_until"])
569
+ except (ValueError, TypeError):
570
+ return unverified("bad_statement")
571
+ if (su - sa).total_seconds() > MAX_IN_FORCE_SECONDS or su <= sa: return unverified("statement_window")
572
+ if now < sa or now > su: return unverified("stale")
573
+ source = "statement"
574
+ if ambiguous_escalation(art): return {"decision": "MALFORMED", "reason_code": "ambiguous_escalation", "artifact_id": art_id}, None
575
+ gates, bad_g = gates_of(art)
576
+ if bad_g: return {"decision": "MALFORMED", "reason_code": bad_g, "artifact_id": art_id}, None
577
+ return None, {"artifact": art, "meta": meta, "artifact_id": art_id, "gates": gates, "inputs": declarations(art, gates), "in_force_source": source}
578
+
579
+
580
+ def verify_act_multi(act: Any, *, relying_party_id: str, root_pem: str, now: datetime, seen_nonces: Set[str],
581
+ currency_policy: str, local_facts: Optional[dict] = None, revoked_kids: Optional[Set[str]] = None,
582
+ revoked_certs: Optional[Set[str]] = None, in_force: Optional[Dict[str, str]] = None,
583
+ revoked_artifacts: Optional[Set[str]] = None, max_window_seconds: int = MAX_WINDOW_SECONDS,
584
+ evaluate_only: Optional[Set[str]] = None) -> dict:
585
+ """rev. 0.8.0 §6.3-6.4: an Act carrying `further_authorities`, or verified under a resolution."""
586
+ revoked_kids = revoked_kids or set(); revoked_certs = revoked_certs or set(); local_facts = local_facts or {}
587
+ in_force = in_force or {}; revoked_artifacts = revoked_artifacts or set()
588
+ need = ("act_version", "act_id", "nonce", "issued_at", "expires_at", "relying_party", "action", "authority")
589
+ if not isinstance(act, dict) or any(k not in act for k in need) or act.get("act_version") != "1" \
590
+ or not isinstance(act.get("authority"), dict):
591
+ return {"decision": "MALFORMED", "reason_code": "bad_envelope"}
592
+ try:
593
+ jcs(act)
594
+ except (ValueError, TypeError):
595
+ return {"decision": "MALFORMED", "reason_code": "not_canonicalizable"}
596
+ action, auth = act["action"], act["authority"]
597
+ if not isinstance(action, dict) or not isinstance(action.get("type"), str) or not isinstance(action.get("params", {}), dict):
598
+ return {"decision": "MALFORMED", "reason_code": "bad_action"}
599
+ further = act.get("further_authorities", [])
600
+ if "further_authorities" in act and (not isinstance(further, list) or not 1 <= len(further) <= MAX_FURTHER_AUTHORITIES
601
+ or not all(isinstance(f, dict) and isinstance(f.get("artifact"), dict) for f in further)):
602
+ return {"decision": "MALFORMED", "reason_code": "bad_envelope"}
603
+ pool = auth.get("key_certs", [])
604
+ carried = [auth] + list(further)
605
+ bad = chain.check_pool(pool)
606
+ for entry in carried:
607
+ bad = bad or chain.check_seal_shape(entry.get("artifact"))
608
+ if bad: return {"decision": "MALFORMED", "reason_code": bad}
609
+ hashes = [e["artifact"]["seal"]["hash"] for e in carried]
610
+ ids = [e["artifact"].get("meta", {}).get("artifact_id") for e in carried]
611
+ if len(set(hashes)) != len(hashes) or len(set(ids)) != len(ids):
612
+ return {"decision": "MALFORMED", "reason_code": "duplicate_authority"}
613
+ try:
614
+ t0, t1 = ts(act["issued_at"]), ts(act["expires_at"])
615
+ except (ValueError, TypeError):
616
+ return {"decision": "MALFORMED", "reason_code": "bad_time"}
617
+ if (t1 - t0).total_seconds() > max_window_seconds or t1 <= t0:
618
+ return {"decision": "MALFORMED", "reason_code": "validity_window"}
619
+ if act["relying_party"] != relying_party_id: return {"decision": "WRONG_RELYING_PARTY"}
620
+ if now < t0: return {"decision": "NOT_YET_VALID"}
621
+ if now > t1: return {"decision": "EXPIRED"}
622
+ if act["nonce"] in seen_nonces: return {"decision": "REPLAYED"}
623
+ # §6.4.2: a member of the applicable set that is not carried holds the Act
624
+ if evaluate_only is not None:
625
+ missing = sorted(set(evaluate_only) - set(ids))
626
+ if missing: return {"decision": "INCOMPLETE", "commit": False, "reason_code": "laws_not_presented", "laws": missing}
627
+ # §6.4.1: under a resolution, only the carried members of the applicable set are evaluated
628
+ active_entries = [e for e in carried if evaluate_only is None or e["artifact"].get("meta", {}).get("artifact_id") in evaluate_only]
629
+ if not active_entries:
630
+ return {"decision": "INCOMPLETE", "commit": False, "reason_code": "laws_not_presented", "laws": sorted(evaluate_only or [])}
631
+ # §6.3.1: each carried authority, in order; the first failure decides
632
+ laws = []
633
+ for entry in active_entries:
634
+ failure, rec = _check_authority(entry, pool, root_pem, now, currency_policy, in_force, revoked_artifacts, revoked_kids, revoked_certs)
635
+ if failure: return failure
636
+ laws.append(rec)
637
+ def declaring(name): return [l for l in laws if name in l["inputs"]]
638
+ def gate_of(l, name): return l["gates"].get(name)
639
+ # §6.4.1: a fact or statement only a carried, non-governing authority declares is not read at all
640
+ ignored_inputs = set()
641
+ for e in carried:
642
+ if e not in active_entries:
643
+ dc = e["artifact"].get("data_contract") or {}
644
+ ignored_inputs |= set((dc.get("inputs") or {}).keys()) | set((dc.get("gates") or {}).keys() if isinstance(dc.get("gates"), dict) else ())
645
+ def only_ignored(name): return not declaring(name) and name in ignored_inputs
646
+ # §6.3.3: testimony once; its key admitted under every authority that declares the claim
647
+ facts: Dict[str, Any] = {}; channel: Dict[str, str] = {}
648
+ def put(name, value, src):
649
+ if name in channel: raise KeyError(name)
650
+ facts[name] = value; channel[name] = src
651
+ subject = action.get("subject")
652
+ for t in act.get("testimony") or []:
653
+ if not isinstance(t, dict) or not all(k in t for k in ("claim", "value", "as_of", "valid_until", "kid", "signature")) \
654
+ or t.get("algorithm") not in TESTIMONY_SUITES:
655
+ return {"decision": "MALFORMED", "reason_code": "bad_testimony"}
656
+ if only_ignored(t["claim"]): continue
657
+ key_pem = None
658
+ for l in (declaring(t["claim"]) or laws[:1]):
659
+ w = resolve_statement_key("claim", t["claim"], t, pool, root_pem, now, l["meta"], revoked_kids, revoked_certs)
660
+ if w["decision"] != "RESOLVED":
661
+ return {**statement_failure(w, "TESTIMONY_INVALID", "TESTIMONY_OUT_OF_SCOPE", claim=t["claim"]), "artifact_id": l["artifact_id"]}
662
+ key_pem = w["key"]
663
+ ok, why = statement_sig(key_pem, t, testimony_payload(t))
664
+ if not ok: return {"decision": "TESTIMONY_INVALID", "claim": t["claim"], "reason_code": why}
665
+ try:
666
+ fresh = ts(t["as_of"]) <= now <= ts(t["valid_until"])
667
+ except (ValueError, TypeError, AttributeError):
668
+ fresh = False
669
+ if not fresh: return {"decision": "TESTIMONY_INVALID", "claim": t["claim"], "reason_code": "stale"}
670
+ if t.get("about") is not None and t.get("about") != subject:
671
+ return {"decision": "TESTIMONY_INVALID", "claim": t["claim"], "reason_code": "wrong_subject"}
672
+ try: put(t["claim"], t["value"], "testimony")
673
+ except KeyError: return {"decision": "FACT_SOURCE_VIOLATION", "field": t["claim"], "reason_code": "duplicate"}
674
+ try:
675
+ put("action_type", action["type"], "action")
676
+ for k, v in (action.get("params") or {}).items(): put(k, v, "action")
677
+ for k, v in (act.get("presenter_facts") or {}).items(): put(k, v, "presenter")
678
+ for k, v in local_facts.items(): put(k, v, "relying_party")
679
+ except KeyError as e:
680
+ return {"decision": "FACT_SOURCE_VIOLATION", "field": e.args[0], "reason_code": "duplicate"}
681
+ # §6.3.2: every supplied fact declared by at least one authority, the same way by all that declare it
682
+ for name in [n for n in channel if n != "action_type" and only_ignored(n)]:
683
+ facts.pop(name); channel.pop(name)
684
+ for name, src in channel.items():
685
+ if name == "action_type": continue
686
+ decl = [l["inputs"][name] for l in declaring(name)]
687
+ if not decl: return {"decision": "FACT_SOURCE_VIOLATION", "field": name, "reason_code": "undeclared_input"}
688
+ if len({(d.get("source"), d.get("type"), jcs(gate_of(l, name)) if d.get("gate") else None) for l, d in zip(declaring(name), decl)}) > 1:
689
+ return {"decision": "FACT_SOURCE_VIOLATION", "field": name, "reason_code": "conflicting_declarations"}
690
+ if decl[0].get("source") != src:
691
+ return {"decision": "FACT_SOURCE_VIOLATION", "field": name, "declared": decl[0].get("source"), "supplied_via": src}
692
+ for name, value in facts.items():
693
+ if name == "action_type" or value is None: continue
694
+ d = declaring(name)[0]["inputs"][name]
695
+ if not type_ok(value, d):
696
+ return {"decision": "FACT_TYPE_VIOLATION", "field": name, "declared": d.get("type"), "supplied_via": channel[name]}
697
+ # §6.3.4: each authority over exactly the facts it declares
698
+ digest = binding_digest(act)
699
+ results = []
700
+ for l in laws:
701
+ answers = {k: v for k, v in facts.items() if k == "action_type" or k in l["inputs"]}
702
+ mine, contradiction = apply_gates(l["gates"], answers) # rev. 0.9.0 §6.5, each law its own questions
703
+ if contradiction: return {**contradiction, "artifact_id": l["artifact_id"]}
704
+ try:
705
+ ev = evaluate(l["artifact"], mine)
706
+ except (ValueError, KeyError, TypeError, IndexError):
707
+ return {"decision": "MALFORMED", "reason_code": "unevaluable_rules", "commit": False, "artifact_id": l["artifact_id"]}
708
+ if ev["outcome"] == "undecided" and l["gates"]: ev = {**ev, "open_gates": open_gates(l["gates"], answers, ev["open_facts"])}
709
+ results.append((l, ev))
710
+ # §6.3.5: every consent validated under the authorities whose escalation needs its role
711
+ esc_of = {}
712
+ for l, ev in results:
713
+ if ev["outcome"] == "escalate":
714
+ e = next((x for x in l["artifact"].get("governance", {}).get("escalations", []) if x.get("id") == ev["escalation_id"]), None)
715
+ esc_of[l["artifact_id"]] = e
716
+ approvers: Dict[str, Set[str]] = {aid: set() for aid in esc_of}
717
+ for c in act.get("consents") or []:
718
+ if not isinstance(c, dict) or not all(isinstance(c.get(k), str) for k in ("binding_digest", "role", "decision", "signed_at", "kid", "signature")) \
719
+ or c.get("algorithm") not in CONSENT_SUITES \
720
+ or (c["algorithm"] == "WebAuthn-ES256" and not all(isinstance(c.get(k), str) for k in WEBAUTHN_FIELDS)):
721
+ return {"decision": "MALFORMED", "reason_code": "bad_consent"}
722
+ under = [l for l, ev in results if esc_of.get(l["artifact_id"]) and esc_of[l["artifact_id"]].get("role_required") == c["role"]] or laws[:1]
723
+ for l in under:
724
+ k = resolve_statement_key("consent", c["role"], c, pool, root_pem, now, l["meta"], revoked_kids, revoked_certs)
725
+ if k["decision"] != "RESOLVED":
726
+ r = statement_failure(k, "CONSENT_INVALID", "CONSENT_OUT_OF_SCOPE", role=c["role"])
727
+ if r["decision"] == "CONSENT_INVALID": r.pop("role")
728
+ return {**r, "artifact_id": l["artifact_id"]}
729
+ if len({e["approver"] for e in k["admitted"]}) > 1: return {"decision": "CONSENT_INVALID", "reason_code": "approver_ambiguous"}
730
+ ok, why = statement_sig(k["key"], c, consent_payload(c))
731
+ if not ok: return {"decision": "CONSENT_INVALID", "reason_code": why}
732
+ if c["binding_digest"] != digest: return {"decision": "CONSENT_INVALID", "reason_code": "binding_mismatch"}
733
+ e = esc_of.get(l["artifact_id"])
734
+ if e and c["decision"] == "approve" and c["role"] == e.get("role_required"): approvers[l["artifact_id"]].add(k["effective"]["approver"])
735
+ # §6.3.6: combine — any deny denies; a missing fact is incomplete; a yes needs every law
736
+ per = []
737
+ for l, ev in results:
738
+ row = {"artifact_id": l["artifact_id"], "rule": ev["rule"]}
739
+ if ev["outcome"] == "undecided":
740
+ row.update(decision="INCOMPLETE", open_rules=ev["open_rules"], open_facts=ev["open_facts"])
741
+ if "open_gates" in ev: row["open_gates"] = ev["open_gates"]
742
+ elif ev["outcome"] == "allow": row.update(decision="AUTHORIZED")
743
+ elif ev["outcome"] == "block": row.update(decision="DENIED")
744
+ else:
745
+ e = esc_of.get(l["artifact_id"]); n = int((e or {}).get("required_consents", 1)) if e else None
746
+ got = len(approvers.get(l["artifact_id"], set()))
747
+ ok = e is not None and got >= n
748
+ row.update(decision="AUTHORIZED" if ok else "ESCALATED", by_consent=ok, escalation_id=ev["escalation_id"], consents_valid=got, consents_required=n)
749
+ per.append(row)
750
+ decisions = [p["decision"] for p in per]
751
+ overall = "DENIED" if "DENIED" in decisions else "INCOMPLETE" if "INCOMPLETE" in decisions else "ESCALATED" if "ESCALATED" in decisions else "AUTHORIZED"
752
+ out = {"decision": overall, "commit": overall == "AUTHORIZED", "act_digest": digest, "laws": per, "currency_policy": currency_policy}
753
+ if overall == "INCOMPLETE": out["reason_code"] = "undecided_rules"
754
+ return out
@@ -0,0 +1,145 @@
1
+ """NOMOS-SPEC-011 (Draft) Tool Bindings: which of a tool's arguments is which fact a sealed policy reads.
2
+
3
+ Pure: no I/O. ``parse`` reads a binding file, refusing anything it does not fully understand, and
4
+ returns its normal form; ``apply`` gives the facts a policy sees for one call, and the facts it could
5
+ not get; ``digest`` is the value an enforcement point records with each decision (SPEC-012 §6).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from decimal import ROUND_HALF_UP, Decimal
10
+ from typing import Any
11
+
12
+ from .jcs import _es_number, jcs, sha256_hex
13
+
14
+ RESERVED = {"__proto__", "constructor", "prototype"}
15
+ TOP = {"version", "artifact", "reviewed", "tools", "_review"}
16
+ TOOL = {"facts", "_why"}
17
+ FACT = {"arg", "scale", "map", "_why"}
18
+
19
+
20
+ class BindingError(ValueError):
21
+ """The file is refused (SPEC-011 §2). The message is informative only."""
22
+
23
+
24
+ def _is_number(v: Any) -> bool:
25
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and v == v and v not in (float("inf"), float("-inf"))
26
+
27
+
28
+ def _is_scalar(v: Any) -> bool:
29
+ return isinstance(v, (str, bool)) or _is_number(v)
30
+
31
+
32
+ def parse(raw: Any) -> dict:
33
+ """The normal form of a binding file (comments removed), or BindingError."""
34
+ def no(why: str):
35
+ raise BindingError(why)
36
+ if not isinstance(raw, dict):
37
+ no("not a JSON object")
38
+ if raw.get("version") != 1 or isinstance(raw.get("version"), bool) or not isinstance(raw.get("version"), int):
39
+ no('"version" must be 1')
40
+ if not isinstance(raw.get("artifact"), str) or not raw["artifact"]:
41
+ no('"artifact" must name the sealed policy')
42
+ if not isinstance(raw.get("reviewed"), bool):
43
+ no('"reviewed" must be true or false')
44
+ if not isinstance(raw.get("tools"), dict):
45
+ no('"tools" must be an object')
46
+ for k in raw:
47
+ if k not in TOP:
48
+ no(f'unknown setting "{k}"')
49
+ tools: dict = {}
50
+ for tool, entry in raw["tools"].items():
51
+ if tool in RESERVED:
52
+ no(f'"{tool}" is not a usable tool name')
53
+ if not isinstance(entry, dict):
54
+ no(f'tool "{tool}" must be an object with "facts"')
55
+ for k in entry:
56
+ if k not in TOOL:
57
+ no(f'tool "{tool}": unknown setting "{k}"')
58
+ facts = entry.get("facts")
59
+ if not isinstance(facts, dict):
60
+ no(f'tool "{tool}" needs "facts"')
61
+ out: dict = {}
62
+ for fact, b in facts.items():
63
+ where = f"{tool}.{fact}"
64
+ if fact == "tool":
65
+ no(f'{where}: "tool" is set by the enforcement point')
66
+ if fact in RESERVED:
67
+ no(f"{where} is not a usable fact name")
68
+ if not isinstance(b, dict):
69
+ no(f'{where} must be an object with "arg"')
70
+ for k in b:
71
+ if k not in FACT:
72
+ no(f'{where}: "{k}" is not allowed; a fact only comes from an argument')
73
+ arg = b.get("arg")
74
+ if not isinstance(arg, str) or not arg:
75
+ no(f'{where} needs "arg"')
76
+ if any(not s or s in RESERVED for s in arg.split(".")):
77
+ no(f'{where}: "{arg}" is not a usable argument path')
78
+ if "scale" in b and "map" in b:
79
+ no(f'{where}: "scale" or "map", not both')
80
+ if "scale" in b and (not _is_number(b["scale"]) or b["scale"] == 0):
81
+ no(f'{where}: "scale" must be a non-zero number')
82
+ if "map" in b:
83
+ m = b["map"]
84
+ if not isinstance(m, dict) or any(k in RESERVED or not _is_scalar(v) for k, v in m.items()):
85
+ no(f'{where}: "map" must be an object of plain values')
86
+ norm = {"arg": arg}
87
+ if "scale" in b:
88
+ norm["scale"] = b["scale"]
89
+ if "map" in b:
90
+ norm["map"] = dict(b["map"])
91
+ out[fact] = norm
92
+ tools[tool] = {"facts": out}
93
+ return {"version": 1, "artifact": raw["artifact"], "reviewed": raw["reviewed"], "tools": tools}
94
+
95
+
96
+ def digest(normal: dict) -> str:
97
+ """SHA-256 (hex) of the JCS form of a parsed binding file."""
98
+ return sha256_hex(jcs(normal))
99
+
100
+
101
+ def _key(v: Any) -> str:
102
+ """How a value is looked up in a map (SPEC-011 §3.3)."""
103
+ if isinstance(v, bool):
104
+ return "true" if v else "false"
105
+ if isinstance(v, str):
106
+ return v
107
+ return _es_number(float(v))
108
+
109
+
110
+ def _scaled(v: float, scale: float) -> float:
111
+ """The product, rounded to nine decimal places, ties away from zero (SPEC-011 §3.2)."""
112
+ return float(Decimal(v * scale).quantize(Decimal("1e-9"), rounding=ROUND_HALF_UP))
113
+
114
+
115
+ def apply(normal: dict, tool: str, args: dict) -> tuple[dict, list]:
116
+ """The facts a policy gets for this call (``tool`` always set), and the facts it could not get."""
117
+ inputs: dict = {"tool": tool}
118
+ unresolved: list = []
119
+ entry = normal["tools"].get(tool) if tool in normal["tools"] else None
120
+ for fact, b in (entry["facts"] if entry else {}).items():
121
+ v: Any = args
122
+ for seg in b["arg"].split("."):
123
+ # Through objects' own members only: never into an array.
124
+ v = v[seg] if isinstance(v, dict) and seg in v else None
125
+ if v is None:
126
+ unresolved.append({"fact": fact, "arg": b["arg"], "why": "missing"})
127
+ continue
128
+ if "scale" in b:
129
+ if not _is_number(v):
130
+ unresolved.append({"fact": fact, "arg": b["arg"], "why": "not_a_number"})
131
+ continue
132
+ inputs[fact] = _scaled(v, b["scale"])
133
+ continue
134
+ if not _is_scalar(v):
135
+ unresolved.append({"fact": fact, "arg": b["arg"], "why": "not_a_value"})
136
+ continue
137
+ if "map" in b:
138
+ k = _key(v)
139
+ if k not in b["map"]:
140
+ unresolved.append({"fact": fact, "arg": b["arg"], "why": "not_in_map"})
141
+ continue
142
+ inputs[fact] = b["map"][k]
143
+ continue
144
+ inputs[fact] = v
145
+ return inputs, unresolved
@@ -182,7 +182,9 @@ def _candidates(target: str, root: str, pool: list, on_path: frozenset, depth: i
182
182
  yield []
183
183
  return
184
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):
185
+ # rev. 1.11: ties (certificates differing only in signature) break on the signature, so the
186
+ # verdict depends on the set presented, never on its order.
187
+ for c in sorted((c for c in pool if c.get("child_kid") == target), key=lambda c: (fingerprint(c), str(c.get("signature", "")))):
186
188
  for head in _candidates(c.get("parent_kid"), root, pool, on_path | {target}, depth + 1):
187
189
  yield head + [c]
188
190
 
@@ -205,7 +207,7 @@ def _validate(path: list, root_pem: str, now: datetime, admit: Admit,
205
207
  revoked_kids: Set[str], revoked_certs: Set[str], memo: Optional[dict] = None) -> Verdict:
206
208
  cur_pem, effective = root_pem, {}
207
209
  hops = []
208
- for cert in path:
210
+ for index, cert in enumerate(path):
209
211
  ktype, _, reason = suites.load_key(cert["child_public_key_pem"])
210
212
  if reason: return _fail("ISSUER_NOT_RECOGNIZED", reason_code="invalid_key")
211
213
  if suites.compute_kid(cert["child_public_key_pem"]) != cert["child_kid"]:
@@ -229,6 +231,11 @@ def _validate(path: list, root_pem: str, now: datetime, admit: Admit,
229
231
  return _fail("OUT_OF_SCOPE", reason_code="malformed_scope")
230
232
  narrowed = dict(effective)
231
233
  for d, v in terms:
234
+ # rev. 1.11 §3.5: statement authority comes from the root. Below the root's own
235
+ # certificate a claim or consent term may only narrow one its parent already holds; a
236
+ # key with none (a sealing key) cannot certify witnesses or approvers.
237
+ if d in ("claim", "consent") and index > 0 and d not in effective:
238
+ return _fail("OUT_OF_SCOPE", dimension=d, reason_code="statement_below_root")
232
239
  if d in effective and not contains(d, effective[d], v):
233
240
  return _fail("OUT_OF_SCOPE", dimension=d, reason_code="widening")
234
241
  narrowed[d] = v
@@ -0,0 +1,279 @@
1
+ """NOMOS-SPEC-014 0.4.0 registrar logs: the reference reading of a registrar's log, written apart
2
+ from the TypeScript verifier so the published vectors are checked by two implementations.
3
+
4
+ verify_registrar_log(...) is this copy of a log genuine, current, append-only, and signed by the
5
+ key in force (after rotations the key in force signed)?
6
+ fold_registrar_log(...) the record the resolver reads: claims, closures, recognitions (with
7
+ their windows and any delegation), supersessions, revocations
8
+ parse_dns_record(...) §2.5: a `_nomos-registrar` TXT record, or None
9
+ discover(...) §2.5: where the log is, given the kid the relying party already holds
10
+ load_registrar_world(...) §2.3: pins first, then delegates named by recognitions in force,
11
+ each verified under the key the relying party or its recognizer chose
12
+
13
+ Pure: no network (logs are passed in), no clock but the one passed.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from datetime import datetime
18
+ from typing import Any, Callable, Dict, List, Optional, Tuple
19
+
20
+ from . import suites as S
21
+ from .jcs import jcs, sha256_hex
22
+
23
+ GENESIS = "0" * 64
24
+ PLATFORM_LOG = "nomos-exchange-log"
25
+
26
+
27
+ def registrar_log_name(registrar_id: str) -> str:
28
+ return f"nomos-registrar:{registrar_id}"
29
+
30
+
31
+ def _ts(s: Any) -> Optional[float]:
32
+ if not isinstance(s, str):
33
+ return None
34
+ try:
35
+ return datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp()
36
+ except ValueError:
37
+ return None
38
+
39
+
40
+ def suite_for_key(pem: Any) -> Optional[str]:
41
+ ktype, _, reason = S.load_key(pem)
42
+ if reason:
43
+ return None
44
+ return "Ed25519" if ktype == "Ed25519" else "ES256"
45
+
46
+
47
+ def head_payload(head: Dict[str, Any], log: str) -> bytes:
48
+ return jcs({"log": log, "size": head["size"], "hash": head["hash"], "at": head["at"]})
49
+
50
+
51
+ def rotation_payload(log: str, seq: int, prev_hash: str, kid: str, public_key_pem: str) -> bytes:
52
+ return jcs({"log": log, "seq": seq, "prev_hash": prev_hash, "kid": kid, "public_key_pem": public_key_pem})
53
+
54
+
55
+ def entry_hash(e: Dict[str, Any]) -> str:
56
+ body = {k: e[k] for k in ("seq", "kind", "name", "version", "seal_hash", "entry", "at", "prev_hash")}
57
+ return sha256_hex(jcs(body))
58
+
59
+
60
+ def verify_chain(entries: List[Dict[str, Any]]) -> Tuple[bool, Dict[int, str], str]:
61
+ prev, hash_at = GENESIS, {0: GENESIS}
62
+ for i, e in enumerate(entries):
63
+ if e.get("seq") != i + 1:
64
+ return False, hash_at, f"entry {i + 1}: its seq is {e.get('seq')}"
65
+ if e.get("prev_hash") != prev:
66
+ return False, hash_at, f"entry {e['seq']}: prev_hash does not match"
67
+ if entry_hash(e) != e.get("hash"):
68
+ return False, hash_at, f"entry {e['seq']}: its hash does not match its contents"
69
+ prev = e["hash"]
70
+ hash_at[e["seq"]] = prev
71
+ return True, hash_at, ""
72
+
73
+
74
+ def verify_registrar_log(entries: List[Dict[str, Any]], head: Dict[str, Any], public_key_pem: str, now: str,
75
+ max_head_age_seconds: int, previous: Optional[Dict[str, Any]] = None,
76
+ log: str = PLATFORM_LOG) -> Dict[str, Any]:
77
+ def fail(reason: str, detail: str) -> Dict[str, Any]:
78
+ return {"ok": False, "reason": reason, "detail": detail}
79
+
80
+ ok, hash_at, detail = verify_chain(entries)
81
+ if not ok:
82
+ return fail("chain_broken", detail)
83
+ size = head.get("size") if isinstance(head, dict) else None
84
+ if not isinstance(size, int) or isinstance(size, bool) or size < 0 or size > len(entries) or hash_at.get(size) != head.get("hash"):
85
+ return fail("head_mismatch", "the head does not name an entry of this chain")
86
+ if not head.get("signature") or not head.get("kid"):
87
+ return fail("head_unsigned", "the head is not signed")
88
+ if "log" in head and head["log"] != log:
89
+ return fail("wrong_log", f"the head is for log {head['log']!r}, not {log!r}")
90
+
91
+ pinned_suite = suite_for_key(public_key_pem)
92
+ if pinned_suite is None:
93
+ return fail("wrong_key", "the pinned key is not an Ed25519 or P-256 key in canonical form")
94
+ pinned_kid = S.compute_kid(public_key_pem)
95
+ vouched = entries[:size]
96
+ start = 0
97
+ for i, e in enumerate(vouched):
98
+ if e.get("kind") == "key" and e.get("name") == pinned_kid:
99
+ start = i + 1
100
+ break
101
+ pem = public_key_pem
102
+ for e in vouched[start:]:
103
+ if e.get("kind") != "key":
104
+ continue
105
+ new = (e.get("entry") or {}).get("public_key_pem")
106
+ if not isinstance(new, str) or suite_for_key(new) is None or S.compute_kid(new) != e.get("name"):
107
+ return fail("rotation_invalid", f"entry {e['seq']}: the new key is not canonical or its kid differs")
108
+ good, _ = S.verify(suite_for_key(pem), pem, rotation_payload(log, e["seq"], e["prev_hash"], e["name"], new),
109
+ {"signature": (e.get("entry") or {}).get("signature")})
110
+ if not good:
111
+ return fail("rotation_invalid", f"entry {e['seq']}: the rotation is not signed by the key in force")
112
+ pem = new
113
+
114
+ kid = S.compute_kid(pem)
115
+ if head.get("kid") != kid:
116
+ return fail("wrong_key", f"the head is signed by {head.get('kid')}, not the key in force {kid}")
117
+ suite = suite_for_key(pem)
118
+ if "algorithm" in head and head["algorithm"] != suite:
119
+ return fail("algorithm_mismatch", f"the head names {head['algorithm']!r}; the key in force verifies {suite} only")
120
+ good, _ = S.verify(suite, pem, head_payload(head, log), {"signature": head.get("signature")})
121
+ if not good:
122
+ return fail("bad_signature", "the head signature does not verify under the key in force")
123
+ t_head, t_now = _ts(head.get("at")), _ts(now)
124
+ if t_head is None:
125
+ return fail("head_stale", "the head carries no time")
126
+ age = t_now - t_head
127
+ if age < -60:
128
+ return fail("head_in_future", "the head is dated after now")
129
+ if age > max_head_age_seconds:
130
+ return fail("head_stale", f"the head is {round(age)} s old; the bound is {max_head_age_seconds} s")
131
+ if previous and hash_at.get(previous.get("size")) != previous.get("hash"):
132
+ return fail("history_rewritten", "the head kept earlier is not part of this log")
133
+ return {"ok": True, "size": len(entries), "head": {"size": size, "hash": head["hash"], "at": head["at"], "kid": kid}, "public_key_pem": pem}
134
+
135
+
136
+ def fold_registrar_log(entries: List[Dict[str, Any]], registrar_id: str, certified_scope: str = "always",
137
+ delegated: bool = False) -> Dict[str, Any]:
138
+ open_claims: Dict[str, Dict[str, Any]] = {}
139
+ closed_claims: List[Dict[str, Any]] = []
140
+ closures: List[Dict[str, Any]] = []
141
+ edges: List[Dict[str, Any]] = []
142
+ open_edges: Dict[str, Dict[str, Any]] = {}
143
+ supersessions: List[Dict[str, Any]] = []
144
+ revoked = set()
145
+ head = None
146
+ for e in entries:
147
+ head = e["hash"]
148
+ kind, name, x, at = e.get("kind"), e.get("name"), e.get("entry") or {}, e.get("at")
149
+ if kind == "applies":
150
+ if name in open_claims:
151
+ closed_claims.append({**open_claims[name], "until": at})
152
+ c = {"authority": name, "version": e.get("version"), "scope": x["scope"] if isinstance(x.get("scope"), str) else "always",
153
+ "exclusive": x.get("exclusive") is True, "from": at, "until": x["until"] if isinstance(x.get("until"), str) else None}
154
+ if isinstance(x.get("basis"), str):
155
+ c["basis"] = x["basis"]
156
+ open_claims[name] = c
157
+ elif kind == "withdrawn":
158
+ if name in open_claims:
159
+ closed_claims.append({**open_claims.pop(name), "until": at})
160
+ if name in open_edges:
161
+ edges.append({**open_edges.pop(name), "until": at})
162
+ elif kind == "revoked":
163
+ revoked.add(name)
164
+ elif kind == "closed":
165
+ c = {"scope": x["scope"] if isinstance(x.get("scope"), str) else "always",
166
+ "authorities": [a for a in x.get("authorities", []) if isinstance(a, str)] if isinstance(x.get("authorities"), list) else [],
167
+ "at": at, "label": name}
168
+ if isinstance(x.get("max_age_days"), (int, float)) and not isinstance(x.get("max_age_days"), bool):
169
+ c["max_age_days"] = x["max_age_days"]
170
+ closures.append(c)
171
+ elif kind == "recognizes":
172
+ if name in open_edges:
173
+ edges.append({**open_edges[name], "until": at})
174
+ edge = {"to": name, "scope": x["scope"] if isinstance(x.get("scope"), str) else "always", "from": at, "until": None}
175
+ if all(isinstance(x.get(k), str) for k in ("kid", "public_key_pem", "url")):
176
+ edge.update({"delegates": True, "kid": x["kid"], "public_key_pem": x["public_key_pem"], "url": x["url"],
177
+ "log": x["log"] if isinstance(x.get("log"), str) else registrar_log_name(name)})
178
+ open_edges[name] = edge
179
+ elif kind == "superseded":
180
+ if isinstance(x.get("by"), str):
181
+ supersessions.append({"superseded": name, "by": x["by"], "from": at})
182
+ record = {"id": registrar_id, "certified_scope": certified_scope, "claims": closed_claims + list(open_claims.values()),
183
+ "closures": closures, "recognitions": edges + list(open_edges.values()), "supersessions": supersessions,
184
+ "revoked": sorted(revoked), "head": head}
185
+ if delegated:
186
+ record["delegated"] = True
187
+ return record
188
+
189
+
190
+ def parse_dns_record(txt: Any) -> Optional[Dict[str, str]]:
191
+ """§2.5: `v=nomos1; id=…; url=…; kid=…`, or None when it is not one."""
192
+ if not isinstance(txt, str):
193
+ return None
194
+ fields: Dict[str, str] = {}
195
+ for part in txt.split(";"):
196
+ if "=" not in part:
197
+ continue
198
+ k, v = part.split("=", 1)
199
+ k, v = k.strip(), v.strip()
200
+ if k and k not in fields:
201
+ fields[k] = v
202
+ if fields.get("v") != "nomos1" or not all(fields.get(k) for k in ("id", "url", "kid")):
203
+ return None
204
+ return {"id": fields["id"], "url": fields["url"], "kid": fields["kid"]}
205
+
206
+
207
+ def discover(records: List[str], registrar_id: str, kid: str) -> Dict[str, Any]:
208
+ """§2.5: the log URL from the first record that is one; refused if it disagrees with what is held."""
209
+ for txt in records:
210
+ r = parse_dns_record(txt)
211
+ if r is None:
212
+ continue
213
+ if r["id"] != registrar_id or r["kid"] != kid:
214
+ return {"ok": False, "reason": "discovery_mismatch", "detail": "the record names another registrar or key"}
215
+ if not r["url"].startswith("https://"):
216
+ return {"ok": False, "reason": "discovery_mismatch", "detail": "the record's url is not https"}
217
+ return {"ok": True, "url": r["url"]}
218
+ return {"ok": False, "reason": "unreachable", "detail": "no _nomos-registrar record"}
219
+
220
+
221
+ def load_registrar_world(pins: List[Dict[str, Any]], logs: Callable[[str], Optional[Dict[str, Any]]], now: str,
222
+ max_head_age_seconds: int = 600, max_hops: int = 8, max_registrars: int = 32) -> Dict[str, Any]:
223
+ """§2.3: pins = [{id, url, public_key_pem, certified_scope, log?}]; logs(url) -> {entries, head} or None."""
224
+ registrars: Dict[str, Any] = {}
225
+ absent: Dict[str, str] = {}
226
+ pinned = {p["id"] for p in pins}
227
+ frontier = [{"id": p["id"], "url": p["url"], "pem": p["public_key_pem"], "log": p.get("log") or registrar_log_name(p["id"]),
228
+ "scope": p["certified_scope"], "delegated": False, "hop": 0} for p in sorted(pins, key=lambda p: p["id"])]
229
+ seen = set()
230
+ t_now = _ts(now)
231
+ while frontier:
232
+ batch = [j for j in frontier if j["id"] not in seen]
233
+ loaded_before = len(registrars)
234
+ nxt: Dict[str, Tuple[Dict[str, Any], set]] = {}
235
+ for i, j in enumerate(batch):
236
+ seen.add(j["id"])
237
+ if loaded_before + i >= max_registrars:
238
+ absent[j["id"]] = "beyond_bounds"
239
+ continue
240
+ got = logs(j["url"])
241
+ if got is None:
242
+ absent[j["id"]] = "unreachable"
243
+ continue
244
+ head = got.get("head") or {}
245
+ entries = got.get("entries") or []
246
+ size = head.get("size")
247
+ vouched = entries[:size] if isinstance(size, int) and size >= 0 else entries
248
+ check = verify_registrar_log(vouched, head, j["pem"], now, max_head_age_seconds, None, j["log"])
249
+ if not check["ok"]:
250
+ absent[j["id"]] = check["reason"]
251
+ continue
252
+ rec = fold_registrar_log(vouched, j["id"], j["scope"], j["delegated"])
253
+ rec["head_at"] = check["head"]["at"]
254
+ registrars[j["id"]] = rec
255
+ for e in rec["recognitions"]:
256
+ if not e.get("delegates") or e.get("until") or e["to"] in pinned:
257
+ continue
258
+ if e.get("from") and _ts(e["from"]) > t_now:
259
+ continue
260
+ job = {"id": e["to"], "url": e["url"], "pem": e["public_key_pem"], "log": e["log"], "scope": "always", "delegated": True, "hop": j["hop"] + 1}
261
+ if e["to"] in nxt:
262
+ nxt[e["to"]][1].add(e["kid"])
263
+ else:
264
+ nxt[e["to"]] = (job, {e["kid"]})
265
+ frontier = []
266
+ for rid in sorted(nxt):
267
+ job, kids = nxt[rid]
268
+ if rid in seen or rid in absent:
269
+ continue
270
+ if len(kids) > 1:
271
+ absent[rid] = "key_disagreement"
272
+ seen.add(rid)
273
+ continue
274
+ if job["hop"] > max_hops:
275
+ absent[rid] = "beyond_bounds"
276
+ seen.add(rid)
277
+ continue
278
+ frontier.append(job)
279
+ return {"world": {"pins": sorted(p["id"] for p in pins), "registrars": registrars, "max_head_age_seconds": max_head_age_seconds}, "absent": absent}
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nomosprotocol
3
- Version: 0.1.0
4
- Summary: NOMOS for Python: the reference verifiers for NOMOS-SPEC-007, -008 and -010, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs.
3
+ Version: 0.2.0
4
+ Summary: NOMOS for Python: the reference verifiers for NOMOS-SPEC-007 (rev. 1.11), -008 and -010, NOMOS-SPEC-014 registrar logs, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs.
5
5
  Author-email: NOMOS Protocol <hello@nomosprotocol.com>
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://www.computableauthority.com
@@ -109,7 +109,7 @@ chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
109
109
  ## Conformance
110
110
 
111
111
  This package is checked against:
112
- - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.9, rev. 1.10 revocation sources), NOMOS-SPEC-008
112
+ - every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.11, rev. 1.10 revocation sources), NOMOS-SPEC-008
113
113
  0.6.0 and NOMOS-SPEC-010 0.2.0;
114
114
  - the NOMOS-SPEC-009 selection vectors;
115
115
  - the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
@@ -3,10 +3,12 @@ pyproject.toml
3
3
  nomosprotocol/__init__.py
4
4
  nomosprotocol/accept.py
5
5
  nomosprotocol/act.py
6
+ nomosprotocol/bindings.py
6
7
  nomosprotocol/carrier.py
7
8
  nomosprotocol/chain.py
8
9
  nomosprotocol/issuer.py
9
10
  nomosprotocol/jcs.py
11
+ nomosprotocol/registrar.py
10
12
  nomosprotocol/statements.py
11
13
  nomosprotocol/suites.py
12
14
  nomosprotocol/witness.py
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "nomosprotocol"
7
- version = "0.1.0"
8
- description = "NOMOS for Python: the reference verifiers for NOMOS-SPEC-007, -008 and -010, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs."
7
+ version = "0.2.0"
8
+ description = "NOMOS for Python: the reference verifiers for NOMOS-SPEC-007 (rev. 1.11), -008 and -010, NOMOS-SPEC-014 registrar logs, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
11
11
  license = { text = "MIT" }
File without changes