#!/usr/bin/env python3
"""Repair Bench demo: broken vs fixed HMAC webhook verification.

A Stripe-style signed webhook. The receiver must verify the HMAC-SHA256
signature over the RAW request body, reject replays, and compare in
constant time. The broken version has three real-world bugs; the fixed
version passes 6/6.

Run: python3 hmac_demo.py
"""
import hmac
import hashlib
import json

SECRET = b"whsec_test_secret_123"
TOLERANCE_S = 300
NOW = 1_750_000_000


def sign(payload: bytes, ts: int, secret: bytes = SECRET) -> str:
    mac = hmac.new(secret, f"{ts}.".encode() + payload, hashlib.sha256).hexdigest()
    return f"t={ts},v1={mac}"


# ---------------------------------------------------------------- broken
def verify_broken(raw_body: bytes, header: str) -> bool:
    """Bug 1: verifies over re-serialized JSON, not the raw bytes.
    Bug 2: never checks the timestamp (replays accepted).
    Bug 3: == comparison instead of hmac.compare_digest (timing leak)."""
    try:
        parts = dict(p.split("=", 1) for p in header.split(","))
        sig, ts = parts["v1"], int(parts["t"])
    except Exception:
        return False
    canonical = json.dumps(json.loads(raw_body), separators=(",", ":")).encode()  # BUG 1
    expected = hmac.new(SECRET, f"{ts}.".encode() + canonical, hashlib.sha256).hexdigest()
    return expected == sig  # BUG 3 (and BUG 2: ts is never range-checked)


# ----------------------------------------------------------------- fixed
def verify_fixed(raw_body: bytes, header: str, now: int = NOW) -> bool:
    try:
        parts = dict(p.split("=", 1) for p in header.split(","))
        sig, ts = parts["v1"], int(parts["t"])
    except Exception:
        return False
    if abs(now - ts) > TOLERANCE_S:  # replay protection
        return False
    expected = hmac.new(SECRET, f"{ts}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig)  # constant-time


USES_COMPARE_DIGEST = {
    "broken": False,  # verify_broken uses ==
    "fixed": True,    # verify_fixed uses hmac.compare_digest
}


def run_checks(verify, label):
    raw = b'{"amount": 100, "id": "evt_1"}'  # note the whitespace: reserializing changes bytes
    tight = b'{"amount":100,"id":"evt_1"}'   # byte-identical after reserialization
    results = []

    # 1. valid signature over the exact bytes the sender signed
    results.append(("valid signature accepted",
                    verify(raw, sign(raw, NOW)) is True))
    # 2. one byte tampered in transit
    results.append(("tampered payload rejected",
                    verify(b'{"amount": 900, "id": "evt_1"}', sign(raw, NOW)) is False))
    # 3. signed with the wrong secret
    results.append(("wrong secret rejected",
                    verify(raw, sign(raw, NOW, secret=b"wrong")) is False))
    # 4. signature header missing entirely
    results.append(("missing header rejected",
                    verify(raw, "") is False))
    # 5. hour-old timestamp replayed with an otherwise valid signature.
    #    Uses the whitespace-free payload so bug 1 can't mask bug 2.
    results.append(("stale timestamp (replay) rejected",
                    verify(tight, sign(tight, NOW - 3600)) is False))
    # 6. static check: constant-time comparison (timing-attack resistance)
    results.append(("constant-time comparison",
                    USES_COMPARE_DIGEST[label] is True))

    passed = sum(1 for _, ok in results if ok)
    print(f"--- {label}: {passed}/6 ---")
    for name, ok in results:
        print(f"[{'PASS' if ok else 'FAIL'}] {name}")
    print()
    return passed


if __name__ == "__main__":
    b = run_checks(verify_broken, "broken")
    f = run_checks(verify_fixed, "fixed")
    print(f"broken: {b}/6   fixed: {f}/6")
