# apidata.one: verifying a webhook's signature in Python (3.7 or later, standard library only). # The page that explains it: docs/concepts/webhooks.md. Test vectors: vectors.json. # # Use it: from verify import verify_webhook # Try it: echo '{"secret":"…","header":"…","body":"…","now":1794322803}' | python verify.py # prints true or false. import hashlib import hmac import time # docs:begin def verify_webhook(secret, header, body, now=None): """True when `header` is a valid ApiData-Signature for `body` under `secret`. secret the endpoint's secret, exactly as it was shown when the endpoint was created header the value of the ApiData-Signature header body the request body exactly as received: bytes, before any JSON parsing now the current time in Unix seconds (left out: the clock) """ if not isinstance(secret, str) or secret == "" or not isinstance(header, str): return False if isinstance(body, str): body = body.encode("utf-8") if now is None: now = int(time.time()) timestamp = None signatures = [] for part in header.split(","): name, found, value = part.partition("=") if not found: continue if name == "t": timestamp = value elif name == "v1": signatures.append(value) if timestamp is None or not (timestamp.isascii() and timestamp.isdigit()): return False if len(timestamp) > 15: return False # Refuse a timestamp more than five minutes from now, in either direction. if abs(now - int(timestamp)) > 300: return False signed = timestamp.encode("ascii") + b"." + body expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest() valid = False for signature in signatures: # Constant time: never compare signatures with == . if hmac.compare_digest(expected.encode("ascii"), signature.encode("utf-8")): valid = True return valid # docs:end # Command line: {"secret","header","body","now"} as JSON on standard input; prints true or # false. `now` is Unix seconds (a number or digits) or an ISO-8601 time; left out, the clock. if __name__ == "__main__": import json import sys from datetime import datetime answer = False try: given = json.loads(sys.stdin.buffer.read().decode("utf-8")) now = given.get("now") if isinstance(now, bool): raise ValueError("now") if isinstance(now, (int, float)): now = int(now) elif isinstance(now, str) and now.isascii() and now.isdigit(): now = int(now) elif isinstance(now, str): now = int(datetime.fromisoformat(now.replace("Z", "+00:00")).timestamp()) elif now is not None: raise ValueError("now") if isinstance(given.get("body"), str): answer = verify_webhook( given.get("secret"), given.get("header"), given["body"].encode("utf-8"), now ) except Exception: answer = False sys.stdout.write("true\n" if answer else "false\n")