SPB Git

Repository Public

webhook.py 6.3 KB 137 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr Identity7# File             : sdk/python/src/maclustr_identity/webhook.py8# Description      : Webhook signature verification.9# Module           : maclustr_identity10# Repository       : https://git.spboucher.ai/maclustr-identity11# Project Website  : https://identity.spboucher.ai12# Created          : 2026-12-0113# Last Modified    : 2026-12-0114#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Webhook signature verification.4243Header: ``MLID-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>]``.44Each v1 is HMAC-SHA256(secret, "<t>." + raw body). Several v1 values are sent while a secret is being rotated:45the payload is authentic as soon as one of them matches.46"""47from __future__ import annotations4849import hashlib50import hmac51import json52import time5354from .errors import SignatureVerificationError55from .types import Event5657DEFAULT_TOLERANCE = 30058SIGNATURE_HEADER = "MLID-Signature"596061def _to_bytes(payload: bytes | bytearray | memoryview | str) -> bytes:62    if isinstance(payload, str):63        return payload.encode("utf-8")64    if isinstance(payload, (bytes, bytearray, memoryview)):65        return bytes(payload)66    raise SignatureVerificationError("The webhook payload must be the raw request body (bytes or str), not a parsed object.",67                                     type="signature_error", code="payload_not_raw")686970class Webhook:71    """Namespace of static helpers: ``Webhook.construct_event(payload, sig_header, secret)``."""7273    DEFAULT_TOLERANCE = DEFAULT_TOLERANCE7475    @staticmethod76    def sign(payload: bytes | str, secret: str, timestamp: int | None = None) -> str:77        """Computes the MLID-Signature header value. Useful to build test fixtures."""78        ts = int(time.time()) if timestamp is None else int(timestamp)79        mac = hmac.new(secret.encode("utf-8"), f"{ts}.".encode() + _to_bytes(payload), hashlib.sha256).hexdigest()80        return f"t={ts},v1={mac}"8182    @staticmethod83    def parse_header(sig_header: str | None) -> tuple[int, list[str]] | None:84        """Returns (timestamp, signatures), or None when the header is malformed."""85        if not isinstance(sig_header, str) or not sig_header:86            return None87        ts: int | None = None88        sigs: list[str] = []89        for part in sig_header.split(","):90            key, sep, value = part.partition("=")91            key, value = key.strip(), value.strip()92            if not sep:93                continue94            if key == "t" and value.isascii() and value.isdigit():95                ts = int(value)96            elif key == "v1" and value:97                sigs.append(value)98        if ts is None or not sigs:99            return None100        return ts, sigs101102    @staticmethod103    def verify_signature(payload: bytes | str, sig_header: str | None, secret: str, tolerance: int = DEFAULT_TOLERANCE) -> None:104        """Raises SignatureVerificationError unless the signature is valid and recent."""105        if not secret:106            raise SignatureVerificationError("No webhook signing secret was provided.", type="signature_error", code="secret_missing")107        parsed = Webhook.parse_header(sig_header)108        if parsed is None:109            raise SignatureVerificationError(f"Missing or malformed {SIGNATURE_HEADER} header.", type="signature_error", code="signature_header_invalid")110        ts, sigs = parsed111        body = _to_bytes(payload)112        expected = hmac.new(secret.encode("utf-8"), f"{ts}.".encode() + body, hashlib.sha256).hexdigest().encode()113        match = False114        for candidate in sigs:      # every candidate is compared, in constant time, without stopping at the first match115            if hmac.compare_digest(expected, candidate.encode("utf-8", "replace")):116                match = True117        if not match:118            raise SignatureVerificationError("No signature matches the payload. Check that you pass the raw body and the secret of this endpoint.",119                                             type="signature_error", code="signature_mismatch")120        if abs(time.time() - ts) > tolerance:121            raise SignatureVerificationError("The signature timestamp is outside the tolerance window.", type="signature_error", code="signature_expired")122123    @staticmethod124    def construct_event(payload: bytes | str, sig_header: str | None, secret: str, tolerance: int = DEFAULT_TOLERANCE) -> Event:125        """Verifies the signature of a delivery then parses it.126127        Always pass the raw body exactly as received: re-serialized JSON does not verify.128        """129        Webhook.verify_signature(payload, sig_header, secret, tolerance)130        try:131            data = json.loads(_to_bytes(payload).decode("utf-8"))132        except (ValueError, UnicodeDecodeError) as e:133            raise SignatureVerificationError("The webhook payload is not valid JSON.", type="signature_error", code="payload_invalid") from e134        if not isinstance(data, dict) or data.get("object") != "event" or "id" not in data or "type" not in data:135            raise SignatureVerificationError("The webhook payload is not an event object.", type="signature_error", code="payload_invalid")136        return Event.from_dict(data)137
Files main
Menu

Theme