SPB Git

Repository Public

_webhooks.py 2.8 KB 62 lines python

1"""Webhook signature: ``SPMail-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, t + "." + raw body)>``."""2from __future__ import annotations34import hashlib5import hmac6import json7import re8import time9from typing import Any, Dict, Optional, Union1011from ._errors import SignatureVerificationError1213_HEADER = re.compile(r"t=(\d{1,12}),v1=([0-9a-f]{64})")14Payload = Union[str, bytes, bytearray, memoryview]151617def _raw(payload: Payload) -> bytes:18    return payload.encode("utf-8") if isinstance(payload, str) else bytes(payload)192021def _check(payload: Payload, header: Optional[str], secret: str, tolerance: float, now: Optional[float]) -> Optional[str]:22    m = _HEADER.fullmatch(header or "")23    if not m:24        return "missing or malformed SPMail-Signature header"25    if not secret:26        return "no webhook secret given"27    if abs((time.time() if now is None else now) - int(m.group(1))) > tolerance:28        return "timestamp outside the tolerance window"29    expected = hmac.new(secret.encode("utf-8"), m.group(1).encode("ascii") + b"." + _raw(payload), hashlib.sha256).hexdigest()30    return None if hmac.compare_digest(expected, m.group(2)) else "signature mismatch"313233def verify_webhook_signature(payload: Payload, header: Optional[str], secret: str, *, tolerance: float = 300,34                             now: Optional[float] = None) -> bool:35    """True when the signature matches the RAW request body and its timestamp is inside the replay window.3637    ``payload`` must be the body exactly as received (bytes or str), never a re-serialised JSON. Never raises on a38    bad signature. The comparison is constant-time.39    """40    return _check(payload, header, secret, tolerance, now) is None414243def construct_event(payload: Payload, header: Optional[str], secret: str, *, tolerance: float = 300,44                    now: Optional[float] = None) -> Dict[str, Any]:45    """Verifies the signature, then parses the event. Raises SignatureVerificationError when it does not verify."""46    reason = _check(payload, header, secret, tolerance, now)47    if reason:48        raise SignatureVerificationError(f"Webhook signature verification failed: {reason}")49    try:50        event = json.loads(_raw(payload).decode("utf-8"))51    except ValueError as exc:52        raise SignatureVerificationError("Webhook payload is not valid JSON") from exc53    if not isinstance(event, dict):54        raise SignatureVerificationError("Webhook payload is not a JSON object")55    return event565758def sign_webhook_payload(payload: Payload, secret: str, *, timestamp: Optional[float] = None) -> str:59    """Builds a valid header value (for tests of your own receiver)."""60    t = str(int(time.time() if timestamp is None else timestamp))61    return f"t={t},v1=" + hmac.new(secret.encode("utf-8"), t.encode("ascii") + b"." + _raw(payload), hashlib.sha256).hexdigest()62
Files main
Menu

Theme