"""Inbound webhook handler contract + the built-in HMAC handler. An *inbound handler* is the extension point an app uses to interpret a provider's payload (GitHub, Jira, …). Verification is a hard gate: by default every handler uses the shared HMAC scheme (``infrasynth.webhooks.signature``) and a provider that ships a different signature scheme overrides :meth:`BaseInboundHandler.verify`. """ from __future__ import annotations from abc import ABC, abstractmethod from typing import Any from ..signature import verify_signature class BaseInboundHandler(ABC): """Base class for inbound webhook handlers. ``verify`` defaults to the shared HMAC scheme over the raw request body; a provider with its own signature scheme (Stripe, GitHub, …) overrides it. ``process`` receives the parsed payload after verification and returns a JSON-serializable result that is stored on the event. """ def verify(self, payload: dict, headers: dict, secret: str, *, raw_body: bytes | None = None) -> bool: """Return ``True`` when the request is authentic. The default implementation validates the shared HMAC signature. The raw body is preferred over a re-serialized payload so the digest matches byte-for-byte what the sender signed. """ from infrasynth.shared.settings_utils import get_setting header_name = get_setting("INFRASYNTH_WEBHOOKS", "SIGNATURE_HEADER", "X-Webhook-Signature") tolerance = int(get_setting("INFRASYNTH_WEBHOOKS", "INBOUND_SIGNATURE_TOLERANCE_SECONDS", 300)) signature = headers.get(header_name) or headers.get(header_name.lower()) or headers.get("X-Signature") or "" if not signature: return False body = raw_body.decode("utf-8", errors="replace") if raw_body is not None else _canonical(payload) return verify_signature(secret, body, signature, tolerance_seconds=tolerance) @abstractmethod def process(self, event_type: str, payload: dict) -> dict: """Handle a verified event and return a JSON-serializable result.""" class HMACInboundHandler(BaseInboundHandler): """Default handler: verify the shared HMAC and accept the event as-is.""" def process(self, event_type: str, payload: dict) -> dict[str, Any]: return {"received": True, "event_type": event_type} def _canonical(payload: Any) -> str: import json return json.dumps(payload, separators=(",", ":"), default=str, sort_keys=True)