decision-cert 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ """Verify and apply `decision-certificate.v1` (spec/decision-certificate.v1.md).
2
+
3
+ A port of the Rust crate in this repository's `rust/`, which is the reference: both must agree on
4
+ every conformance fixture. A certificate describes a measured process; it never promises an outcome.
5
+
6
+ from decision_cert import loads, verify
7
+ v = verify(loads(open("cert.json").read()), keys) # keys: key id -> base64url public key
8
+ v.id, v.threshold_for("north"), v.is_expired(now)
9
+ """
10
+
11
+ from ._verify import (
12
+ ABSTAIN_ALL,
13
+ SPEC,
14
+ BadKey,
15
+ BadSignature,
16
+ CertError,
17
+ Invalid,
18
+ UntrustedKey,
19
+ Verified,
20
+ canonical,
21
+ certificate_id,
22
+ is_expired,
23
+ key_id,
24
+ loads,
25
+ threshold_for,
26
+ timestamp,
27
+ verify,
28
+ )
29
+
30
+ __version__ = "0.1.0"
31
+
32
+ __all__ = [
33
+ "ABSTAIN_ALL",
34
+ "SPEC",
35
+ "BadKey",
36
+ "BadSignature",
37
+ "CertError",
38
+ "Invalid",
39
+ "UntrustedKey",
40
+ "Verified",
41
+ "__version__",
42
+ "canonical",
43
+ "certificate_id",
44
+ "is_expired",
45
+ "key_id",
46
+ "loads",
47
+ "threshold_for",
48
+ "timestamp",
49
+ "verify",
50
+ ]
@@ -0,0 +1,73 @@
1
+ """`python -m decision_cert verify <cert.json> --keys <keys.json> [--now <ts>]`
2
+
3
+ Exit 0: the certificate verifies against the trusted keys and has not expired at `--now` (default:
4
+ the current time); its id is printed on stdout.
5
+ Exit 1: it does not verify, or it has expired; the reason is printed on stderr.
6
+ Exit 2: usage error, an unreadable file, or a keys file that is not a JSON object of strings.
7
+ The Rust `decision-cert verify` behaves the same.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import datetime as dt
14
+ import sys
15
+ from collections.abc import Sequence
16
+ from pathlib import Path
17
+
18
+ from . import CertError, Invalid, loads, timestamp, verify
19
+
20
+
21
+ def _usage(msg: str) -> int:
22
+ print(f"decision-cert: {msg}", file=sys.stderr)
23
+ return 2
24
+
25
+
26
+ def main(argv: Sequence[str] | None = None) -> int:
27
+ ap = argparse.ArgumentParser(prog="decision-cert", description="Verify decision-certificate.v1 certificates")
28
+ sub = ap.add_subparsers(dest="command", required=True)
29
+ v = sub.add_parser("verify", help="Verify a certificate against trusted keys and check its expiry.")
30
+ v.add_argument("cert", type=Path, help="The certificate, a JSON object.")
31
+ v.add_argument("--keys", type=Path, required=True, help="Trusted keys: key id -> base64url public key.")
32
+ v.add_argument("--now", help="The time to check expiry at, YYYY-MM-DDTHH:MM:SSZ (default: now).")
33
+ args = ap.parse_args(argv) # exits 2 on a usage error
34
+
35
+ try:
36
+ keys_text = args.keys.read_text(encoding="utf-8")
37
+ except (OSError, UnicodeDecodeError) as e:
38
+ return _usage(f"{args.keys}: {e}")
39
+ try:
40
+ keys = loads(keys_text)
41
+ except Invalid as e:
42
+ return _usage(f"{args.keys}: not a JSON object of key id -> public key: {e}")
43
+ if not isinstance(keys, dict) or not all(isinstance(k, str) and isinstance(x, str) for k, x in keys.items()):
44
+ return _usage(f"{args.keys}: not a JSON object of key id -> public key")
45
+ if args.now is None:
46
+ now = dt.datetime.now(dt.UTC)
47
+ else:
48
+ try:
49
+ now = timestamp(args.now)
50
+ except Invalid:
51
+ return _usage(f"--now {args.now!r} is not YYYY-MM-DDTHH:MM:SSZ")
52
+ try:
53
+ text = args.cert.read_text(encoding="utf-8")
54
+ except (OSError, UnicodeDecodeError) as e:
55
+ return _usage(f"{args.cert}: {e}")
56
+
57
+ try:
58
+ cert = verify(loads(text), keys)
59
+ except CertError as e:
60
+ print(f"{args.cert}: {e}", file=sys.stderr)
61
+ return 1
62
+ if cert.is_expired(now):
63
+ print(
64
+ f"{args.cert}: certificate {cert.id} has expired (its expires_at is not after the check time)",
65
+ file=sys.stderr,
66
+ )
67
+ return 1
68
+ print(cert.id)
69
+ return 0
70
+
71
+
72
+ if __name__ == "__main__":
73
+ sys.exit(main())
@@ -0,0 +1,85 @@
1
+ """The parts of Ed25519 point handling that `cryptography` does not expose, in pure Python.
2
+
3
+ The Rust crate verifies with ed25519-dalek's `verify_strict`, which on top of the RFC 8032 equation
4
+ rejects a small-order public key `A` or a small-order `R`, and a non-canonical `S`. OpenSSL (behind
5
+ `cryptography`) checks `S` but not small order, so these checks run here first. Decoding follows
6
+ curve25519-dalek's `CompressedEdwardsY::decompress`, which is what the Rust crate uses: `y` is read
7
+ modulo p and `x = 0` with the sign bit set is accepted. Nothing here is secret, so nothing here needs
8
+ to run in constant time.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ P = 2**255 - 19
14
+ L = 2**252 + 27742317777372353535851937790883648493
15
+ D = -121665 * pow(121666, P - 2, P) % P
16
+ _SQRT_M1 = pow(2, (P - 1) // 4, P)
17
+
18
+ Point = tuple[int, int, int, int] # extended coordinates (X, Y, Z, T), x = X/Z, y = Y/Z, xy = T/Z
19
+
20
+
21
+ def decode(b: bytes) -> Point | None:
22
+ """The point a 32-byte encoding names, or None when it names no curve point."""
23
+ if len(b) != 32:
24
+ return None
25
+ n = int.from_bytes(b, "little")
26
+ sign = n >> 255
27
+ y = (n & ((1 << 255) - 1)) % P
28
+ u = (y * y - 1) % P
29
+ v = (D * y * y + 1) % P
30
+ # x = sqrt(u / v), per RFC 8032 §5.1.3 step 3.
31
+ x = u * pow(v, 3, P) * pow(u * pow(v, 7, P), (P - 5) // 8, P) % P
32
+ if (v * x * x - u) % P != 0:
33
+ x = x * _SQRT_M1 % P
34
+ if (v * x * x - u) % P != 0:
35
+ return None
36
+ if (x & 1) != sign:
37
+ x = (P - x) % P
38
+ return (x, y, 1, x * y % P)
39
+
40
+
41
+ def add(p: Point, q: Point) -> Point:
42
+ x1, y1, z1, t1 = p
43
+ x2, y2, z2, t2 = q
44
+ a = (y1 - x1) * (y2 - x2) % P
45
+ b = (y1 + x1) * (y2 + x2) % P
46
+ c = t1 * 2 * D * t2 % P
47
+ d = z1 * 2 * z2 % P
48
+ e, f, g, h = b - a, d - c, d + c, b + a
49
+ return (e * f % P, g * h % P, f * g % P, e * h % P)
50
+
51
+
52
+ IDENTITY: Point = (0, 1, 1, 0)
53
+
54
+
55
+ def mul(k: int, p: Point) -> Point:
56
+ out = IDENTITY
57
+ while k:
58
+ if k & 1:
59
+ out = add(out, p)
60
+ p = add(p, p)
61
+ k >>= 1
62
+ return out
63
+
64
+
65
+ def is_identity(p: Point) -> bool:
66
+ x, y, z, _ = p
67
+ return x % P == 0 and (y - z) % P == 0
68
+
69
+
70
+ def is_small_order(p: Point) -> bool:
71
+ """True when 8·p is the identity: p lies in the torsion subgroup."""
72
+ for _ in range(3):
73
+ p = add(p, p)
74
+ return is_identity(p)
75
+
76
+
77
+ def encode(p: Point) -> bytes:
78
+ x, y, z, _ = p
79
+ zi = pow(z, P - 2, P)
80
+ x, y = x * zi % P, y * zi % P
81
+ return (y | ((x & 1) << 255)).to_bytes(32, "little")
82
+
83
+
84
+ _BASE_Y = 4 * pow(5, P - 2, P) % P
85
+ BASE: Point = decode(_BASE_Y.to_bytes(32, "little")) # type: ignore[assignment]
@@ -0,0 +1,549 @@
1
+ """A port of the Rust crate's `verify` (rust/src/lib.rs). The Rust crate is the oracle: where the two
2
+ disagree on a certificate, this module is wrong.
3
+
4
+ The typed read mirrors serde's: every field is required, nullable fields must be present (as null),
5
+ unknown fields are rejected at every level, booleans are never numbers, and integer fields reject
6
+ floats even when integral. `check` then mirrors the crate's `check`, the schema constraints a typed
7
+ read does not enforce.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import binascii
14
+ import datetime as dt
15
+ import hashlib
16
+ import json
17
+ import math
18
+ from collections.abc import Callable, Mapping
19
+ from dataclasses import dataclass, field
20
+ from typing import Any
21
+
22
+ import rfc8785
23
+ from cryptography.exceptions import InvalidSignature
24
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
25
+
26
+ from . import _ed25519
27
+
28
+ SPEC = "decision-certificate.v1"
29
+ #: `abstain_below` that abstains on every case.
30
+ ABSTAIN_ALL = 1.01
31
+
32
+ _U64_MAX = 2**64 - 1
33
+ _I64 = (-(2**63), 2**63 - 1)
34
+ _SAFE_INT = 2**53 - 1
35
+
36
+
37
+ class CertError(Exception):
38
+ """A certificate that does not verify. The message matches the Rust crate's `CertError`."""
39
+
40
+
41
+ class Invalid(CertError):
42
+ def __init__(self, reason: str) -> None:
43
+ super().__init__(f"certificate is not a valid {SPEC}: {reason}")
44
+
45
+
46
+ class UntrustedKey(CertError):
47
+ def __init__(self, key_id: str) -> None:
48
+ super().__init__(f"certificate signed by {key_id}, which is not a trusted key")
49
+
50
+
51
+ class BadKey(CertError):
52
+ def __init__(self, key_id: str) -> None:
53
+ super().__init__(f"trusted key {key_id} is malformed or does not hash to its id")
54
+
55
+
56
+ class BadSignature(CertError):
57
+ def __init__(self) -> None:
58
+ super().__init__("certificate signature does not verify")
59
+
60
+
61
+ class _TypeError(Exception):
62
+ """A serde-style typed-read error; becomes `Invalid`."""
63
+
64
+
65
+ # ---------- typed read (serde's semantics) ----------
66
+
67
+
68
+ def _unexpected(v: Any) -> str:
69
+ if v is None:
70
+ return "null"
71
+ if isinstance(v, bool):
72
+ return f"boolean `{'true' if v else 'false'}`"
73
+ if isinstance(v, int):
74
+ return f"integer `{v}`"
75
+ if isinstance(v, float):
76
+ return f"floating point `{v!r}`"
77
+ if isinstance(v, str):
78
+ return f"string {json.dumps(v, ensure_ascii=False)}"
79
+ if isinstance(v, list):
80
+ return "sequence"
81
+ if isinstance(v, Mapping):
82
+ return "map"
83
+ return type(v).__name__
84
+
85
+
86
+ def _bad_type(v: Any, expected: str) -> _TypeError:
87
+ return _TypeError(f"invalid type: {_unexpected(v)}, expected {expected}")
88
+
89
+
90
+ Reader = Callable[[Any], Any]
91
+
92
+
93
+ def _string(v: Any) -> str:
94
+ if not isinstance(v, str):
95
+ raise _bad_type(v, "a string")
96
+ return v
97
+
98
+
99
+ def _boolean(v: Any) -> bool:
100
+ if not isinstance(v, bool):
101
+ raise _bad_type(v, "a boolean")
102
+ return v
103
+
104
+
105
+ def _f64(v: Any) -> float:
106
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
107
+ raise _bad_type(v, "f64")
108
+ try:
109
+ x = float(v)
110
+ except OverflowError:
111
+ raise _TypeError(f"invalid value: {_unexpected(v)}, expected f64") from None
112
+ if not math.isfinite(x):
113
+ raise _TypeError(f"invalid value: {_unexpected(v)}, expected a finite f64")
114
+ return x
115
+
116
+
117
+ def _integer(lo: int, hi: int, name: str) -> Reader:
118
+ def read(v: Any) -> int:
119
+ if isinstance(v, bool) or not isinstance(v, int):
120
+ raise _bad_type(v, name)
121
+ if not lo <= v <= hi:
122
+ raise _TypeError(f"invalid value: {_unexpected(v)}, expected {name}")
123
+ return v
124
+
125
+ return read
126
+
127
+
128
+ _u64 = _integer(0, _U64_MAX, "u64")
129
+ _i64 = _integer(*_I64, "i64")
130
+
131
+
132
+ def _nullable(inner: Reader) -> Reader:
133
+ return lambda v: None if v is None else inner(v)
134
+
135
+
136
+ def _seq(inner: Reader) -> Reader:
137
+ def read(v: Any) -> list[Any]:
138
+ if not isinstance(v, list):
139
+ raise _bad_type(v, "a sequence")
140
+ return [inner(x) for x in v]
141
+
142
+ return read
143
+
144
+
145
+ def _map_of(inner: Reader) -> Reader:
146
+ def read(v: Any) -> dict[str, Any]:
147
+ if not isinstance(v, Mapping):
148
+ raise _bad_type(v, "a map")
149
+ return {_string(k): inner(x) for k, x in sorted(v.items())}
150
+
151
+ return read
152
+
153
+
154
+ def _struct(name: str, fields: dict[str, Reader]) -> Reader:
155
+ """A `#[serde(deny_unknown_fields)]` struct with no defaults. Keys are read in sorted order (as
156
+ serde_json's map holds them), and missing fields are reported after the present ones."""
157
+
158
+ def read(v: Any) -> dict[str, Any]:
159
+ if not isinstance(v, Mapping):
160
+ raise _bad_type(v, f"struct {name}")
161
+ out: dict[str, Any] = {}
162
+ for k in sorted(v):
163
+ if not isinstance(k, str):
164
+ raise _bad_type(k, "a string")
165
+ if k not in fields:
166
+ raise _TypeError(f"unknown field `{k}`, expected one of {', '.join(f'`{f}`' for f in fields)}")
167
+ out[k] = fields[k](v[k])
168
+ for f in fields:
169
+ if f not in out:
170
+ raise _TypeError(f"missing field `{f}`")
171
+ return out
172
+
173
+ return read
174
+
175
+
176
+ _band = _struct("Band", {"level": _f64, "low": _f64, "high": _f64})
177
+ _segment = _struct(
178
+ "Segment",
179
+ {
180
+ "field": _string,
181
+ "value": _string,
182
+ "n": _u64,
183
+ "abstain_below": _f64,
184
+ "coverage": _f64,
185
+ "ucb": _nullable(_f64),
186
+ "realized_band": _nullable(_band),
187
+ "inherited": _boolean,
188
+ },
189
+ )
190
+ _certificate = _struct(
191
+ "Certificate",
192
+ {
193
+ "spec": _string,
194
+ "domain": _string,
195
+ "decision": _string,
196
+ "options": _seq(_string),
197
+ "model_id": _string,
198
+ "manifest_hash": _nullable(_string),
199
+ "data_hash": _string,
200
+ "n_cal": _u64,
201
+ "n_temperature": _u64,
202
+ "split": _struct("Split", {"method": _string, "seed": _nullable(_i64)}),
203
+ "calibration_map": _struct(
204
+ "CalibrationMap", {"kind": _string, "params": _map_of(_f64), "label_budget": _nullable(_u64)}
205
+ ),
206
+ "rule": _struct("Rule", {"cannot_tell_above": _nullable(_f64), "unscored": _string}),
207
+ "alpha": _f64,
208
+ "delta": _nullable(_f64),
209
+ "method": _string,
210
+ "risk": _string,
211
+ "n": _u64,
212
+ "abstain_below": _f64,
213
+ "coverage": _f64,
214
+ "ucb": _nullable(_f64),
215
+ "realized_band": _band,
216
+ "segments": _seq(_segment),
217
+ "window": _nullable(_struct("Window", {"start": _string, "end": _string})),
218
+ "fitted_at": _string,
219
+ "expires_at": _string,
220
+ "audit": _struct("Audit", {"mode": _string, "rate": _f64, "n": _u64, "propensity_logged": _boolean}),
221
+ "issuer": _struct("Issuer", {"tool": _string, "version": _string}),
222
+ "signer_key_id": _string,
223
+ "signature": _string,
224
+ },
225
+ )
226
+
227
+
228
+ # ---------- check (the schema constraints a typed read doesn't enforce) ----------
229
+
230
+
231
+ def _unit(x: float) -> bool:
232
+ return 0.0 <= x <= 1.0
233
+
234
+
235
+ def _open(x: float) -> bool:
236
+ return 0.0 < x < 1.0
237
+
238
+
239
+ def _threshold(x: float) -> bool:
240
+ return 0.0 <= x <= ABSTAIN_ALL
241
+
242
+
243
+ def _band_ok(b: Mapping[str, float]) -> bool:
244
+ return _open(b["level"]) and _unit(b["low"]) and _unit(b["high"])
245
+
246
+
247
+ def _lower_hex(s: str) -> bool:
248
+ return all(c in "0123456789abcdef" for c in s)
249
+
250
+
251
+ def _sha256_ok(h: str) -> bool:
252
+ return h.startswith("sha256:") and len(h) == 71 and _lower_hex(h[7:])
253
+
254
+
255
+ def _model_id_ok(m: str) -> bool:
256
+ """`^[^/]+/.+@.+$`, and not ending in `@?`. The pattern's `.` matches no line terminator."""
257
+ if any(c in "\n\r\u2028\u2029" for c in m):
258
+ return False
259
+ backend, slash, rest = m.partition("/")
260
+ if not slash or not backend:
261
+ return False
262
+ at = any(ch == "@" and i + 1 < len(rest) for i, ch in enumerate(rest) if i >= 1)
263
+ return at and not m.endswith("@?")
264
+
265
+
266
+ _B64URL = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
267
+
268
+
269
+ def _check(c: Mapping[str, Any]) -> None:
270
+ def bad(m: str) -> Invalid:
271
+ return Invalid(m)
272
+
273
+ if c["spec"] != SPEC:
274
+ raise bad("spec is not decision-certificate.v1")
275
+ opts = c["options"]
276
+ if len(opts) < 2 or not all(o for o in opts) or len(set(opts)) != len(opts):
277
+ raise bad("options needs at least 2 distinct non-empty ids")
278
+ if not all((c["domain"], c["decision"], c["calibration_map"]["kind"], c["issuer"]["tool"], c["issuer"]["version"])):
279
+ raise bad("domain, decision, calibration_map.kind and issuer must be non-empty")
280
+ method, risk, delta, ucb = c["method"], c["risk"], c["delta"], c["ucb"]
281
+ if not (
282
+ (method == "ltt" and risk == "selective_error" and delta is not None and _open(delta))
283
+ or (method == "crc" and risk == "joint_error" and delta is None and ucb is None)
284
+ ):
285
+ raise bad("method, risk, delta and ucb disagree")
286
+ if not _open(c["alpha"]) or not _threshold(c["abstain_below"]) or not _unit(c["coverage"]):
287
+ raise bad("alpha, abstain_below or coverage out of range")
288
+ if (ucb is not None and not _unit(ucb)) or not _band_ok(c["realized_band"]):
289
+ raise bad("ucb or realized_band out of range")
290
+ for s in c["segments"]:
291
+ if (
292
+ not s["field"]
293
+ or not _threshold(s["abstain_below"])
294
+ or not _unit(s["coverage"])
295
+ or (s["ucb"] is not None and not _unit(s["ucb"]))
296
+ or (s["realized_band"] is not None and not _band_ok(s["realized_band"]))
297
+ ):
298
+ raise bad("a segment is out of range")
299
+ split = c["split"]
300
+ if not (
301
+ (split["method"] == "time" and split["seed"] is None)
302
+ or (split["method"] == "seeded" and split["seed"] is not None)
303
+ ):
304
+ raise bad("split.method and split.seed disagree")
305
+ rule = c["rule"]
306
+ if rule["unscored"] != "abstain" or (
307
+ rule["cannot_tell_above"] is not None and not _unit(rule["cannot_tell_above"])
308
+ ):
309
+ raise bad("rule out of range")
310
+ audit = c["audit"]
311
+ if audit["mode"] not in ("sample", "full-label") or not 0.0 < audit["rate"] <= 1.0:
312
+ raise bad("audit out of range")
313
+ if not _model_id_ok(c["model_id"]):
314
+ raise bad("model_id must be <backend>/<model>@<version>")
315
+ if not _sha256_ok(c["data_hash"]) or (c["manifest_hash"] is not None and not _sha256_ok(c["manifest_hash"])):
316
+ raise bad("data_hash and manifest_hash must be sha256:<64 hex>")
317
+ kid = c["signer_key_id"]
318
+ if not (kid.startswith("ed25519:") and len(kid) == 24 and _lower_hex(kid[8:])):
319
+ raise bad("signer_key_id must be ed25519:<16 hex>")
320
+ sig = c["signature"]
321
+ if len(sig) != 86 or not set(sig) <= _B64URL:
322
+ raise bad("signature must be 86 base64url characters")
323
+ timestamp(c["fitted_at"])
324
+ timestamp(c["expires_at"])
325
+ if c["window"] is not None:
326
+ timestamp(c["window"]["start"])
327
+ timestamp(c["window"]["end"])
328
+
329
+
330
+ # ---------- timestamps ----------
331
+
332
+
333
+ def _days_in_month(year: int, month: int) -> int:
334
+ if month == 2:
335
+ return 29 if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) else 28
336
+ return 30 if month in (4, 6, 9, 11) else 31
337
+
338
+
339
+ def timestamp(s: str) -> dt.datetime:
340
+ """Parse the spec's timestamp form, `YYYY-MM-DDTHH:MM:SSZ`, exactly as the Rust crate does.
341
+
342
+ Like the crate (chrono), a leap second (`:60`) and year 0000 are accepted. Python's datetime can
343
+ hold neither, so `:60` reads as `:59.999999` and year 0000 as `datetime.min`; both keep
344
+ `is_expired` correct at microsecond resolution.
345
+ """
346
+ digits = "0123456789"
347
+ shape = len(s) == 20 and all(
348
+ (ch == "-")
349
+ if i in (4, 7)
350
+ else (ch == "T")
351
+ if i == 10
352
+ else (ch == ":")
353
+ if i in (13, 16)
354
+ else (ch == "Z")
355
+ if i == 19
356
+ else (ch in digits)
357
+ for i, ch in enumerate(s)
358
+ )
359
+ if shape:
360
+ y, mo, d, h, mi, se = (int(s[a:b]) for a, b in ((0, 4), (5, 7), (8, 10), (11, 13), (14, 16), (17, 19)))
361
+ if 1 <= mo <= 12 and 1 <= d <= _days_in_month(y, mo) and h <= 23 and mi <= 59 and se <= 60:
362
+ if y == 0:
363
+ return dt.datetime.min.replace(tzinfo=dt.UTC)
364
+ if se == 60:
365
+ return dt.datetime(y, mo, d, h, mi, 59, 999999, tzinfo=dt.UTC)
366
+ return dt.datetime(y, mo, d, h, mi, se, tzinfo=dt.UTC)
367
+ raise Invalid(f"timestamp {json.dumps(s, ensure_ascii=False)} is not YYYY-MM-DDTHH:MM:SSZ")
368
+
369
+
370
+ # ---------- canonical bytes, ids, keys ----------
371
+
372
+
373
+ def _as_serde_number(v: Any) -> Any:
374
+ """serde_jcs writes every number through f64, so an integer beyond 2^53 loses precision there;
375
+ rfc8785 refuses it instead. Convert such integers the way the crate does."""
376
+ if isinstance(v, bool) or v is None or isinstance(v, (str, float)):
377
+ return v
378
+ if isinstance(v, int):
379
+ return float(v) if abs(v) > _SAFE_INT else v
380
+ if isinstance(v, Mapping):
381
+ return {k: _as_serde_number(x) for k, x in v.items()}
382
+ if isinstance(v, (list, tuple)):
383
+ return [_as_serde_number(x) for x in v]
384
+ return v
385
+
386
+
387
+ def canonical(v: Any) -> bytes:
388
+ """The RFC 8785 (JCS) bytes of a JSON value, identical to the crate's `canonical`."""
389
+ try:
390
+ return rfc8785.dumps(_as_serde_number(v))
391
+ except Exception as e: # noqa: BLE001 - rfc8785 raises several unrelated types
392
+ raise Invalid(f"not canonicalisable: {e}") from None
393
+
394
+
395
+ def certificate_id(v: Any) -> str:
396
+ """`sha256:` + hex SHA-256 of the signed certificate's canonical bytes."""
397
+ return "sha256:" + hashlib.sha256(canonical(v)).hexdigest()
398
+
399
+
400
+ def key_id(raw_public_key: bytes) -> str:
401
+ """`ed25519:` + the first 16 hex chars of SHA-256 of the raw 32-byte public key."""
402
+ return "ed25519:" + hashlib.sha256(raw_public_key).hexdigest()[:16]
403
+
404
+
405
+ def b64url_decode(s: str) -> bytes | None:
406
+ """Strict base64url without padding, as the crate's `URL_SAFE_NO_PAD`: no `=`, no characters
407
+ outside the alphabet, no non-zero trailing bits. None when `s` is not such a string."""
408
+ if not isinstance(s, str) or not set(s) <= _B64URL or len(s) % 4 == 1:
409
+ return None
410
+ try:
411
+ b = base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
412
+ except (binascii.Error, ValueError):
413
+ return None
414
+ return b if b64url_encode(b) == s else None
415
+
416
+
417
+ def b64url_encode(b: bytes) -> str:
418
+ return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
419
+
420
+
421
+ def _verify_strict(raw_key: bytes, sig: bytes, msg: bytes) -> bool:
422
+ """ed25519-dalek's `verify_strict`: canonical S, neither A nor R of small order, then RFC 8032."""
423
+ if int.from_bytes(sig[32:], "little") >= _ed25519.L:
424
+ return False
425
+ a = _ed25519.decode(raw_key)
426
+ r = _ed25519.decode(sig[:32])
427
+ if a is None or r is None or _ed25519.is_small_order(a) or _ed25519.is_small_order(r):
428
+ return False
429
+ try:
430
+ Ed25519PublicKey.from_public_bytes(raw_key).verify(sig, msg)
431
+ except (InvalidSignature, ValueError):
432
+ return False
433
+ return True
434
+
435
+
436
+ # ---------- verify ----------
437
+
438
+
439
+ @dataclass(frozen=True)
440
+ class Verified:
441
+ """A certificate whose signature verified against a trusted key."""
442
+
443
+ #: `sha256:<hex>` of the signed certificate's canonical bytes.
444
+ id: str
445
+ #: The certificate as received.
446
+ cert: Mapping[str, Any]
447
+ expires_at: dt.datetime
448
+ _typed: Mapping[str, Any] = field(repr=False, compare=False)
449
+
450
+ def threshold_for(self, segment: str | None) -> float:
451
+ """The threshold for a case in `segment`: a certified segment's own, else the top-level one."""
452
+ if segment is not None:
453
+ for s in self._typed["segments"]:
454
+ if not s["inherited"] and s["value"] == segment:
455
+ return float(s["abstain_below"])
456
+ return float(self._typed["abstain_below"])
457
+
458
+ def is_expired(self, now: dt.datetime) -> bool:
459
+ """True from `expires_at` on. `now` must be timezone-aware."""
460
+ if now.tzinfo is None or now.utcoffset() is None:
461
+ raise ValueError("now must be timezone-aware")
462
+ return now >= self.expires_at
463
+
464
+ def temperature(self) -> float | None:
465
+ """The temperature of a `kind: temperature` calibration map; None for other kinds."""
466
+ m = self._typed["calibration_map"]
467
+ if m["kind"] != "temperature":
468
+ return None
469
+ t = m["params"].get("temperature")
470
+ return None if t is None else float(t)
471
+
472
+
473
+ def verify(v: Any, keys: Mapping[str, str]) -> Verified:
474
+ """Verify `v` (a parsed JSON value) against `keys` (key id → base64url raw public key) and read it.
475
+
476
+ Raises `Invalid`, `UntrustedKey`, `BadKey` or `BadSignature`, in that order of checking.
477
+ """
478
+ if not isinstance(v, Mapping):
479
+ raise Invalid("not a JSON object")
480
+ try:
481
+ typed = _certificate(v)
482
+ except _TypeError as e:
483
+ raise Invalid(str(e)) from None
484
+ _check(typed)
485
+
486
+ kid = typed["signer_key_id"]
487
+ if kid not in keys:
488
+ raise UntrustedKey(kid)
489
+ raw = b64url_decode(keys[kid])
490
+ if raw is None or len(raw) != 32 or _ed25519.decode(raw) is None or key_id(raw) != kid:
491
+ raise BadKey(kid)
492
+ sig = b64url_decode(typed["signature"])
493
+ if sig is None or len(sig) != 64:
494
+ raise BadSignature()
495
+ body = {k: x for k, x in v.items() if k != "signature"}
496
+ if not _verify_strict(raw, sig, canonical(body)):
497
+ raise BadSignature()
498
+
499
+ return Verified(id=certificate_id(v), cert=v, expires_at=timestamp(typed["expires_at"]), _typed=typed)
500
+
501
+
502
+ def is_expired(cert: Verified, now: dt.datetime) -> bool:
503
+ """Module-level form of `Verified.is_expired`."""
504
+ return cert.is_expired(now)
505
+
506
+
507
+ def threshold_for(cert: Verified, segment: str | None) -> float:
508
+ """Module-level form of `Verified.threshold_for`."""
509
+ return cert.threshold_for(segment)
510
+
511
+
512
+ def _reject_constant(name: str) -> Any:
513
+ raise Invalid(f"{name} is not a JSON number")
514
+
515
+
516
+ def _parse_int(s: str) -> int | float:
517
+ # serde_json reads `-0` as the float -0.0, so an integer field rejects it.
518
+ return -0.0 if s == "-0" else int(s)
519
+
520
+
521
+ def _parse_float(s: str) -> float:
522
+ x = float(s)
523
+ if not math.isfinite(x):
524
+ raise Invalid(f"number {s} is out of range")
525
+ return x
526
+
527
+
528
+ def _no_surrogates(v: Any) -> None:
529
+ if isinstance(v, str):
530
+ if any(0xD800 <= ord(c) <= 0xDFFF for c in v):
531
+ raise Invalid("string contains a lone surrogate")
532
+ elif isinstance(v, Mapping):
533
+ for k, x in v.items():
534
+ _no_surrogates(k)
535
+ _no_surrogates(x)
536
+ elif isinstance(v, list):
537
+ for x in v:
538
+ _no_surrogates(x)
539
+
540
+
541
+ def loads(text: str | bytes) -> Any:
542
+ """Parse JSON as the crate's serde_json does: no NaN or Infinity, no out-of-range numbers, no lone
543
+ surrogates, `-0` read as a float. A duplicate key keeps its last value, as in serde_json."""
544
+ try:
545
+ v = json.loads(text, parse_constant=_reject_constant, parse_int=_parse_int, parse_float=_parse_float)
546
+ except (ValueError, RecursionError) as e:
547
+ raise Invalid(f"not JSON: {e}") from None
548
+ _no_surrogates(v)
549
+ return v
decision_cert/py.typed ADDED
File without changes
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.5
2
+ Name: decision-cert
3
+ Version: 0.1.0
4
+ Summary: Verify and apply decision-certificate.v1: signed records of how a model's decisions were measured
5
+ Project-URL: Repository, https://github.com/zer07labs/decision-cert
6
+ Project-URL: Specification, https://github.com/zer07labs/decision-cert/blob/main/spec/decision-certificate.v1.md
7
+ Author: zer07 Labs
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: calibration,certificate,ed25519,jcs,verification
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Security :: Cryptography
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.12
17
+ Requires-Dist: cryptography>=43
18
+ Requires-Dist: rfc8785>=0.1.4
19
+ Description-Content-Type: text/markdown
20
+
21
+ # decision-cert (Python verifier)
22
+
23
+ A pure-Python verifier for `decision-certificate.v1`, a port of the Rust crate in
24
+ [`rust/`](https://github.com/zer07labs/decision-cert/tree/main/rust). Dependencies: `rfc8785` and `cryptography`, nothing else. It verifies; it
25
+ does not issue.
26
+
27
+ ```python
28
+ from decision_cert import loads, verify
29
+
30
+ cert = loads(open("cert.json").read()) # strict JSON, as the Rust crate parses it
31
+ keys = loads(open("trusted-keys.json").read()) # key id -> base64url raw Ed25519 public key
32
+ v = verify(cert, keys) # raises Invalid, UntrustedKey, BadKey or BadSignature
33
+ v.id, v.threshold_for("north"), v.is_expired(datetime.now(UTC))
34
+ ```
35
+
36
+ The Rust crate is the reference. This package passes the same conformance fixtures
37
+ ([`fixtures/`](https://github.com/zer07labs/decision-cert/tree/main/fixtures)); where the two disagree, this package is wrong. A certificate
38
+ describes a measured process and never promises an outcome; see the
39
+ [spec](https://github.com/zer07labs/decision-cert/blob/main/spec/decision-certificate.v1.md).
40
+
41
+ ```bash
42
+ pip install decision-cert
43
+ python -m decision_cert verify cert.json --keys trusted-keys.json # exit 0 / 1 / 2
44
+ ```
45
+
46
+ Development, from `python/` in the repository:
47
+
48
+ ```bash
49
+ uv sync && uv run pytest && uv run ruff check && uv run mypy
50
+ ```
@@ -0,0 +1,10 @@
1
+ decision_cert/__init__.py,sha256=iDtXDW4gGODvqYiDef3AjPJGO3FBnTLaHWiOvxDp1G8,1068
2
+ decision_cert/__main__.py,sha256=gicGRr3wVU3pEbrZxSY08SnRKxV9rDmyg_CeRpQSA24,2759
3
+ decision_cert/_ed25519.py,sha256=0n3BeyYvY7cFRsn0ph10c3isfj-U5K3YtQTg5dVzcPI,2615
4
+ decision_cert/_verify.py,sha256=aRf7dR3DkaJXu83uJbdOC2UdImhX6cPwFInPi3NnfoI,18882
5
+ decision_cert/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ decision_cert-0.1.0.dist-info/METADATA,sha256=APLFVP8PL81kp9w70zkPPq1M-8SgTfpxVicPSDkas_I,2112
7
+ decision_cert-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ decision_cert-0.1.0.dist-info/entry_points.txt,sha256=bTtuSaC8ZKdTI0K9RPfX9ClRn6NONmpfvpRgLiEd2D4,62
9
+ decision_cert-0.1.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
10
+ decision_cert-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ decision-cert = decision_cert.__main__:main
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+