#!/usr/bin/env python3 """SendPier webhooks — a receiver that verifies the signature. Requirements: Python 3.9 or newer. Standard library only, no packages -- so no Flask either; the interesting part is the raw body, and that is what a framework tends to take away from you. Try it out: export SENDPIER_WEBHOOK_SECRET='whsec_...' # from the webhook page python3 webhook_receiver.py In production this listens behind your own https address; we refuse a plain http address when you enter it. USING FLASK INSTEAD? Read the raw body with `request.get_data(as_text=True)` and verify over that, not over `request.json`. A JSON parser hands you an object, and re-serialising that object shifts a space or a key order -- after which the signature no longer matches. THE ORDER MATTERS 1. read the RAW body; 2. verify the signature -- if it does not match: 400, and process nothing; 3. check whether you already know this id; if so: 200 and stop; 4. put the event on your own queue; 5. answer 200; 6. process it afterwards, outside the request. Step 5 before step 6 is the whole point: the timeout is ten seconds, and every timeout earns you the same event again. """ import hashlib import hmac import json import os import sys import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer # How far the timestamp may be off, in seconds. TOLERANCE_SECONDS = 300 PORT = int(os.environ.get("PORT", "8080")) def signature_is_valid(secret, header, body, tolerance=TOLERANCE_SECONDS): """Is this request really ours? The header reads `t=,v1=`. The hex is HMAC-SHA256 over the literal text ".", keyed with the secret of that endpoint. For 24 hours after you renew the secret the header carries TWO signatures: `t=,v1=,v1=`. Collect every `v1` and accept the request if any one of them matches. This is what lets you switch to the new secret at your own pace. """ timestamp_text = None candidates = [] for part in header.split(","): if "=" not in part: continue key, value = part.split("=", 1) key = key.strip() if key == "t": timestamp_text = value elif key == "v1": candidates.append(value) if timestamp_text is None or not candidates: return False try: timestamp = int(timestamp_text) except ValueError: return False # Without the age check an intercepted request stays replayable for as long # as the secret lives: the signature itself never expires. if abs(time.time() - timestamp) > tolerance: return False expected = hmac.new( secret.encode("utf-8"), "{}.{}".format(timestamp_text, body).encode("utf-8"), hashlib.sha256, ).hexdigest() # Constant time, and for every value: a plain == leaks, through its own # running time, how many leading characters of a guess were right. Do not # stop at the first match, so the running time does not tell which of the # two signatures was the right one. valid = False for candidate in candidates: if hmac.compare_digest(expected.encode(), candidate.encode()): valid = True return valid class WebhookHandler(BaseHTTPRequestHandler): """One SendPier delivery.""" # The default logger writes a line per request to stderr; keep it quiet so # our own lines stand out. def log_message(self, format, *args): # noqa: A002 - signature is fixed pass def do_POST(self): # noqa: N802 - the base class dictates the name secret = os.environ["SENDPIER_WEBHOOK_SECRET"] length = int(self.headers.get("Content-Length") or 0) # The raw bytes we sent, read before anything turns them into an object. body = self.rfile.read(length).decode("utf-8", "replace") header = self.headers.get("X-SendPier-Signature", "") if not signature_is_valid(secret, header, body): print("refused a webhook delivery with an invalid signature", file=sys.stderr) self.send_response(400) self.end_headers() return try: event = json.loads(body) except ValueError: self.send_response(400) self.end_headers() return if not isinstance(event, dict) or "id" not in event or "event" not in event: self.send_response(400) self.end_headers() return # Deduplicate on `id` (the same number as the X-SendPier-Delivery # header) and order on `occurred_at`. We queue every event once, but a # delivery that answers too late gets it again, and a retry from # yesterday can arrive after a fresh event. Process an event you already # know silently and answer 200: # # if store.has_event(event["id"]): # self.send_response(200); self.end_headers(); return # store.queue(event) self.send_response(200) self.end_headers() # Everything below runs after the answer is on its way. In a real # application this is where you hand the event to your queue worker. data = event.get("data") or {} print( "webhook {}: {} for {}".format( event["id"], event["event"], data.get("to") or data.get("domain") or "unknown" ), file=sys.stderr, ) def main(): if not os.environ.get("SENDPIER_WEBHOOK_SECRET"): sys.exit("SENDPIER_WEBHOOK_SECRET is not set") print("listening for SendPier webhooks on port {}".format(PORT), file=sys.stderr) ThreadingHTTPServer(("127.0.0.1", PORT), WebhookHandler).serve_forever() if __name__ == "__main__": main()