# Verifying a Baatzo status webhook (API v1). Python 3.9 or later, no packages. # # Baatzo sends Baatzo-Signature: t=1801123456,v1=[,v1=] # where each v1 is the HMAC-SHA256 of "." keyed with your signing secret (whsec_...). # During a secret rotation the header carries two v1 values for 24 hours; accept the request if any matches. # Check the RAW body, byte for byte, before parsing it as JSON. import hashlib import hmac import re import time TOLERANCE_SECONDS = 5 * 60 def verify_baatzo_signature(raw_body, header, secret, now=None): """True when header is a valid signature of raw_body (bytes), made at most 5 minutes from now.""" if not isinstance(header, str) or not secret: return False t, signatures = None, [] for part in header.split(","): k, _, v = (x.strip() for x in part.partition("=")) if k == "t" and re.fullmatch(r"[0-9]{1,12}", v): t = int(v) if k == "v1" and re.fullmatch(r"[0-9a-f]{64}", v): signatures.append(v) if t is None or not signatures: return False if abs(int(time.time() if now is None else now) - t) > TOLERANCE_SECONDS: return False expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest() return any(hmac.compare_digest(s, expected) for s in signatures) # Flask example: request.get_data() is the raw body. # # @app.post("/baatzo-webhook") # def baatzo_webhook(): # raw = request.get_data() # if not verify_baatzo_signature(raw, request.headers.get("Baatzo-Signature"), os.environ["BAATZO_WEBHOOK_SECRET"]): # return "", 400 # event = json.loads(raw) # # Drop a repeat by event["id"]; ignore a status older than one you already have (status_rank). # return "", 200 # answer within 5 seconds, then do the work