"""Borrou Partner API: webhook signature verification, standard library only. v0.1 DRAFT. Every delivery carries ``Borrou-Signature: t=,v1=``, the MAC of ``.`` keyed with the subscription's whole signing secret (``whsec_...``, from ``GET /v1/webhooks/subscriptions/{id}/signing-secret``). Borrou signs with one secret today, but a header may carry more than one v1 entry (as it would while a signing secret rotates): accept the delivery if any one matches. Verify the raw bytes exactly as received, before any JSON parsing; reject a timestamp more than five minutes from your clock; then de-duplicate on the event's ``id`` (also ``Borrou-Event-Id``). """ from __future__ import annotations import hashlib import hmac import re import time from typing import Optional, Tuple, Union SIGNATURE_HEADER = "Borrou-Signature" DEFAULT_TOLERANCE_SECONDS = 300 _TIMESTAMP = re.compile(r"[0-9]{1,12}") _SIGNATURE = re.compile(r"[0-9a-f]{64}") def verify_borrou_signature( header: Optional[str], raw_body: Union[bytes, str], secret: str, tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS, now_seconds: Optional[int] = None, ) -> Tuple[bool, str]: """Returns (True, "ok"), or (False, "missing" | "malformed" | "stale" | "mismatch").""" if not header: return False, "missing" timestamp: Optional[int] = None candidates = [] for part in header.split(","): pieces = part.strip().split("=") if not pieces[0] or len(pieces) != 2: return False, "malformed" key, value = pieces if key == "t": timestamp = int(value) if _TIMESTAMP.fullmatch(value) else None elif key == "v1" and _SIGNATURE.fullmatch(value): candidates.append(value) if timestamp is None or not candidates: return False, "malformed" now = int(time.time()) if now_seconds is None else now_seconds if abs(now - timestamp) > tolerance_seconds: return False, "stale" body = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body expected = hmac.new(secret.encode("utf-8"), f"{timestamp}.".encode("ascii") + body, hashlib.sha256).hexdigest() # Constant time, and every candidate compared, so the answer's timing says nothing about which. matched = False for candidate in candidates: matched = hmac.compare_digest(expected, candidate) or matched return (True, "ok") if matched else (False, "mismatch") # Flask, reading the body raw: # # @app.post("/borrou/webhooks") # def borrou_webhook(): # ok, reason = verify_borrou_signature(request.headers.get(SIGNATURE_HEADER), request.get_data(), SECRET) # if not ok: # return "", 400 # event = json.loads(request.get_data()) # # Answer quickly; process asynchronously, de-duplicating on event["id"]. # return "", 200