"""Prepared Board webhook signature verifier (prepared-board.webhook-signature.v1).

Python 3.8+, standard library only.

    from verify_webhook import verify_webhook
    result = verify_webhook(
        payload=request.body,                       # bytes (or str): the body exactly as received
        header=request.headers.get("Prepared-Signature"),
        secrets=[os.environ["PREPARED_WEBHOOK_SECRET"]],
    )
    if not result["ok"]:
        return 400, result["error"]

Run the published test vectors:

    python3 verify_webhook.py --vectors signature-vectors.json

Docs: https://preparedboard.com/standard#webhooks
"""
import hashlib
import hmac
import json
import re
import sys
import time

SIGNATURE_HEADER = "Prepared-Signature"
DEFAULT_TOLERANCE_SECONDS = 300

_T = re.compile(r"[0-9]{1,15}")
_V1 = re.compile(r"[0-9a-f]{64}")


def parse_signature_header(header):
    """Strict parse. Returns (timestamp, [v1, ...]) or None."""
    if not isinstance(header, str) or not header or len(header) > 4096:
        return None
    timestamp = None
    v1 = []
    for item in header.split(","):
        i = item.find("=")
        if i <= 0:
            return None
        k = item[:i].strip(" \t")
        v = item[i + 1:].strip(" \t")
        if k == "t":
            if timestamp is not None or not _T.fullmatch(v):
                return None
            timestamp = int(v)
        elif k == "v1":
            if not _V1.fullmatch(v):
                return None
            v1.append(v)
    if timestamp is None:
        return None
    return timestamp, v1


def verify_webhook(payload, header, secrets, now=None, tolerance_seconds=DEFAULT_TOLERANCE_SECONDS):
    """Returns {"ok": True, "timestamp": t} or {"ok": False, "error": code}.

    Codes, checked in this order: no_secrets, malformed_header, no_signatures,
    timestamp_outside_tolerance, signature_mismatch.
    """
    if not secrets:
        return {"ok": False, "error": "no_secrets"}
    parsed = parse_signature_header(header)
    if parsed is None:
        return {"ok": False, "error": "malformed_header"}
    timestamp, v1 = parsed
    if not v1:
        return {"ok": False, "error": "no_signatures"}
    now = int(time.time()) if now is None else now
    if abs(now - timestamp) > tolerance_seconds:
        return {"ok": False, "error": "timestamp_outside_tolerance"}
    body = payload.encode("utf-8") if isinstance(payload, str) else bytes(payload)
    message = ("%d." % timestamp).encode("utf-8") + body
    match = False
    for secret in secrets:
        expected = hmac.new(secret.encode("utf-8"), message, hashlib.sha256).hexdigest()
        for got in v1:
            if hmac.compare_digest(expected, got):
                match = True
    if match:
        return {"ok": True, "timestamp": timestamp}
    return {"ok": False, "error": "signature_mismatch"}


def run_vectors(doc):
    passed, failed = 0, []
    for c in doc["cases"]:
        got = verify_webhook(c["payload"], c["header"], c["secrets"], now=c["now"], tolerance_seconds=doc["toleranceSeconds"])
        exp = c["expected"]
        if exp["valid"]:
            ok = got["ok"] and got["timestamp"] == exp["timestamp"]
        else:
            ok = (not got["ok"]) and got["error"] == exp["error"]
        if ok:
            passed += 1
        else:
            failed.append((c["name"], exp, got))
    return passed, failed


if __name__ == "__main__":
    if len(sys.argv) != 3 or sys.argv[1] != "--vectors":
        print("usage: python3 verify_webhook.py --vectors signature-vectors.json", file=sys.stderr)
        sys.exit(2)
    with open(sys.argv[2], encoding="utf-8") as f:
        doc = json.load(f)
    passed, failed = run_vectors(doc)
    for name, exp, got in failed:
        print("FAIL %s: expected %s, got %s" % (name, json.dumps(exp), json.dumps(got)))
    print("%d/%d vectors passed" % (passed, len(doc["cases"])))
    sys.exit(1 if failed else 0)
