#!/usr/bin/env python3 # Independent verifier for mtb-receipt v1, written from the rules in the spec, not from the JS. import sys, json, base64, hashlib, re from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey from cryptography.exceptions import InvalidSignature def d(s): if not re.fullmatch(r"[A-Za-z0-9_-]*", s): raise ValueError("b64") return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) def e(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode() def verify(token, ctx, keys): parts = token.strip().split(".") if len(parts) != 3 or not parts[0] or not parts[1]: return "bad_format" try: h = json.loads(d(parts[0])) except Exception: return "bad_format" if not isinstance(h, dict): return "bad_format" if h.get("alg") != "EdDSA": return "alg_not_allowed" if h.get("typ") != "application/mtb-receipt+jws": return "bad_format" x = keys.get(h.get("kid")) if x is None: return "unknown_kid" try: sig = d(parts[2]) except Exception: return "bad_format" if len(sig) != 64: return "bad_signature" try: Ed25519PublicKey.from_public_bytes(d(x)).verify(sig, (parts[0] + "." + parts[1]).encode()) except InvalidSignature: return "bad_signature" try: p = json.loads(d(parts[1])) except Exception: return "bad_format" if not isinstance(p, dict) or p.get("ver") != "1": return "bad_format" if not isinstance(p.get("nbf"), int) or not isinstance(p.get("exp"), int): return "bad_format" if ctx["now"] < p["nbf"]: return "not_yet_valid" if ctx["now"] >= p["exp"]: return "expired" if not ctx.get("aud") or p.get("aud") != ctx["aud"]: return "wrong_audience" if p.get("authorized") is not True: return "not_authorized" if ctx.get("request_hash"): if not any(i.get("request_hash") == ctx["request_hash"] for i in p.get("items", [])): return "binding_mismatch" if ctx.get("batch"): node = hashlib.sha256(b"\x00" + (parts[0] + "." + parts[1]).encode()).digest() for step in ctx["batch"]["proof"]: sib = d(step["h"]) node = hashlib.sha256(b"\x01" + (node + sib if step["side"] == "R" else sib + node)).digest() if e(node) != ctx["batch"]["root"]: return "merkle_mismatch" return "valid" if __name__ == "__main__": doc = json.load(open(sys.argv[1])) out = [] for v in doc["vectors"]: tok = doc["tokens"]["sample"] if v["token"] == "@sample" else v["token"] got = verify(tok, v["ctx"], doc["keys"]) want = "valid" if v["expect"]["ok"] else v["expect"]["reason"] out.append({"name": v["name"], "got": got, "want": want, "pass": got == want}) json.dump(out, open(sys.argv[2], "w")) bad = [o for o in out if not o["pass"]] print("python verifier:", len(out) - len(bad), "of", len(out), "pass") for o in bad: print(" FAIL", o)