nomosprotocol 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nomosprotocol/__init__.py +36 -0
- nomosprotocol/accept.py +312 -0
- nomosprotocol/act.py +462 -0
- nomosprotocol/carrier.py +178 -0
- nomosprotocol/chain.py +421 -0
- nomosprotocol/issuer.py +73 -0
- nomosprotocol/jcs.py +46 -0
- nomosprotocol/statements.py +191 -0
- nomosprotocol/suites.py +252 -0
- nomosprotocol/witness.py +72 -0
- nomosprotocol-0.1.0.dist-info/METADATA +121 -0
- nomosprotocol-0.1.0.dist-info/RECORD +14 -0
- nomosprotocol-0.1.0.dist-info/WHEEL +5 -0
- nomosprotocol-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Signing and building the objects of NOMOS-SPEC-001, -007, -008 and -009: seals, key certificates,
|
|
2
|
+
testimony, consents, in-force statements, revocations, Acts, and the certificates an Act presents.
|
|
3
|
+
|
|
4
|
+
Every payload is exactly the one the specification names, canonicalized with RFC 8785 (jcs.py)
|
|
5
|
+
and signed under a NOMOS-SPEC-010 suite (suites.py). The same functions the reference vector
|
|
6
|
+
generators use.
|
|
7
|
+
|
|
8
|
+
A `Signer` is anything with `kid`, `public_key_pem`, `algorithm` ("Ed25519" or "ES256") and
|
|
9
|
+
`sign(payload: bytes) -> str` (base64, the suite's encoding). `local_signer()` wraps a private key
|
|
10
|
+
held in this process; in production, pass one backed by your KMS or HSM.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import os
|
|
16
|
+
import uuid
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from datetime import datetime, timedelta, timezone
|
|
19
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Protocol
|
|
20
|
+
|
|
21
|
+
from cryptography.hazmat.primitives import serialization
|
|
22
|
+
from cryptography.hazmat.primitives.asymmetric import ec, ed25519
|
|
23
|
+
|
|
24
|
+
from . import suites
|
|
25
|
+
from .act import binding_digest, consent_payload, in_force_payload, testimony_payload
|
|
26
|
+
from .chain import cert_payload, fingerprint, revocation_list_payload, revocation_payload
|
|
27
|
+
from .jcs import jcs, sha256_hex
|
|
28
|
+
|
|
29
|
+
MAX_PRESENTED = 20
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Signer(Protocol):
|
|
33
|
+
kid: str
|
|
34
|
+
public_key_pem: str
|
|
35
|
+
algorithm: str
|
|
36
|
+
def sign(self, payload: bytes) -> str: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class LocalSigner:
|
|
41
|
+
"""A Signer over a private key in this process: for development, tests and offline roots."""
|
|
42
|
+
kid: str
|
|
43
|
+
public_key_pem: str
|
|
44
|
+
algorithm: str
|
|
45
|
+
_key: Any
|
|
46
|
+
|
|
47
|
+
def sign(self, payload: bytes) -> str:
|
|
48
|
+
# Ed25519 signs the payload; ES256 signs SHA-256 of it, P1363 r‖s, low-S, deterministic nonces.
|
|
49
|
+
return suites.sign_ed25519(self._key, payload) if self.algorithm == "Ed25519" else suites.sign_es256(self._key, payload)
|
|
50
|
+
|
|
51
|
+
def private_key_pem(self) -> str:
|
|
52
|
+
return self._key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()).decode()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _wrap(key) -> LocalSigner:
|
|
56
|
+
if isinstance(key, ed25519.Ed25519PrivateKey): alg = "Ed25519"
|
|
57
|
+
elif isinstance(key, ec.EllipticCurvePrivateKey) and isinstance(key.curve, ec.SECP256R1): alg = "ES256"
|
|
58
|
+
else: raise ValueError("only Ed25519 and P-256 keys are NOMOS signature suites (NOMOS-SPEC-010)")
|
|
59
|
+
pem = suites.public_pem(key)
|
|
60
|
+
return LocalSigner(kid=suites.compute_kid(pem), public_key_pem=pem, algorithm=alg, _key=key)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def local_signer(private_key_pem: str) -> LocalSigner:
|
|
64
|
+
"""A signer from a PKCS#8 (or SEC1, for P-256) PEM private key."""
|
|
65
|
+
return _wrap(serialization.load_pem_private_key(private_key_pem.encode(), password=None))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def generate_signer(algorithm: str = "Ed25519") -> LocalSigner:
|
|
69
|
+
"""A fresh in-memory key. For development and tests."""
|
|
70
|
+
if algorithm == "Ed25519": return _wrap(ed25519.Ed25519PrivateKey.generate())
|
|
71
|
+
if algorithm == "ES256": return _wrap(ec.generate_private_key(ec.SECP256R1()))
|
|
72
|
+
raise ValueError("algorithm must be Ed25519 or ES256")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def seeded_signer(seed: str) -> LocalSigner:
|
|
76
|
+
"""A deterministic Ed25519 key from a seed: the same test key everywhere. The seed is the key;
|
|
77
|
+
never use one for anything real. Byte-identical to @nomosprotocol/sdk's seededSigner()."""
|
|
78
|
+
return _wrap(suites.ed25519_key_from_seed(seed.encode()))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def iso(t: datetime) -> str:
|
|
82
|
+
"""ISO 8601 UTC with milliseconds, as JavaScript's toISOString() writes it."""
|
|
83
|
+
t = t.astimezone(timezone.utc)
|
|
84
|
+
return t.strftime("%Y-%m-%dT%H:%M:%S.") + f"{t.microsecond // 1000:03d}Z"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def now_utc() -> datetime:
|
|
88
|
+
return datetime.now(timezone.utc)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ── NOMOS-SPEC-007 ─────────────────────────────────────────────────────────────────────────
|
|
92
|
+
def certify(parent: Signer, child_kid: str, child_public_key_pem: str, *, expires_at: datetime,
|
|
93
|
+
scope: Optional[str] = None, issued_at: Optional[datetime] = None) -> dict:
|
|
94
|
+
"""§3: `parent` certifies the child key within `scope` until `expires_at`."""
|
|
95
|
+
c: Dict[str, Any] = {"parent_kid": parent.kid, "child_kid": child_kid, "child_public_key_pem": child_public_key_pem}
|
|
96
|
+
if scope: c["scope"] = scope
|
|
97
|
+
c["issued_at"] = iso(issued_at or now_utc()); c["expires_at"] = iso(expires_at)
|
|
98
|
+
c["algorithm"] = parent.algorithm
|
|
99
|
+
c["signature"] = parent.sign(jcs(cert_payload(c)))
|
|
100
|
+
return c
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def sign_revocation(parent: Signer, *, kid: Optional[str] = None, certificate: Optional[dict] = None,
|
|
104
|
+
reason: str, issued_at: Optional[datetime] = None) -> dict:
|
|
105
|
+
"""rev. 1.10 §5.1: revoke a key the parent certified, or one certificate it issued."""
|
|
106
|
+
if (kid is None) == (certificate is None): raise ValueError("give exactly one of kid or certificate")
|
|
107
|
+
if certificate is not None and certificate.get("parent_kid") != parent.kid:
|
|
108
|
+
raise ValueError("only the parent that issued a certificate can revoke it")
|
|
109
|
+
st: Dict[str, Any] = {"revoked_kid": kid} if kid else {"revoked_fingerprint": fingerprint(certificate)}
|
|
110
|
+
st.update({"reason": reason, "issued_at": iso(issued_at or now_utc())})
|
|
111
|
+
return {**st, "kid": parent.kid, "algorithm": parent.algorithm, "signature": parent.sign(jcs(revocation_payload(st)))}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def sign_revocation_list(signer: Signer, statements: List[dict], key_certs: Iterable[dict] = (), generated_at: Optional[datetime] = None) -> dict:
|
|
115
|
+
"""rev. 1.10 §5.3: a signed, dated list carrying the certificates that make it checkable."""
|
|
116
|
+
lst: Dict[str, Any] = {"generated_at": iso(generated_at or now_utc()), "kid": signer.kid, "algorithm": signer.algorithm, "statements": statements}
|
|
117
|
+
kc = list(key_certs)
|
|
118
|
+
if kc: lst["key_certs"] = kc
|
|
119
|
+
lst["signature"] = signer.sign(jcs(revocation_list_payload(lst)))
|
|
120
|
+
return lst
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ── NOMOS-SPEC-001 §8 ──────────────────────────────────────────────────────────────────────
|
|
124
|
+
def seal(body: dict, issuer: Signer, signed_by: Any) -> dict:
|
|
125
|
+
content = {k: v for k, v in body.items() if k not in ("seal", "attestations")}
|
|
126
|
+
h = sha256_hex(jcs(content))
|
|
127
|
+
signature = issuer.sign(jcs({"hash": h, "signed_by": signed_by}))
|
|
128
|
+
return {**content, "seal": {"status": "sealed", "hash": h, "canonicalization": "JCS", "signature_algorithm": issuer.algorithm,
|
|
129
|
+
"kid": issuer.kid, "signed_by": signed_by, "signature": signature}}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ── NOMOS-SPEC-008 ─────────────────────────────────────────────────────────────────────────
|
|
133
|
+
def sign_testimony(witness: Signer, *, claim: str, value: Any, about: Optional[str], valid_until: datetime, as_of: Optional[datetime] = None) -> dict:
|
|
134
|
+
st = {"claim": claim, "value": value, "about": about, "as_of": iso(as_of or now_utc()), "valid_until": iso(valid_until), "kid": witness.kid, "algorithm": witness.algorithm}
|
|
135
|
+
st["signature"] = witness.sign(jcs(testimony_payload(st)))
|
|
136
|
+
return st
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def sign_consent(approver: Signer, act: dict, role: str, decision: str = "approve") -> dict:
|
|
140
|
+
c = {"binding_digest": binding_digest(act), "role": role, "decision": decision, "signed_at": iso(now_utc()), "kid": approver.kid, "algorithm": approver.algorithm}
|
|
141
|
+
c["signature"] = approver.sign(jcs(consent_payload(c)))
|
|
142
|
+
return c
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def sign_in_force(issuer: Signer, artifact: dict, *, valid_until: datetime, as_of: Optional[datetime] = None) -> dict:
|
|
146
|
+
st = {"artifact_id": artifact["meta"]["artifact_id"], "version": artifact["meta"]["version"], "seal_hash": artifact["seal"]["hash"],
|
|
147
|
+
"as_of": iso(as_of or now_utc()), "valid_until": iso(valid_until), "kid": artifact["seal"]["kid"], "algorithm": issuer.algorithm}
|
|
148
|
+
st["signature"] = issuer.sign(jcs(in_force_payload(st)))
|
|
149
|
+
return st
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def build_act(*, relying_party: str, action: dict, artifact: dict, key_certs: List[dict], testimony: Optional[List[dict]] = None,
|
|
153
|
+
presenter_facts: Optional[dict] = None, in_force: Optional[dict] = None, window_seconds: int = 300,
|
|
154
|
+
now: Optional[datetime] = None) -> dict:
|
|
155
|
+
"""§2: assemble an Act. It needs no key: what makes it valid is what it carries. Issued a second
|
|
156
|
+
in the past so a relying party whose clock is a moment behind still accepts it."""
|
|
157
|
+
t = (now or now_utc()) - timedelta(seconds=1)
|
|
158
|
+
act: Dict[str, Any] = {
|
|
159
|
+
"act_version": "1", "act_id": f"act-{uuid.uuid4()}", "nonce": base64.b64encode(os.urandom(16)).decode(),
|
|
160
|
+
"issued_at": iso(t), "expires_at": iso(t + timedelta(seconds=window_seconds)),
|
|
161
|
+
"relying_party": relying_party, "action": action,
|
|
162
|
+
"authority": {"artifact": artifact, "key_certs": key_certs, **({"in_force": in_force} if in_force else {})},
|
|
163
|
+
"testimony": testimony or [], "consents": [],
|
|
164
|
+
}
|
|
165
|
+
if presenter_facts: act["presenter_facts"] = presenter_facts
|
|
166
|
+
return act
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ── NOMOS-SPEC-009 0.2.0 §6.5 ──────────────────────────────────────────────────────────────
|
|
170
|
+
def relied_kids(act: dict) -> List[str]:
|
|
171
|
+
kids = [((act.get("authority") or {}).get("artifact") or {}).get("seal", {}).get("kid")]
|
|
172
|
+
kids += [t.get("kid") for t in act.get("testimony") or []] + [c.get("kid") for c in act.get("consents") or []]
|
|
173
|
+
out: List[str] = []
|
|
174
|
+
for k in kids:
|
|
175
|
+
if isinstance(k, str) and k and k not in out: out.append(k)
|
|
176
|
+
return out
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def presented_certificates(available: Iterable[dict], act: dict) -> List[dict]:
|
|
180
|
+
"""The closure of `available` over the kids `act` relies on, each certificate once. Deterministic,
|
|
181
|
+
so two carriers with the same certificates present the same set (carrier indifference)."""
|
|
182
|
+
unique: Dict[str, dict] = {}
|
|
183
|
+
for c in available: unique.setdefault(fingerprint(c), c)
|
|
184
|
+
kids, chosen = set(relied_kids(act)), {}
|
|
185
|
+
grew = True
|
|
186
|
+
while grew:
|
|
187
|
+
grew = False
|
|
188
|
+
for fp, c in unique.items():
|
|
189
|
+
if fp not in chosen and c.get("child_kid") in kids:
|
|
190
|
+
chosen[fp] = c; kids.add(c.get("parent_kid")); grew = True
|
|
191
|
+
return list(chosen.values())
|
nomosprotocol/suites.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""NOMOS-SPEC-010 Signature Suites: reference verifier, and the signers the vector generator uses.
|
|
2
|
+
|
|
3
|
+
verify(suite, public_key_pem, payload, proof) -> (ok, reason)
|
|
4
|
+
|
|
5
|
+
suite "Ed25519" | "ES256" | "WebAuthn-ES256"
|
|
6
|
+
public_key_pem the signing key, as PEM SubjectPublicKeyInfo
|
|
7
|
+
payload the exact JCS bytes the calling specification says are signed
|
|
8
|
+
proof {"signature": ...} for Ed25519 and ES256;
|
|
9
|
+
{"authenticator_data", "client_data_json", "signature"} for WebAuthn-ES256
|
|
10
|
+
|
|
11
|
+
reason is one of the §7 reasons, or None when ok.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import base64
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
from typing import Any, Dict, Optional, Tuple
|
|
20
|
+
|
|
21
|
+
from cryptography.exceptions import InvalidSignature
|
|
22
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
23
|
+
from cryptography.hazmat.primitives.asymmetric import ec, ed25519
|
|
24
|
+
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature, encode_dss_signature
|
|
25
|
+
|
|
26
|
+
SUITES = ("Ed25519", "ES256", "WebAuthn-ES256")
|
|
27
|
+
P256_N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
|
|
28
|
+
|
|
29
|
+
_B64 = re.compile(r"^[A-Za-z0-9+/]*={0,2}$")
|
|
30
|
+
_B64URL = re.compile(r"^[A-Za-z0-9_-]*$")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ── canonical base64 ─────────────────────────────────────────────────────────────────────────
|
|
34
|
+
def b64decode_canonical(s: Any) -> Optional[bytes]:
|
|
35
|
+
"""RFC 4648 §4 base64, padded, accepted only in its canonical encoding."""
|
|
36
|
+
if not isinstance(s, str) or len(s) % 4 or not _B64.match(s):
|
|
37
|
+
return None
|
|
38
|
+
try:
|
|
39
|
+
raw = base64.b64decode(s, validate=True)
|
|
40
|
+
except ValueError:
|
|
41
|
+
return None
|
|
42
|
+
return raw if base64.b64encode(raw).decode() == s else None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def b64url_decode_canonical(s: Any) -> Optional[bytes]:
|
|
46
|
+
"""RFC 4648 §5 base64url, unpadded, accepted only in its canonical encoding."""
|
|
47
|
+
if not isinstance(s, str) or not _B64URL.match(s) or len(s) % 4 == 1:
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
raw = base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
51
|
+
except ValueError:
|
|
52
|
+
return None
|
|
53
|
+
return raw if b64url_encode(raw) == s else None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def b64url_encode(raw: bytes) -> str:
|
|
57
|
+
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ── keys (§3) ────────────────────────────────────────────────────────────────────────────────
|
|
61
|
+
def _pem_der(pem: Any) -> Optional[bytes]:
|
|
62
|
+
if not isinstance(pem, str):
|
|
63
|
+
return None
|
|
64
|
+
m = re.fullmatch(r"\s*-----BEGIN PUBLIC KEY-----\s*([A-Za-z0-9+/=\s]+?)\s*-----END PUBLIC KEY-----\s*", pem)
|
|
65
|
+
if not m:
|
|
66
|
+
return None
|
|
67
|
+
return b64decode_canonical("".join(m.group(1).split()))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
ED25519_SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100")
|
|
71
|
+
P256_SPKI_PREFIX = bytes.fromhex("3059301306072a8648ce3d020106082a8648ce3d03010703420004")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
_ED_P = 2**255 - 19
|
|
75
|
+
_ED_D = (-121665 * pow(121666, _ED_P - 2, _ED_P)) % _ED_P
|
|
76
|
+
_ED_SMALL_ORDER = {bytes.fromhex(h) for h in (
|
|
77
|
+
"0100000000000000000000000000000000000000000000000000000000000000",
|
|
78
|
+
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
|
|
79
|
+
"0000000000000000000000000000000000000000000000000000000000000000",
|
|
80
|
+
"0000000000000000000000000000000000000000000000000000000000000080",
|
|
81
|
+
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
|
|
82
|
+
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
|
|
83
|
+
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
|
|
84
|
+
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa")}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def ed25519_point_valid(a: bytes) -> bool:
|
|
88
|
+
"""§3.1: canonical, on the curve, not of small order (RFC 8032 §5.1.3 decoding, strictly)."""
|
|
89
|
+
if len(a) != 32 or a in _ED_SMALL_ORDER:
|
|
90
|
+
return False
|
|
91
|
+
y = int.from_bytes(a, "little") & ((1 << 255) - 1)
|
|
92
|
+
sign = a[31] >> 7
|
|
93
|
+
if y >= _ED_P:
|
|
94
|
+
return False
|
|
95
|
+
x2 = (y * y - 1) * pow(_ED_D * y * y + 1, _ED_P - 2, _ED_P) % _ED_P
|
|
96
|
+
if x2 == 0:
|
|
97
|
+
return sign == 0
|
|
98
|
+
x = pow(x2, (_ED_P + 3) // 8, _ED_P)
|
|
99
|
+
if (x * x - x2) % _ED_P != 0:
|
|
100
|
+
x = x * pow(2, (_ED_P - 1) // 4, _ED_P) % _ED_P
|
|
101
|
+
return (x * x - x2) % _ED_P == 0
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def load_key(pem: Any) -> Tuple[Optional[str], Any, Optional[str]]:
|
|
105
|
+
"""Returns (key_type, key, reason). key_type is 'Ed25519' or 'P-256'.
|
|
106
|
+
|
|
107
|
+
Canonical form is checked against the exact bytes of §3.1, never by re-encoding through a
|
|
108
|
+
library, whose output format is not part of the specification.
|
|
109
|
+
"""
|
|
110
|
+
der = _pem_der(pem)
|
|
111
|
+
if der is None:
|
|
112
|
+
return None, None, "invalid_key"
|
|
113
|
+
if len(der) == 44 and der.startswith(ED25519_SPKI_PREFIX):
|
|
114
|
+
if not ed25519_point_valid(der[12:]):
|
|
115
|
+
return None, None, "invalid_key"
|
|
116
|
+
ktype = "Ed25519"
|
|
117
|
+
elif len(der) == 91 and der.startswith(P256_SPKI_PREFIX):
|
|
118
|
+
ktype = "P-256"
|
|
119
|
+
else:
|
|
120
|
+
return None, None, "invalid_key"
|
|
121
|
+
try:
|
|
122
|
+
key = serialization.load_der_public_key(der) # also rejects a P-256 point not on the curve
|
|
123
|
+
except (ValueError, TypeError):
|
|
124
|
+
return None, None, "invalid_key"
|
|
125
|
+
return ktype, key, None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def compute_kid(pem: str) -> str:
|
|
129
|
+
der = _pem_der(pem)
|
|
130
|
+
return base64.urlsafe_b64encode(hashlib.sha256(der).digest()).decode().rstrip("=")[:16]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
_SUITES_FOR_TYPE = {"Ed25519": ("Ed25519",), "P-256": ("ES256", "WebAuthn-ES256")}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# ── verification ─────────────────────────────────────────────────────────────────────────────
|
|
137
|
+
def verify(suite: Any, public_key_pem: Any, payload: bytes, proof: Dict[str, Any]) -> Tuple[bool, Optional[str]]:
|
|
138
|
+
if suite not in SUITES:
|
|
139
|
+
return False, "unknown_suite"
|
|
140
|
+
ktype, key, reason = load_key(public_key_pem)
|
|
141
|
+
if reason:
|
|
142
|
+
return False, reason
|
|
143
|
+
if suite not in _SUITES_FOR_TYPE[ktype]:
|
|
144
|
+
return False, "suite_key_mismatch"
|
|
145
|
+
if not isinstance(proof, dict):
|
|
146
|
+
return False, "bad_encoding"
|
|
147
|
+
if suite == "Ed25519":
|
|
148
|
+
return _verify_ed25519(key, payload, proof.get("signature"))
|
|
149
|
+
if suite == "ES256":
|
|
150
|
+
return _verify_es256(key, payload, proof.get("signature"))
|
|
151
|
+
return _verify_webauthn(key, payload, proof)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _verify_ed25519(key, payload: bytes, sig_b64: Any):
|
|
155
|
+
sig = b64decode_canonical(sig_b64)
|
|
156
|
+
if sig is None or len(sig) != 64:
|
|
157
|
+
return False, "bad_encoding"
|
|
158
|
+
try:
|
|
159
|
+
key.verify(sig, payload)
|
|
160
|
+
except InvalidSignature:
|
|
161
|
+
return False, "bad_signature"
|
|
162
|
+
return True, None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _verify_es256(key, payload: bytes, sig_b64: Any):
|
|
166
|
+
sig = b64decode_canonical(sig_b64)
|
|
167
|
+
if sig is None or len(sig) != 64:
|
|
168
|
+
return False, "bad_encoding"
|
|
169
|
+
r, s = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:], "big")
|
|
170
|
+
if not (1 <= r < P256_N and 1 <= s < P256_N):
|
|
171
|
+
return False, "bad_encoding"
|
|
172
|
+
if s > P256_N // 2:
|
|
173
|
+
return False, "high_s"
|
|
174
|
+
try:
|
|
175
|
+
key.verify(encode_dss_signature(r, s), payload, ec.ECDSA(hashes.SHA256()))
|
|
176
|
+
except InvalidSignature:
|
|
177
|
+
return False, "bad_signature"
|
|
178
|
+
return True, None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _verify_webauthn(key, payload: bytes, proof: Dict[str, Any]):
|
|
182
|
+
auth = b64url_decode_canonical(proof.get("authenticator_data"))
|
|
183
|
+
cdj = b64url_decode_canonical(proof.get("client_data_json"))
|
|
184
|
+
sig = b64url_decode_canonical(proof.get("signature"))
|
|
185
|
+
if auth is None or cdj is None or sig is None:
|
|
186
|
+
return False, "bad_encoding"
|
|
187
|
+
try:
|
|
188
|
+
client = json.loads(cdj.decode("utf-8"))
|
|
189
|
+
except (UnicodeDecodeError, ValueError):
|
|
190
|
+
return False, "bad_client_data"
|
|
191
|
+
if not isinstance(client, dict) or client.get("type") != "webauthn.get":
|
|
192
|
+
return False, "bad_client_data"
|
|
193
|
+
if client.get("challenge") != b64url_encode(hashlib.sha256(payload).digest()):
|
|
194
|
+
return False, "challenge_mismatch"
|
|
195
|
+
if len(auth) < 37:
|
|
196
|
+
return False, "bad_encoding"
|
|
197
|
+
flags = auth[32]
|
|
198
|
+
if not (flags & 0x01) or not (flags & 0x04):
|
|
199
|
+
return False, "user_not_verified"
|
|
200
|
+
try:
|
|
201
|
+
decode_dss_signature(sig)
|
|
202
|
+
except ValueError:
|
|
203
|
+
return False, "bad_encoding"
|
|
204
|
+
try:
|
|
205
|
+
key.verify(sig, auth + hashlib.sha256(cdj).digest(), ec.ECDSA(hashes.SHA256()))
|
|
206
|
+
except InvalidSignature:
|
|
207
|
+
return False, "bad_signature"
|
|
208
|
+
return True, None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# ── signers (producers; used by the vector generator) ────────────────────────────────────────
|
|
212
|
+
def ed25519_key_from_seed(seed: bytes) -> ed25519.Ed25519PrivateKey:
|
|
213
|
+
return ed25519.Ed25519PrivateKey.from_private_bytes(hashlib.sha256(seed).digest())
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def p256_key_from_seed(seed: bytes) -> ec.EllipticCurvePrivateKey:
|
|
217
|
+
scalar = int.from_bytes(hashlib.sha256(seed).digest(), "big") % (P256_N - 1) + 1
|
|
218
|
+
return ec.derive_private_key(scalar, ec.SECP256R1())
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def public_pem(private_key) -> str:
|
|
222
|
+
return private_key.public_key().public_bytes(
|
|
223
|
+
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def sign_ed25519(private_key, payload: bytes) -> str:
|
|
227
|
+
return base64.b64encode(private_key.sign(payload)).decode()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def sign_es256(private_key, payload: bytes, *, low_s: bool = True) -> str:
|
|
231
|
+
der = private_key.sign(payload, ec.ECDSA(hashes.SHA256(), deterministic_signing=True))
|
|
232
|
+
r, s = decode_dss_signature(der)
|
|
233
|
+
if low_s and s > P256_N // 2:
|
|
234
|
+
s = P256_N - s
|
|
235
|
+
if not low_s and s <= P256_N // 2:
|
|
236
|
+
s = P256_N - s # deliberately high-S, for the vector that must be refused
|
|
237
|
+
return base64.b64encode(r.to_bytes(32, "big") + s.to_bytes(32, "big")).decode()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def webauthn_assert(private_key, payload: bytes, *, rp_id: str = "approve.example",
|
|
241
|
+
origin: str = "https://approve.example", flags: int = 0x05,
|
|
242
|
+
type_: str = "webauthn.get", challenge: Optional[str] = None,
|
|
243
|
+
sign_count: int = 0) -> Dict[str, str]:
|
|
244
|
+
"""A WebAuthn assertion as an authenticator would produce it (§5)."""
|
|
245
|
+
client = {"type": type_,
|
|
246
|
+
"challenge": challenge if challenge is not None else b64url_encode(hashlib.sha256(payload).digest()),
|
|
247
|
+
"origin": origin, "crossOrigin": False}
|
|
248
|
+
cdj = json.dumps(client, separators=(",", ":")).encode()
|
|
249
|
+
auth = hashlib.sha256(rp_id.encode()).digest() + bytes([flags]) + sign_count.to_bytes(4, "big")
|
|
250
|
+
sig = private_key.sign(auth + hashlib.sha256(cdj).digest(), ec.ECDSA(hashes.SHA256(), deterministic_signing=True))
|
|
251
|
+
return {"authenticator_data": b64url_encode(auth), "client_data_json": b64url_encode(cdj),
|
|
252
|
+
"signature": b64url_encode(sig)}
|
nomosprotocol/witness.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""witness(): turn an existing lookup into signed statements (NOMOS-SPEC-009 §3.3, §4).
|
|
2
|
+
|
|
3
|
+
finance = witness(origin="https://finance.acme.example", witness_id="acme-finance", signer=finance_key,
|
|
4
|
+
claims={"budget_remaining": lambda about: budgets.get(about)}, # None = unknown subject
|
|
5
|
+
key_certs=finance_chain) # returned with every statement (0.2.0 §4)
|
|
6
|
+
app = finance.wsgi # or finance.asgi
|
|
7
|
+
|
|
8
|
+
A witness is never in a relying party's verification path: it only produces statements, which the
|
|
9
|
+
relying party checks against the root it pins. `authorize` is your access control.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
from datetime import timedelta
|
|
15
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
from .statements import Signer, iso, now_utc, sign_testimony
|
|
18
|
+
|
|
19
|
+
WELL_KNOWN = "/.well-known/nomos-witness"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Witness:
|
|
23
|
+
def __init__(self, *, origin: str, witness_id: str, signer: Signer, claims: Dict[str, Callable[[Optional[str]], Any]],
|
|
24
|
+
max_validity_seconds: int = 900, authorize: Optional[Callable[[dict], bool]] = None,
|
|
25
|
+
access: Optional[str] = None, key_certs: Optional[List[dict]] = None):
|
|
26
|
+
self.base, self.witness_id, self.signer, self.claims = origin.rstrip("/"), witness_id, signer, claims
|
|
27
|
+
self.max_validity_seconds, self.authorize, self.access, self.key_certs = max_validity_seconds, authorize, access, key_certs or []
|
|
28
|
+
|
|
29
|
+
def document(self) -> dict:
|
|
30
|
+
return {"nomos_document": "witness", "version": "1", "witness_id": self.witness_id, "kid": self.signer.kid, "claims": list(self.claims),
|
|
31
|
+
"statement_endpoint": f"{self.base}/nomos/statements", **({"access": self.access} if self.access else {}),
|
|
32
|
+
"valid_until": iso(now_utc() + timedelta(days=1))}
|
|
33
|
+
|
|
34
|
+
def handle(self, method: str, path: str, body: bytes):
|
|
35
|
+
if method == "GET" and path == WELL_KNOWN: return 200, self.document()
|
|
36
|
+
if method != "POST" or path != "/nomos/statements": return 404, {"error": "Not found"}
|
|
37
|
+
try: req = json.loads(body or b"{}")
|
|
38
|
+
except ValueError: return 400, {"error": "Not JSON."}
|
|
39
|
+
claim, about = str(req.get("claim") or ""), req.get("about")
|
|
40
|
+
read = self.claims.get(claim)
|
|
41
|
+
if read is None: return 404, {"error": f"{self.witness_id} does not state {claim}."}
|
|
42
|
+
if self.authorize and not self.authorize({"claim": claim, "about": about}): return 403, {"error": "Not entitled to this statement."}
|
|
43
|
+
value = read(about)
|
|
44
|
+
if value is None: return 404, {"error": f"{self.witness_id} knows nothing about {about}."}
|
|
45
|
+
try: wanted = float(req.get("valid_for_seconds") or self.max_validity_seconds)
|
|
46
|
+
except (TypeError, ValueError): wanted = self.max_validity_seconds
|
|
47
|
+
seconds = max(1, min(self.max_validity_seconds, wanted))
|
|
48
|
+
t = sign_testimony(self.signer, claim=claim, value=value, about=about, valid_until=now_utc() + timedelta(seconds=seconds))
|
|
49
|
+
return 200, {"testimony": t, **({"key_certs": self.key_certs} if self.key_certs else {})}
|
|
50
|
+
|
|
51
|
+
def wsgi(self, environ, start_response):
|
|
52
|
+
try: length = int(environ.get("CONTENT_LENGTH") or 0)
|
|
53
|
+
except ValueError: length = 0
|
|
54
|
+
status, body = self.handle(environ.get("REQUEST_METHOD", "GET"), environ.get("PATH_INFO", ""), environ["wsgi.input"].read(length) if length else b"")
|
|
55
|
+
data = json.dumps(body).encode()
|
|
56
|
+
start_response(f"{status} {'OK' if status == 200 else 'Error'}", [("content-type", "application/json"), ("content-length", str(len(data)))])
|
|
57
|
+
return [data]
|
|
58
|
+
|
|
59
|
+
async def asgi(self, scope, receive, send):
|
|
60
|
+
if scope["type"] != "http": return
|
|
61
|
+
chunks = []
|
|
62
|
+
while True:
|
|
63
|
+
m = await receive(); chunks.append(m.get("body", b""))
|
|
64
|
+
if not m.get("more_body"): break
|
|
65
|
+
status, body = self.handle(scope["method"], scope["path"], b"".join(chunks))
|
|
66
|
+
data = json.dumps(body).encode()
|
|
67
|
+
await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(data)).encode())]})
|
|
68
|
+
await send({"type": "http.response.body", "body": data})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def witness(**options) -> Witness:
|
|
72
|
+
return Witness(**options)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
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.
|
|
5
|
+
Author-email: NOMOS Protocol <hello@nomosprotocol.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.computableauthority.com
|
|
8
|
+
Project-URL: Specification, https://github.com/nomos-spec/spec
|
|
9
|
+
Keywords: nomos,computable-authority,agents,authorization,verifier,ed25519,es256,webauthn
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Security :: Cryptography
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
Requires-Dist: cryptography>=43
|
|
17
|
+
Provides-Extra: postgres
|
|
18
|
+
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
|
|
19
|
+
Requires-Dist: psycopg-pool>=3.2; extra == "postgres"
|
|
20
|
+
|
|
21
|
+
# nomosprotocol
|
|
22
|
+
|
|
23
|
+
NOMOS for Python. It includes the reference verifiers of the NOMOS specifications and the developer
|
|
24
|
+
layer built on them:
|
|
25
|
+
- `accept()`, for the system that makes a change;
|
|
26
|
+
- `act()`, for the agent that carries one;
|
|
27
|
+
- `witness()` and `issuer()`, for the systems that sign the facts and publish the rules.
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
pip install nomosprotocol # cryptography is the only dependency
|
|
31
|
+
pip install "nomosprotocol[postgres]" # adds psycopg, for postgres_store()
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Python 3.9+. The verifiers in this package are the same code the specification's published test
|
|
35
|
+
vectors are generated and checked with, so there is no second Python implementation to drift from
|
|
36
|
+
the reference.
|
|
37
|
+
|
|
38
|
+
## Be the system that makes the change
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import nomosprotocol as nomos
|
|
42
|
+
|
|
43
|
+
rp = nomos.accept(
|
|
44
|
+
relying_party_id="orders.acme.example",
|
|
45
|
+
root=ACME_ROOT_PEM, # the root you pin; there is no default
|
|
46
|
+
act_endpoint="https://orders.acme.example/nomos/acts",
|
|
47
|
+
authorities=[{"artifact_id": "acme-purchasing", "issuer": "https://policy.acme.example",
|
|
48
|
+
"actions": ["purchase"], "currency_policy": "record", "in_force_seal_hash": POLICY_SEAL_HASH}],
|
|
49
|
+
local_facts=lambda act, tx=None: {"vendor_blocked": is_blocked(act["action"]["params"]["vendor"])},
|
|
50
|
+
commit=lambda action, tx, act_id: create_order(tx, action), # your code, on the same transaction
|
|
51
|
+
store=nomos.postgres_store(pool.connection), # a psycopg_pool ConnectionPool
|
|
52
|
+
)
|
|
53
|
+
app = rp.wsgi # Flask, Django, gunicorn: any WSGI server
|
|
54
|
+
app = rp.asgi # FastAPI/Starlette mount, uvicorn: any ASGI server
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Every Act is verified locally (NOMOS-SPEC-008). If it is authorized, `accept()` does four things
|
|
58
|
+
in one transaction: records the nonce, re-reads your facts, hands `commit` exactly the verified
|
|
59
|
+
action, and stores the receipt with the Act.
|
|
60
|
+
|
|
61
|
+
| Verdict | Status |
|
|
62
|
+
|---|---|
|
|
63
|
+
| AUTHORIZED, committed | 201 |
|
|
64
|
+
| ESCALATED | 202 |
|
|
65
|
+
| INCOMPLETE | 422 |
|
|
66
|
+
| DENIED | 403 |
|
|
67
|
+
| REPLAYED | 409, with the original receipt |
|
|
68
|
+
| Any other refusal | 400 |
|
|
69
|
+
| Revocations unavailable | 503 |
|
|
70
|
+
|
|
71
|
+
If any number of copies of one Act arrive at once, exactly one commits and the rest get its
|
|
72
|
+
receipt. If revocation status can't be established, nothing commits.
|
|
73
|
+
|
|
74
|
+
## Be the agent
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
r = nomos.act(to="http://localhost:4747",
|
|
78
|
+
action={"type": "purchase", "subject": "DEPT-17", "params": {"amount": 500, "vendor": "paperco"}})
|
|
79
|
+
print(r["status"]) # committed | escalated | incomplete | denied | refused | replayed
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`act()` handles the whole round trip:
|
|
83
|
+
- discovers the system;
|
|
84
|
+
- fetches the rules it acts under;
|
|
85
|
+
- collects signed facts from the witnesses;
|
|
86
|
+
- presents exactly the certificates the Act relies on;
|
|
87
|
+
- submits;
|
|
88
|
+
- if a person must approve, waits for the approval and resubmits.
|
|
89
|
+
|
|
90
|
+
It uses only the standard library. To try it, run `npx @nomosprotocol/cli dev`.
|
|
91
|
+
|
|
92
|
+
## The other roles
|
|
93
|
+
|
|
94
|
+
- `witness(origin=…, witness_id=…, signer=…, claims={"budget_remaining": lambda about: …}, key_certs=…)` signs one fact about one subject on request.
|
|
95
|
+
- `issuer(origin=…, issuer_id=…, signer=…, authorities=[policy], key_certs=…, revocations=…)` publishes the sealed rules, the version in force, the certificate pool and the revocation list.
|
|
96
|
+
|
|
97
|
+
Keys are `Signer`s: anything with `kid`, `public_key_pem`, `algorithm` and `sign(payload) -> str`.
|
|
98
|
+
`local_signer(pem)` and `generate_signer()` are for development; for production, wrap your KMS.
|
|
99
|
+
|
|
100
|
+
## Verify directly
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from nomosprotocol import verify_act, chain
|
|
104
|
+
v = verify_act(act, relying_party_id="…", root_pem=ROOT, now=datetime.now(timezone.utc),
|
|
105
|
+
seen_nonces=set(), currency_policy="record", in_force={"acme-purchasing": SEAL_HASH})
|
|
106
|
+
chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Conformance
|
|
110
|
+
|
|
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
|
|
113
|
+
0.6.0 and NOMOS-SPEC-010 0.2.0;
|
|
114
|
+
- the NOMOS-SPEC-009 selection vectors;
|
|
115
|
+
- the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
|
|
116
|
+
(`python/tests/conformance_rp.py`).
|
|
117
|
+
|
|
118
|
+
`act()` also interoperates with the JavaScript sandbox, escalation and approval included
|
|
119
|
+
(`python/tests/interop_sandbox.py`).
|
|
120
|
+
|
|
121
|
+
MIT licensed.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
nomosprotocol/__init__.py,sha256=R2l3Df4PnSjMndQlI6fvquepEk2R7ncNqYVfdAO_CBs,2175
|
|
2
|
+
nomosprotocol/accept.py,sha256=7_N6z-thPWNdrBZ_1TuxZeI6xyN0ldbUgyYgZMzj8lQ,19995
|
|
3
|
+
nomosprotocol/act.py,sha256=vfUuiHosVB-ZTkUAJ_Rs12V95LXR-Hrj8gWbLmDfqKY,29634
|
|
4
|
+
nomosprotocol/carrier.py,sha256=sy5SMLQ_9YLk4-2JPJbfbSmLxzNfZQI0PYnQhCejto4,11286
|
|
5
|
+
nomosprotocol/chain.py,sha256=_134KQsvqUKNrtfgVJ1FbqUhrlyeQMd58WatBPG-I14,22705
|
|
6
|
+
nomosprotocol/issuer.py,sha256=zPnf-WhFOnU01LxvQzjhMl3Hf9Lv5jzg9TnR_b5_Xu0,4186
|
|
7
|
+
nomosprotocol/jcs.py,sha256=J-68og75XXSyS9_vhxSwA4e-ORJG0U6_EpWJZImY7cU,2020
|
|
8
|
+
nomosprotocol/statements.py,sha256=kd22mnZtugByqS-wYcxUKCDH7fnAHOkjSOKclxk0XqA,10471
|
|
9
|
+
nomosprotocol/suites.py,sha256=Bd6NpRxsNS9Jr5hup1tjmnu6L5d2JL7kD93C-Nua9JY,10863
|
|
10
|
+
nomosprotocol/witness.py,sha256=OzRyHE2CITL4QFPBKAkrHC0CgEL1CtnIQd26Zpp8UZM,4313
|
|
11
|
+
nomosprotocol-0.1.0.dist-info/METADATA,sha256=DtZ-4oLN8g-EfGTbDinX16n4ocTdBQ2XRSbxjCg_XZk,5281
|
|
12
|
+
nomosprotocol-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
13
|
+
nomosprotocol-0.1.0.dist-info/top_level.txt,sha256=zt1IApGYE3yiw3GHDlwxI4sYZpf9zt_sfqvMRKy6TGA,14
|
|
14
|
+
nomosprotocol-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nomosprotocol
|