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/act.py ADDED
@@ -0,0 +1,462 @@
1
+ """
2
+ NOMOS-SPEC-008 0.6.0 reference verifier — Act Binding.
3
+
4
+ Verifies a self-verifying Act at the relying party (the system that commits the change):
5
+ 1. the Act is addressed to this relying party, inside its validity window, not replayed
6
+ 2. the authority artifact's issuer resolves to the pinned root, scope-aware (NOMOS-SPEC-007
7
+ rev. 1.9 §4.2a), its seal verifies, it is the version in force under the relying party's
8
+ declared currency policy (§5.4, §5.5), and its escalations are unambiguous (step 5b)
9
+ 3. every fact is testimony from a witness whose chain carries `claim:` scope for it
10
+ (NOMOS-SPEC-007 rev. 1.8 §3.4.1), or comes from the channel its data_contract declares,
11
+ and has the type that input declares (SPEC-008 §7.1)
12
+ 4. the sealed rules are evaluated over exactly those facts and exactly this action
13
+ (NOMOS-SPEC-001 §4, with the §4.6 default-outcome amendment), three-valued: a condition
14
+ that needs an absent fact is UNDECIDED, and an allow or escalate result stands only when
15
+ every block or escalate rule that outranks it is decided (SPEC-008 §6.2)
16
+ 5. an ESCALATED verdict becomes AUTHORIZED only with consents from enough distinct people
17
+ (§4.4), each signed over this Act's binding digest, by Ed25519, ES256 or passkey (§4.5)
18
+
19
+ Signatures follow NOMOS-SPEC-010; chain resolution is chain.py in this package.
20
+ Everything is resolved from the Act itself plus the relying party's own configuration
21
+ (pinned root, its own identifier, its own state facts, its nonce ledger). No network call.
22
+
23
+ Requires: Python 3.9+, `pip install cryptography`.
24
+ """
25
+ import math
26
+ import re
27
+ from datetime import datetime
28
+ from typing import Any, Dict, Optional, Set, Tuple
29
+
30
+ from . import chain, suites
31
+ from .chain import ts, cert_payload, ScopeError, parse_scope, contains, meta_matches # noqa: F401
32
+ from .jcs import jcs, jcs_text as _jcs, sha256_hex
33
+
34
+ MAX_CHAIN = chain.MAX_CHAIN
35
+ MAX_WINDOW_SECONDS = 300 # SPEC-008 §5.3 RECOMMENDED upper bound on an Act's validity
36
+ MAX_IN_FORCE_SECONDS = 86400 # SPEC-008 §5.4: an in-force statement lives at most one day
37
+ ARTIFACT_DIMS = ("artifact", "industry", "jurisdiction")
38
+ STATEMENT_DIMS = ("claim", "consent")
39
+ ISO_3166 = re.compile(r"^[A-Z]{2}(-[A-Z0-9]{1,3})?$")
40
+ FACT_SOURCES = ("action", "testimony", "relying_party", "presenter")
41
+ # Channels whose absence is itself a fact: the action is exactly what will be committed, and the
42
+ # relying party reads its own state. For these, exists(f) is decided (SPEC-008 §6.2 rule 2).
43
+ ABSENCE_AUTHORITATIVE = ("action", "relying_party")
44
+ _DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
45
+ _DATETIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
46
+
47
+ def type_ok(value: Any, spec: dict) -> bool:
48
+ """SPEC-008 §7.1: a present fact has exactly the JSON type its input declares."""
49
+ t = spec.get("type")
50
+ if t == "string": return isinstance(value, str)
51
+ if t == "number": return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
52
+ if t == "integer": return (isinstance(value, int) and not isinstance(value, bool)) or (isinstance(value, float) and math.isfinite(value) and value.is_integer())
53
+ if t == "boolean": return isinstance(value, bool)
54
+ if t == "date": return isinstance(value, str) and bool(_DATE.match(value))
55
+ if t == "datetime": return isinstance(value, str) and bool(_DATETIME.match(value))
56
+ if t == "enum": return isinstance(value, str) and value in (spec.get("enum") or [])
57
+ if t == "object": return isinstance(value, dict)
58
+ if t == "array": return isinstance(value, list)
59
+ return False # no type, or one this verifier does not know: fail closed
60
+
61
+
62
+ # §6.3 (0.6.0): the suites each statement may be signed under (NOMOS-SPEC-010)
63
+ TESTIMONY_SUITES = ("Ed25519", "ES256") # testimony and in-force statements
64
+ CONSENT_SUITES = ("Ed25519", "ES256", "WebAuthn-ES256")
65
+ CURRENCY_POLICIES = ("record", "record_or_statement")
66
+ WEBAUTHN_FIELDS = ("authenticator_data", "client_data_json", "signature")
67
+
68
+ def proof_of(st: dict) -> dict:
69
+ """The NOMOS-SPEC-010 proof object a statement carries for its suite."""
70
+ if st.get("algorithm") == "WebAuthn-ES256": return {k: st.get(k) for k in WEBAUTHN_FIELDS}
71
+ return {"signature": st.get("signature")}
72
+
73
+ def statement_sig(pem: str, st: dict, payload: dict) -> Tuple[bool, Optional[str]]:
74
+ return suites.verify(st.get("algorithm"), pem, jcs(payload), proof_of(st))
75
+
76
+ def ambiguous_escalation(art: dict) -> bool:
77
+ """NOMOS-SPEC-001 amendment 2.3.0: two escalate decisions of equal priority naming different
78
+ escalations. The verdict would depend on which is listed first (R-19 §7.5)."""
79
+ named: Dict[Any, Set[Any]] = {}
80
+ for d in (art.get("logic") or {}).get("decisions") or []:
81
+ t = (d.get("then") or [{}])[0]
82
+ if t.get("type") == "escalate": named.setdefault(d.get("priority"), set()).add(t.get("escalation_id"))
83
+ return any(len(ids) > 1 for ids in named.values())
84
+
85
+
86
+ # ── signed payloads ─────────────────────────────────────────────────────────────────────
87
+ def testimony_payload(t): return {k: t.get(k) for k in ("claim", "value", "about", "as_of", "valid_until", "kid")}
88
+ def consent_payload(c): return {k: c.get(k) for k in ("binding_digest", "role", "decision", "signed_at", "kid")}
89
+ def in_force_payload(s): return {k: s.get(k) for k in ("artifact_id", "version", "seal_hash", "as_of", "valid_until", "kid")}
90
+
91
+ def binding_core(act: dict) -> dict:
92
+ """SPEC-008 §4: what every consent signs, and what the relying party commits."""
93
+ art = (act.get("authority") or {}).get("artifact") or {}
94
+ return {
95
+ "act_version": act.get("act_version"), "act_id": act.get("act_id"), "nonce": act.get("nonce"),
96
+ "issued_at": act.get("issued_at"), "expires_at": act.get("expires_at"),
97
+ "relying_party": act.get("relying_party"), "action": act.get("action"),
98
+ "artifact_hash": (art.get("seal") or {}).get("hash"),
99
+ "testimony_digest": sha256_hex(jcs(sorted((act.get("testimony") or []), key=lambda t: _jcs(t)))),
100
+ }
101
+
102
+ def binding_digest(act: dict) -> str: return sha256_hex(jcs(binding_core(act)))
103
+
104
+
105
+ # ── chain resolution: NOMOS-SPEC-007 rev. 1.9, shared (python/nomosprotocol/chain.py) ─────────────
106
+ def resolve_statement_key(kind: str, name: str, st: dict, pool: list, root_pem: str, now: datetime,
107
+ meta: dict, revoked_kids: Set[str], revoked_certs: Set[str]) -> dict:
108
+ """§4.6: resolve a witness or approver key for one statement, scope-aware (rev. 1.9 §4.2a),
109
+ under the statement's own suite. A consent key must carry an `approver` (§4.4), and every
110
+ admitted path to it is collected so the approver cannot depend on the path presented."""
111
+ consent = kind == "consent"
112
+ admit = chain.for_statement(kind, name, meta, st["algorithm"], required=("approver",) if consent else ())
113
+ return chain.resolve(st["kid"], pool, root_pem, now, admit, revoked_kids, revoked_certs, all_paths=consent)
114
+
115
+ def statement_failure(r: dict, invalid: str, out_of_scope: str, **who) -> dict:
116
+ """An admission failure (the key is genuine but not permitted this statement) is *_OUT_OF_SCOPE;
117
+ every other failure of the witness's or approver's chain is *_INVALID (SPEC-007 rev. 1.8 §4.6)."""
118
+ if r["decision"] == "OUT_OF_SCOPE" and "reason_code" not in r:
119
+ return {"decision": out_of_scope, **who, "dimension": r["dimension"]}
120
+ prefix = "witness_" if invalid == "TESTIMONY_INVALID" else "approver_"
121
+ return {"decision": invalid, **who, "reason_code": prefix + r["decision"].lower()}
122
+
123
+
124
+ # ── Nomos-Expr v1 evaluator (SPEC-001 §4.1), three-valued (SPEC-008 §6.2) ──────────────
125
+ # A condition is TRUE, FALSE or UNDECIDED. A fact that is absent (or null) is not false: any
126
+ # primitive that reads it is UNDECIDED, and and/or/not follow Kleene's strong three-valued logic.
127
+ T, F, U = "TRUE", "FALSE", "UNDECIDED"
128
+ _TOK = re.compile(r'\s*(?:(?P<num>-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|(?P<str>"[^"]*")|(?P<op>==|!=|>=|<=|>|<|\(|\)|,)|(?P<id>[A-Za-z_][\w.]*))')
129
+
130
+ def _tokens(s: str) -> list:
131
+ pos, out = 0, []
132
+ while pos < len(s):
133
+ if s[pos:].strip() == "": break
134
+ m = _TOK.match(s, pos)
135
+ if not m or m.end() == pos: raise ValueError(f"cannot parse at {pos}: {s[pos:pos+20]!r}")
136
+ kind = m.lastgroup; val = m.group(kind); pos = m.end()
137
+ out.append((kind, val))
138
+ return out
139
+
140
+ def _lookup(facts: dict, path: str):
141
+ cur: Any = facts
142
+ for part in path.split("."):
143
+ if not isinstance(cur, dict) or part not in cur: return None
144
+ cur = cur[part]
145
+ return cur
146
+
147
+ def _tri(b) -> str: return T if b else F
148
+ def _and(a, b): return F if F in (a, b) else (U if U in (a, b) else T)
149
+ def _or(a, b): return T if T in (a, b) else (U if U in (a, b) else F)
150
+ def _not(a): return {T: F, F: T, U: U}[a]
151
+
152
+ class _Absent: pass
153
+ ABSENT = _Absent()
154
+
155
+ def _kind(x) -> str:
156
+ """The JSON type of a present value. Booleans are not numbers."""
157
+ if isinstance(x, bool): return "boolean"
158
+ if isinstance(x, (int, float)): return "number"
159
+ if isinstance(x, str): return "string"
160
+ if isinstance(x, dict): return "object"
161
+ if isinstance(x, list): return "array"
162
+ return "other"
163
+ # SPEC-008 §6.2 rule 3: a primitive whose present operands are outside its domain is UNDECIDED,
164
+ # like an absent one. A value of the wrong kind says nothing decisive about the condition, and
165
+ # reading it as FALSE would let a presenter silence a deny rule by choosing the kind.
166
+
167
+ class _Parser:
168
+ def __init__(self, toks, facts, decided_absent=()):
169
+ self.t, self.i, self.f, self.da = toks, 0, facts, decided_absent
170
+ self.undecided_by: Set[str] = set() # fields that left some primitive UNDECIDED
171
+ def _u(self, *ops) -> str:
172
+ """UNDECIDED, recording which fields made it so: they are what would decide the rule."""
173
+ self.undecided_by.update(o[1] for o in ops if isinstance(o, tuple))
174
+ return U
175
+ def peek(self): return self.t[self.i] if self.i < len(self.t) else (None, None)
176
+ def take(self): tok = self.peek(); self.i += 1; return tok
177
+ def expr(self):
178
+ v = self.andx()
179
+ while self.peek() == ("id", "or"): self.take(); v = _or(v, self.andx())
180
+ return v
181
+ def andx(self):
182
+ v = self.unary()
183
+ while self.peek() == ("id", "and"): self.take(); v = _and(v, self.unary())
184
+ return v
185
+ def unary(self):
186
+ if self.peek() == ("id", "not"): self.take(); return _not(self.unary())
187
+ return self.primary()
188
+ def operand(self):
189
+ k, v = self.take()
190
+ if k == "num": return float(v) if any(c in v for c in ".eE") else int(v)
191
+ if k == "str": return v[1:-1]
192
+ if k == "id":
193
+ if v == "true": return True
194
+ if v == "false": return False
195
+ if v == "always": return True
196
+ return ("FIELD", v)
197
+ raise ValueError(f"unexpected {v!r}")
198
+ def val(self, x):
199
+ """A literal, the fact's value, or ABSENT when the fact is missing or null."""
200
+ if not isinstance(x, tuple): return x
201
+ got = _lookup(self.f, x[1])
202
+ return ABSENT if got is None else got
203
+ def primary(self) -> str:
204
+ k, v = self.peek()
205
+ if (k, v) == ("op", "("):
206
+ self.take(); r = self.expr(); self.take(); return r
207
+ if k == "id" and v in ("exists", "matches") and self.t[self.i + 1:self.i + 2] == [("op", "(")]:
208
+ self.take(); self.take(); f = self.operand()
209
+ if v == "exists":
210
+ self.take()
211
+ if self.val(f) is not ABSENT: return T
212
+ # Absence decides exists() only where absence is authoritative (§6.2 rule 2):
213
+ # a missing witness statement is unknown, not a statement that nothing exists.
214
+ name = f[1] if isinstance(f, tuple) else None
215
+ return F if name is not None and (name in self.da or name.split(".")[0] in self.da) else self._u(f)
216
+ self.take(); pat = self.operand(); self.take()
217
+ x = self.val(f)
218
+ if x is ABSENT or _kind(x) != "string": return self._u(f)
219
+ return _tri(re.search(pat, x) is not None)
220
+ left = self.operand()
221
+ k2, op = self.peek()
222
+ if k2 == "op" and op in ("==", "!=", ">", ">=", "<", "<="):
223
+ self.take(); right = self.operand()
224
+ a, b = self.val(left), self.val(right)
225
+ # §6.2: open_facts names the fields that left the primitive undecided — the absent ones,
226
+ # not a present operand beside them.
227
+ if a is ABSENT or b is ABSENT: return self._u(*[x for x, v in ((left, a), (right, b)) if v is ABSENT])
228
+ ka, kb = _kind(a), _kind(b)
229
+ if ka != kb or ka == "other" or (op not in ("==", "!=") and ka not in ("number", "string")): return self._u(left, right)
230
+ if ka in ("object", "array"):
231
+ eq = jcs(a) == jcs(b)
232
+ return _tri(eq if op == "==" else not eq)
233
+ return _tri({"==": a == b, "!=": a != b, ">": a > b, ">=": a >= b, "<": a < b, "<=": a <= b}[op])
234
+ if (k2, op) in (("id", "in"), ("id", "contains"), ("id", "between")):
235
+ self.take(); right = self.operand(); rhs = self.val(right); a = self.val(left)
236
+ if a is ABSENT or rhs is ABSENT: return self._u(*[x for x, v in ((left, a), (right, rhs)) if v is ABSENT])
237
+ if op == "between":
238
+ if _kind(a) != "number": return self._u(left)
239
+ lo, hi = (float(p) for p in str(rhs).split(","))
240
+ return _tri(lo <= a <= hi)
241
+ if _kind(a) not in ("string", "number", "boolean"): return self._u(left)
242
+ if op == "in": return _tri(str(a) in [p.strip() for p in str(rhs).split(",")])
243
+ return _tri(str(rhs).lower() in str(a).lower())
244
+ x = self.val(left)
245
+ return self._u(left) if x is ABSENT or _kind(x) != "boolean" else _tri(x)
246
+
247
+ def eval_when_detail(expr: str, facts: dict, decided_absent=()) -> Tuple[str, Set[str]]:
248
+ p = _Parser(_tokens(expr), facts, decided_absent)
249
+ r = p.expr()
250
+ if p.i != len(p.t): raise ValueError(f"trailing tokens in {expr!r}")
251
+ return r, p.undecided_by
252
+
253
+ def eval_when(expr: str, facts: dict, decided_absent=()) -> str:
254
+ return eval_when_detail(expr, facts, decided_absent)[0]
255
+
256
+ RANK = {"block": 3, "escalate": 2, "allow": 1}
257
+ TIE_ORDERS = {"deny_wins": RANK, "allow_wins": {"allow": 3, "escalate": 2, "block": 1}, "escalate_wins": {"escalate": 3, "block": 2, "allow": 1}}
258
+
259
+ def evaluate(artifact: dict, facts: dict) -> dict:
260
+ logic = artifact["logic"]; res = logic.get("resolution", {})
261
+ order = TIE_ORDERS[res.get("tie_breaker", "deny_wins")]
262
+ inputs = artifact.get("data_contract", {}).get("inputs", {})
263
+ 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"]]
265
+ results = [(d, r) for d, r, _ in detail]
266
+ undecided_by = {d["id"]: u for d, _, u in detail}
267
+ matched = [d for d, r in results if r == T]
268
+ if not matched:
269
+ default = res.get("default_outcome", "block") # SPEC-001 §4.6 amendment; SPEC-008 §6.1
270
+ ev = {"outcome": default, "rule": None, "reason_code": "no_matching_rule", "escalation_id": res.get("default_escalation_id")}
271
+ decider = None
272
+ else:
273
+ top = max(d["priority"] for d in matched)
274
+ best = [d for d in matched if d["priority"] == top]
275
+ decider = max(best, key=lambda x: order[x["then"][0]["type"]])
276
+ t = decider["then"][0]
277
+ ev = {"outcome": t["type"], "rule": decider["id"], "escalation_id": t.get("escalation_id")}
278
+ # SPEC-008 §6.2: a result that could commit stands only if nothing that outranks it is undecided.
279
+ if ev["outcome"] in ("allow", "escalate"):
280
+ def outranks(d) -> bool:
281
+ if decider is None: return True
282
+ if d["priority"] != decider["priority"]: return d["priority"] > decider["priority"]
283
+ return order[d["then"][0]["type"]] > order[ev["outcome"]]
284
+ def same_rank_other_escalation(d) -> bool: # §6.2 (0.5.0): equal priority, both escalate, different escalation
285
+ return (decider is not None and ev["outcome"] == "escalate" and d["then"][0]["type"] == "escalate"
286
+ and d["priority"] == decider["priority"] and d["then"][0].get("escalation_id") != ev.get("escalation_id"))
287
+ open_rules = [d for d, r in results if r == U and d["then"][0]["type"] in ("block", "escalate") and (outranks(d) or same_rank_other_escalation(d))]
288
+ if open_rules:
289
+ open_rules.sort(key=lambda d: -d["priority"])
290
+ return {"outcome": "undecided", "rule": ev["rule"],
291
+ "open_rules": [d["id"] for d in open_rules],
292
+ "open_facts": sorted({f for d in open_rules for f in undecided_by[d["id"]]})}
293
+ return ev
294
+
295
+
296
+ # ── the Act verifier (SPEC-008 §6) ──────────────────────────────────────────────────────
297
+ def verify_act(act: Any, *, relying_party_id: str, root_pem: str, now: datetime,
298
+ seen_nonces: Set[str], currency_policy: str, local_facts: Optional[dict] = None,
299
+ revoked_kids: Optional[Set[str]] = None, revoked_certs: Optional[Set[str]] = None,
300
+ 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
303
+ (§5.4); `revoked_artifacts` the seal hashes its revocation source lists (NOMOS-SPEC-006);
304
+ `currency_policy` the policy it declares for establishing currency (§5.5): "record" or
305
+ "record_or_statement". There is no default: the choice is the relying party's to declare.
306
+ `max_window_seconds` is the relying party's own maximum Act window (§5.1), 300 unless it
307
+ configures otherwise, for example to leave a human time to approve (NOMOS-SPEC-009 §6.3)."""
308
+ if currency_policy not in CURRENCY_POLICIES: raise ValueError(f"currency_policy must be one of {CURRENCY_POLICIES}")
309
+ revoked_kids = revoked_kids or set(); revoked_certs = revoked_certs or set(); local_facts = local_facts or {}
310
+ in_force = in_force or {}; revoked_artifacts = revoked_artifacts or set()
311
+ # 1. structure
312
+ need = ("act_version", "act_id", "nonce", "issued_at", "expires_at", "relying_party", "action", "authority")
313
+ if not isinstance(act, dict) or any(k not in act for k in need) or act.get("act_version") != "1" \
314
+ or not isinstance(act.get("authority"), dict):
315
+ return {"decision": "MALFORMED", "reason_code": "bad_envelope"}
316
+ try:
317
+ jcs(act) # an Act RFC 8785 cannot canonicalize (e.g. NaN, Infinity) has no binding digest
318
+ except (ValueError, TypeError):
319
+ return {"decision": "MALFORMED", "reason_code": "not_canonicalizable"}
320
+ action, auth = act["action"], act["authority"]
321
+ if not isinstance(action, dict) or not isinstance(action.get("type"), str) or not isinstance(action.get("params", {}), dict):
322
+ return {"decision": "MALFORMED", "reason_code": "bad_action"}
323
+ art, pool = auth.get("artifact"), auth.get("key_certs", [])
324
+ bad = chain.check_pool(pool) or chain.check_seal_shape(art)
325
+ if bad: return {"decision": "MALFORMED", "reason_code": bad}
326
+ seal = art["seal"]
327
+ try:
328
+ t0, t1 = ts(act["issued_at"]), ts(act["expires_at"])
329
+ except (ValueError, TypeError):
330
+ return {"decision": "MALFORMED", "reason_code": "bad_time"}
331
+ if (t1 - t0).total_seconds() > max_window_seconds or t1 <= t0:
332
+ return {"decision": "MALFORMED", "reason_code": "validity_window"}
333
+ # 2-4. addressed to us, in time, not replayed
334
+ if act["relying_party"] != relying_party_id: return {"decision": "WRONG_RELYING_PARTY"}
335
+ if now < t0: return {"decision": "NOT_YET_VALID"}
336
+ if now > t1: return {"decision": "EXPIRED"}
337
+ if act["nonce"] in seen_nonces: return {"decision": "REPLAYED"}
338
+ # 5. authority: SPEC-007 §4 for the artifact itself
339
+ # Scope-aware (rev. 1.9 §4.2a): a path whose scope does not admit this artifact is a failed
340
+ # candidate. The resolved key is the same on every path, so the seal is checked once, after.
341
+ meta = art.get("meta", {})
342
+ r = chain.resolve(seal["kid"], pool, root_pem, now, chain.for_artifact(meta, seal["signature_algorithm"]), revoked_kids, revoked_certs)
343
+ if r["decision"] != "RESOLVED": return r
344
+ failure = chain.seal_failure(art, r["key"])
345
+ if failure: return failure
346
+ # 5a. the authority in force at `now` (§5.4): genuine is not enough, it must also be current.
347
+ # A superseded version stays valid for verifying past decisions; it cannot authorize new ones.
348
+ art_id = meta.get("artifact_id")
349
+ if seal["hash"] in revoked_artifacts:
350
+ return {"decision": "ARTIFACT_REVOKED", "artifact_id": art_id}
351
+ if art_id in in_force:
352
+ if in_force[art_id] != seal["hash"]:
353
+ return {"decision": "SUPERSEDED", "artifact_id": art_id, "in_force_seal_hash": in_force[art_id]}
354
+ in_force_source = "record"
355
+ elif currency_policy == "record":
356
+ # §5.5: only the relying party's own record establishes currency; no statement is read,
357
+ # so a compromised issuer key cannot make a version current (R-19 Theorem 9.4).
358
+ return {"decision": "VERSION_UNVERIFIED", "artifact_id": art_id, "reason_code": "not_in_record"}
359
+ else:
360
+ st = auth.get("in_force")
361
+ def unverified(reason): return {"decision": "VERSION_UNVERIFIED", "artifact_id": art_id, "reason_code": reason}
362
+ if st is None: return unverified("no_in_force_evidence")
363
+ 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")) \
364
+ or st.get("algorithm") not in TESTIMONY_SUITES:
365
+ return unverified("bad_statement")
366
+ if st["artifact_id"] != art_id or st["seal_hash"] != seal["hash"] or st["version"] != meta.get("version"):
367
+ return unverified("statement_mismatch")
368
+ if st["kid"] != seal["kid"] or not chain.suite_permitted(r["effective"], st["algorithm"]) \
369
+ or not statement_sig(r["key"], st, in_force_payload(st))[0]:
370
+ return unverified("bad_signature")
371
+ try:
372
+ sa, su = ts(st["as_of"]), ts(st["valid_until"])
373
+ except (ValueError, TypeError):
374
+ return unverified("bad_statement")
375
+ if (su - sa).total_seconds() > MAX_IN_FORCE_SECONDS or su <= sa: return unverified("statement_window")
376
+ if now < sa or now > su: return unverified("stale")
377
+ in_force_source = "statement"
378
+ # 5b. an authority whose verdict would depend on listing order cannot authorize (SPEC-001 2.3.0)
379
+ if ambiguous_escalation(art): return {"decision": "MALFORMED", "reason_code": "ambiguous_escalation"}
380
+ # 6. testimony
381
+ facts: Dict[str, Any] = {}; channel: Dict[str, str] = {}
382
+ def put(name, value, src):
383
+ if name in channel: raise KeyError(name)
384
+ facts[name] = value; channel[name] = src
385
+ subject = action.get("subject")
386
+ for t in act.get("testimony") or []:
387
+ if not isinstance(t, dict) or not all(k in t for k in ("claim", "value", "as_of", "valid_until", "kid", "signature")) \
388
+ or t.get("algorithm") not in TESTIMONY_SUITES:
389
+ return {"decision": "MALFORMED", "reason_code": "bad_testimony"}
390
+ w = resolve_statement_key("claim", t["claim"], t, pool, root_pem, now, meta, revoked_kids, revoked_certs)
391
+ if w["decision"] != "RESOLVED":
392
+ return statement_failure(w, "TESTIMONY_INVALID", "TESTIMONY_OUT_OF_SCOPE", claim=t["claim"])
393
+ ok, why = statement_sig(w["key"], t, testimony_payload(t))
394
+ if not ok: return {"decision": "TESTIMONY_INVALID", "claim": t["claim"], "reason_code": why}
395
+ try:
396
+ fresh = ts(t["as_of"]) <= now <= ts(t["valid_until"])
397
+ except (ValueError, TypeError, AttributeError):
398
+ fresh = False # an unreadable window is not a current one
399
+ if not fresh: return {"decision": "TESTIMONY_INVALID", "claim": t["claim"], "reason_code": "stale"}
400
+ if t.get("about") is not None and t.get("about") != subject:
401
+ return {"decision": "TESTIMONY_INVALID", "claim": t["claim"], "reason_code": "wrong_subject"}
402
+ try: put(t["claim"], t["value"], "testimony")
403
+ except KeyError: return {"decision": "FACT_SOURCE_VIOLATION", "field": t["claim"], "reason_code": "duplicate"}
404
+ # 7. facts from the other three channels, checked against the declared source of each input
405
+ try:
406
+ put("action_type", action["type"], "action")
407
+ for k, v in (action.get("params") or {}).items(): put(k, v, "action")
408
+ for k, v in (act.get("presenter_facts") or {}).items(): put(k, v, "presenter")
409
+ for k, v in local_facts.items(): put(k, v, "relying_party")
410
+ except KeyError as e:
411
+ return {"decision": "FACT_SOURCE_VIOLATION", "field": e.args[0], "reason_code": "duplicate"}
412
+ inputs = art.get("data_contract", {}).get("inputs", {})
413
+ for name, src in channel.items():
414
+ if name == "action_type": continue
415
+ declared = (inputs.get(name) or {}).get("source")
416
+ if declared is None:
417
+ return {"decision": "FACT_SOURCE_VIOLATION", "field": name, "reason_code": "undeclared_input"}
418
+ if declared != src:
419
+ return {"decision": "FACT_SOURCE_VIOLATION", "field": name, "declared": declared, "supplied_via": src}
420
+ # 7b. every present fact has the type its input declares (§7.1); null is absence, not a type
421
+ for name, value in facts.items():
422
+ if name == "action_type" or value is None: continue
423
+ if not type_ok(value, inputs[name]):
424
+ return {"decision": "FACT_TYPE_VIOLATION", "field": name, "declared": inputs[name].get("type"), "supplied_via": channel[name]}
425
+ # 8. evaluate the sealed rules over exactly these facts
426
+ try:
427
+ ev = evaluate(art, facts)
428
+ except (ValueError, KeyError, TypeError, IndexError):
429
+ return {"decision": "MALFORMED", "reason_code": "unevaluable_rules", "commit": False} # never commit what cannot be evaluated
430
+ digest = binding_digest(act)
431
+ base = {"rule": ev["rule"], "act_digest": digest, "in_force_source": in_force_source, "currency_policy": currency_policy}
432
+ 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}
435
+ if ev.get("reason_code"): base["reason_code"] = ev["reason_code"]
436
+ if ev["outcome"] == "allow": return {"decision": "AUTHORIZED", "commit": True, **base}
437
+ if ev["outcome"] == "block": return {"decision": "DENIED", "commit": False, **base}
438
+ # 9. escalation: consents bound to this exact Act
439
+ esc = next((e for e in art.get("governance", {}).get("escalations", []) if e.get("id") == ev["escalation_id"]), None)
440
+ if esc is None: return {"decision": "ESCALATED", "commit": False, "escalation_id": ev["escalation_id"], "consents_valid": 0, "consents_required": None, **base}
441
+ role, need_n = esc["role_required"], int(esc.get("required_consents", 1))
442
+ approvers: Set[str] = set()
443
+ for c in act.get("consents") or []:
444
+ if not isinstance(c, dict) or not all(isinstance(c.get(k), str) for k in ("binding_digest", "role", "decision", "signed_at", "kid", "signature")) \
445
+ or c.get("algorithm") not in CONSENT_SUITES \
446
+ or (c["algorithm"] == "WebAuthn-ES256" and not all(isinstance(c.get(k), str) for k in WEBAUTHN_FIELDS)):
447
+ return {"decision": "MALFORMED", "reason_code": "bad_consent"}
448
+ k = resolve_statement_key("consent", c["role"], c, pool, root_pem, now, meta, revoked_kids, revoked_certs)
449
+ if k["decision"] != "RESOLVED":
450
+ r = statement_failure(k, "CONSENT_INVALID", "CONSENT_OUT_OF_SCOPE", role=c["role"])
451
+ if r["decision"] == "CONSENT_INVALID": r.pop("role")
452
+ return r
453
+ # §4.4: the person a consent counts for must not depend on which certificates were sent
454
+ if len({e["approver"] for e in k["admitted"]}) > 1: return {"decision": "CONSENT_INVALID", "reason_code": "approver_ambiguous"}
455
+ ok, why = statement_sig(k["key"], c, consent_payload(c))
456
+ if not ok: return {"decision": "CONSENT_INVALID", "reason_code": why}
457
+ if c["binding_digest"] != digest: return {"decision": "CONSENT_INVALID", "reason_code": "binding_mismatch"}
458
+ if c["decision"] == "approve" and c["role"] == role: approvers.add(k["effective"]["approver"])
459
+ # §4.4: n consents means n distinct people, never n keys
460
+ if len(approvers) >= need_n:
461
+ return {"decision": "AUTHORIZED", "commit": True, "by_consent": True, "escalation_id": ev["escalation_id"], "consents_valid": len(approvers), "consents_required": need_n, **base}
462
+ return {"decision": "ESCALATED", "commit": False, "escalation_id": ev["escalation_id"], "consents_valid": len(approvers), "consents_required": need_n, **base}
@@ -0,0 +1,178 @@
1
+ """act(): the carrier, an agent taking an action at a system it may never have met.
2
+
3
+ r = act(to="https://shop.example", action={"type": "purchase", "subject": "DEPT-17", "params": {"amount": 500}})
4
+ if r["status"] == "committed": print(r["receipt"])
5
+
6
+ It follows NOMOS-SPEC-009 end to end: discovers the relying party (§3.1) and the authority's issuer
7
+ (§3.2), fetches the sealed authority, asks the issuer's witnesses for the testimony it reads (§4),
8
+ builds the Act, presents exactly the certificates it relies on (0.2.0 §6.5), submits it (§6), and
9
+ if a person must approve, asks the approver for consent over this exact Act (§5) and resubmits it
10
+ (§6.3). It holds no key: nothing it does can make an Act succeed that the relying party would refuse.
11
+
12
+ Standard library only (urllib). The same behaviour as @nomosprotocol/sdk's act().
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ from typing import Any, Callable, Dict, List, Optional
21
+ from urllib.parse import urlparse
22
+
23
+ from .accept import ACT_MEDIA_TYPE
24
+ from .statements import MAX_PRESENTED, build_act, presented_certificates
25
+
26
+ STATUS_OF = {"AUTHORIZED": "committed", "ESCALATED": "escalated", "INCOMPLETE": "incomplete", "DENIED": "denied", "REPLAYED": "replayed"}
27
+ WELL_KNOWN = {"relying-party": "/.well-known/nomos-relying-party", "issuer": "/.well-known/nomos-issuer", "witness": "/.well-known/nomos-witness"}
28
+
29
+
30
+ class NomosActError(Exception):
31
+ pass
32
+
33
+
34
+ def _origin(url: str) -> str:
35
+ u = urlparse(url); return f"{u.scheme}://{u.netloc}"
36
+
37
+
38
+ def _http(method: str, url: str, body: Any = None, content_type: str = "application/json", headers: Optional[dict] = None, timeout: float = 30):
39
+ data = None if body is None else json.dumps(body).encode()
40
+ req = urllib.request.Request(url, data=data, method=method, headers={"accept": "application/json", **({"content-type": content_type} if data else {}), **(headers or {})})
41
+ try:
42
+ with urllib.request.urlopen(req, timeout=timeout) as r:
43
+ return r.status, json.loads(r.read() or b"{}")
44
+ except urllib.error.HTTPError as e:
45
+ try: return e.code, json.loads(e.read() or b"{}")
46
+ except ValueError: return e.code, {}
47
+ except (urllib.error.URLError, OSError) as e:
48
+ return 0, {"error": str(getattr(e, "reason", e))}
49
+
50
+
51
+ def fetch_document(kind: str, url: str) -> dict:
52
+ status, doc = _http("GET", _origin(url) + WELL_KNOWN[kind])
53
+ if status != 200 or doc.get("nomos_document") != kind or doc.get("version") != "1":
54
+ raise NomosActError(f"{_origin(url)} serves no version-1 {kind} document at {WELL_KNOWN[kind]} ({status}).")
55
+ return doc
56
+
57
+
58
+ def act(*, to: str, action: dict, authority: Optional[str] = None, presenter_facts: Optional[dict] = None,
59
+ witness_headers: Optional[Dict[str, dict]] = None, approval_timeout_seconds: Optional[float] = None,
60
+ on_approval: Optional[Callable[[dict], None]] = None, poll_seconds: float = 1.0) -> dict:
61
+ # 1. The relying party (§3.1).
62
+ rp = fetch_document("relying-party", to)
63
+ cands = [a for a in rp["authorities"] if action["type"] in a["actions"] and (not authority or a["artifact_id"] == authority)]
64
+ if not cands: raise NomosActError(f"{_origin(to)} accepts no authority for action type {action['type']!r}.")
65
+ if len(cands) > 1 and not authority: raise NomosActError(f"{_origin(to)} accepts several authorities for {action['type']!r}; pass authority=.")
66
+ accepted = cands[0]
67
+ if not accepted.get("issuer"): raise NomosActError(f"{_origin(to)} does not say where {accepted['artifact_id']}'s issuer publishes it.")
68
+
69
+ # 2. The authority, from its issuer (§3.2). Its seal is verified by the relying party.
70
+ issuer = fetch_document("issuer", accepted["issuer"])
71
+ entry = next((a for a in issuer["authorities"] if a["artifact_id"] == accepted["artifact_id"]), None)
72
+ if not entry: raise NomosActError(f"The issuer at {accepted['issuer']} does not publish {accepted['artifact_id']}.")
73
+ status, artifact = _http("GET", entry["artifact_url"])
74
+ if status != 200: raise NomosActError(f"Could not fetch the authority from {entry['artifact_url']} ({status}).")
75
+ in_force = None
76
+ if accepted.get("currency_policy") == "record_or_statement" and not accepted.get("in_force_seal_hash") and entry.get("in_force_url"):
77
+ s, st = _http("GET", entry["in_force_url"]); in_force = st if s == 200 else None
78
+
79
+ # 3. Testimony for every witnessed input (§4), and the chains witnesses return with it.
80
+ inputs = (artifact.get("data_contract") or {}).get("inputs") or {}
81
+ witnessed = [n for n, i in inputs.items() if (i or {}).get("source") == "testimony"]
82
+ escalates = bool((artifact.get("governance") or {}).get("escalations"))
83
+ window = rp["max_window_seconds"] if escalates else min(300, rp["max_window_seconds"])
84
+ witnesses = []
85
+ for w in issuer.get("witnesses") or []:
86
+ try: witnesses.append(fetch_document("witness", w))
87
+ except NomosActError: pass # a witness that is down leaves its facts missing; the verdict says so
88
+ testimony: List[dict] = []
89
+ available: List[dict] = list(issuer.get("key_certs") or [])
90
+ unavailable: List[dict] = []
91
+ for claim in witnessed:
92
+ w = next((x for x in witnesses if claim in x["claims"]), None)
93
+ if not w: unavailable.append({"fact": claim, "why": f"no witness of {issuer['issuer_id']} publishes {claim}"}); continue
94
+ s, body = _http("POST", w["statement_endpoint"], {"claim": claim, "about": action.get("subject"), "valid_for_seconds": window},
95
+ headers=(witness_headers or {}).get(_origin(w["statement_endpoint"])))
96
+ t = body.get("testimony") if s == 200 else None
97
+ if not t: unavailable.append({"fact": claim, "why": f"{w['witness_id']} answered {s or 'nothing'}{': ' + body['error'] if body.get('error') else ''}"}); continue
98
+ if t.get("claim") != claim or t.get("about") != action.get("subject"):
99
+ unavailable.append({"fact": claim, "why": f"{w['witness_id']} answered for a different claim or subject"}); continue
100
+ testimony.append(t)
101
+ available += body.get("key_certs") or []
102
+
103
+ # 4. Build, present the closure, submit (§6).
104
+ the_act = build_act(relying_party=rp["relying_party_id"], action=action, artifact=artifact, key_certs=[], testimony=testimony,
105
+ presenter_facts=presenter_facts, in_force=in_force, window_seconds=window)
106
+ _present(the_act, available)
107
+ status, body = _submit(rp["act_endpoint"], the_act)
108
+
109
+ # 5. A person must approve (§5, §6.3).
110
+ approval_url = None
111
+ while status == 202 and body.get("decision") == "ESCALATED":
112
+ role = body.get("role")
113
+ endpoint = next((a["endpoint"] for a in issuer.get("approvals") or [] if a["role"] == role), None)
114
+ if not endpoint: return _done("escalated", body, the_act, summary=f"Needs approval from {role}, and {issuer['issuer_id']} publishes no approval endpoint for that role.")
115
+ expires = _epoch(the_act["expires_at"])
116
+ deadline = min(expires, time.time() + approval_timeout_seconds) if approval_timeout_seconds is not None else expires
117
+ answer, approval_url = _request_consent(endpoint, role, the_act, deadline, poll_seconds, body.get("act_digest"), on_approval)
118
+ if answer == "refused": return _done("denied", body, the_act, summary=f"The {role} refused this action.")
119
+ if not answer:
120
+ return _done("escalated", body, the_act, approval_url=approval_url, summary=(
121
+ f"Not approved by {role} before the Act expired at {the_act['expires_at']}; build a new Act to ask again." if time.time() >= expires
122
+ else f"Waiting for approval from {role}{' at ' + approval_url if approval_url else ''}. This Act stays valid until {the_act['expires_at']}."))
123
+ the_act["consents"].append(answer["consent"])
124
+ available += answer.get("key_certs") or []
125
+ _present(the_act, available) # the approver's chain now belongs in the presented set
126
+ before = int(body.get("consents_valid") or 0)
127
+ status, body = _submit(rp["act_endpoint"], the_act)
128
+ if status == 202 and int(body.get("consents_valid") or 0) <= before:
129
+ return _done("escalated", body, the_act, approval_url=approval_url, summary=f"Needs {body.get('consents_required')} distinct {role} approvals; {body.get('consents_valid')} given.")
130
+
131
+ kind = STATUS_OF.get(body.get("decision"), "refused")
132
+ if kind == "incomplete":
133
+ missing = []
134
+ for fact in body.get("open_facts") or []:
135
+ why = next((u for u in unavailable if u["fact"] == fact or fact.startswith(u["fact"] + ".")), None)
136
+ missing.append({"fact": fact, "source": (inputs.get(fact.split(".")[0]) or {}).get("source"), "why": why["why"] if why else "not supplied"})
137
+ return _done("incomplete", body, the_act, missing=missing, summary="Not committed: " + "; ".join(f"{m['fact']} ({m['why']})" for m in missing) + ".")
138
+ summary = {"committed": f"Committed by {rp['relying_party_id']}{', with approval' if body.get('by_consent') else ''}.",
139
+ "denied": f"Denied by rule {body.get('rule') or '(default)'}.", "replayed": "Already committed; this is the original receipt."
140
+ }.get(kind, f"Refused: {body.get('decision')}{' (' + body['reason_code'] + ')' if body.get('reason_code') else ''}.")
141
+ return _done(kind, body, the_act, receipt=body.get("receipt"), result=body.get("result"), summary=summary)
142
+
143
+
144
+ def _present(the_act: dict, available: List[dict]) -> None:
145
+ s = presented_certificates(available, the_act)
146
+ if len(s) > MAX_PRESENTED:
147
+ raise NomosActError(f"This Act relies on {len(s)} certificates; at most {MAX_PRESENTED} can be presented (NOMOS-SPEC-008 §6 step 1).")
148
+ the_act["authority"]["key_certs"] = s
149
+
150
+
151
+ def _submit(endpoint: str, the_act: dict):
152
+ status, body = _http("POST", endpoint, the_act, content_type=ACT_MEDIA_TYPE)
153
+ if status >= 500 or status == 0: raise NomosActError(f"The relying party could not answer ({status}): {body.get('error', '')}")
154
+ return status, body
155
+
156
+
157
+ def _epoch(s: str) -> float:
158
+ from .chain import ts
159
+ return ts(s).timestamp()
160
+
161
+
162
+ def _request_consent(endpoint, role, the_act, deadline, poll_seconds, act_digest, on_approval):
163
+ s, body = _http("POST", endpoint, {"role": role, "act": {**the_act, "consents": []}})
164
+ if s == 200 and body.get("status") == "approved": return {"consent": body["consent"], "key_certs": body.get("key_certs")}, None
165
+ if s != 202 or not body.get("poll_url"): return None, None
166
+ url = body.get("approval_url")
167
+ if on_approval: on_approval({"role": role, "url": url, "act_digest": act_digest})
168
+ while time.time() < deadline:
169
+ time.sleep(poll_seconds)
170
+ _, p = _http("GET", body["poll_url"])
171
+ if p.get("status") == "approved": return {"consent": p["consent"], "key_certs": p.get("key_certs")}, url
172
+ if p.get("status") == "refused": return "refused", url
173
+ if p.get("status") == "expired": return None, url
174
+ return None, url
175
+
176
+
177
+ def _done(status: str, verdict: dict, the_act: dict, **extra) -> dict:
178
+ return {"status": status, "verdict": verdict, "act": the_act, **{k: v for k, v in extra.items() if v is not None}}