Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER7# File : sdk/python/spider_sdk/webhooks.py8# Module : Sdk9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@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 : ISC33#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"""Verification of SPIDER webhook deliveries.4243SPIDER signs every delivery with HMAC-SHA256 over ``<X-Spider-Timestamp>.<X-Spider-Delivery>.<raw body>``44and sends ``X-Spider-Signature: v1=<hex>``. The secret is per tenant: ``GET /v1/webhook-secret``.45"""46from __future__ import annotations4748import hashlib49import hmac50import json51import time52from collections.abc import Mapping53from typing import Any5455from .errors import WebhookVerificationError5657DEFAULT_TOLERANCE_SECONDS = 300585960def compute_signature(secret: str | bytes, timestamp: str, delivery_id: str, raw_body: bytes) -> str:61 """Hex HMAC-SHA256 of ``timestamp.delivery_id.raw_body`` (the value after ``v1=``)."""62 key = secret.encode() if isinstance(secret, str) else secret63 return hmac.new(key, timestamp.encode() + b"." + delivery_id.encode() + b"." + raw_body,64 hashlib.sha256).hexdigest()656667def _header(headers: Mapping[str, Any], name: str) -> str:68 for k, v in headers.items():69 if (k.decode("latin-1") if isinstance(k, bytes) else str(k)).lower() == name:70 return (v.decode("latin-1") if isinstance(v, bytes) else str(v)).strip()71 return ""727374def verify_webhook(secret: str | bytes, headers: Mapping[str, Any], raw_body: bytes | str,75 tolerance_seconds: float = DEFAULT_TOLERANCE_SECONDS, *, now: float | None = None) -> str:76 """Check the signature and the age of a delivery; return its delivery id.7778 Raises :class:`WebhookVerificationError` (``reason`` in ``missing_header``, ``bad_timestamp``,79 ``timestamp_out_of_tolerance``, ``unsupported_version``, ``bad_signature``). Pass the body exactly as80 received (bytes), not a re-serialised JSON document. The comparison is constant-time. The timestamp81 check rejects replays older than ``tolerance_seconds``; to reject replays inside the window, remember82 the returned delivery id and refuse one you have already processed.83 """84 body = raw_body.encode() if isinstance(raw_body, str) else bytes(raw_body)85 ts, delivery, sig = (_header(headers, n) for n in ("x-spider-timestamp", "x-spider-delivery",86 "x-spider-signature"))87 if not (ts and delivery and sig):88 raise WebhookVerificationError("missing_header", "X-Spider-Timestamp, X-Spider-Delivery and "89 "X-Spider-Signature are required")90 if not (ts.isascii() and ts.isdigit()):91 raise WebhookVerificationError("bad_timestamp", "X-Spider-Timestamp is not a Unix timestamp")92 if abs((time.time() if now is None else now) - int(ts)) > tolerance_seconds:93 raise WebhookVerificationError("timestamp_out_of_tolerance", "delivery timestamp is outside the tolerance")94 candidates = [p.strip()[3:] for p in sig.split(",") if p.strip().startswith("v1=")]95 if not candidates:96 raise WebhookVerificationError("unsupported_version", "no v1 signature in X-Spider-Signature")97 expected = compute_signature(secret, ts, delivery, body).encode()98 ok = False99 for c in candidates: # no early exit: every candidate is compared in constant time100 ok |= hmac.compare_digest(expected, c.lower().encode("utf-8", "replace"))101 if not ok:102 raise WebhookVerificationError("bad_signature", "signature does not match")103 return delivery104105106def parse_webhook(secret: str | bytes, headers: Mapping[str, Any], raw_body: bytes | str,107 tolerance_seconds: float = DEFAULT_TOLERANCE_SECONDS, *, now: float | None = None) -> dict[str, Any]:108 """Verify a delivery, then decode its JSON payload (``event``, ``delivery_id``, …)."""109 verify_webhook(secret, headers, raw_body, tolerance_seconds, now=now)110 payload = json.loads(raw_body)111 if not isinstance(payload, dict):112 raise WebhookVerificationError("bad_payload", "webhook payload is not a JSON object")113 return payload114