Close the gaps between the documented contract (API-STANDARD, TENANCY, ENTITLEMENTS) and the implementation, and remove committed build artifacts. Security: - verify + process inbound webhooks (HMAC/handler verify, size limit, timestamp tolerance, idempotency via InboundEvent.external_id) - real 2FA login flow (pre-auth challenge; tokens only after verify/recovery) - wire HybridPermission into security/audit views; add API-key rotate and users/<id>/permissions|roles endpoints - tenant-scoped throttling on by default; webhook replay protection - verify MercadoPago webhook signatures - login brute-force guard, configurable password policy, real ALTCHA PoW Correctness: - apply verified billing webhooks idempotently (subscription/entitlement/ invoice/PaymentTransaction); scheduled payment lifecycle jobs - capture audit update diffs automatically; add audit retention purge - working notification retries, per-channel rate limits, log retention - pluggable virus scanner, upload-size limit, pipeline toggle - feature rollout %/environment targeting; settings-driven registrations - workflow guards (instance cap, route depth, self-assignment, clone on re-entry) - wire every previously-dead INFRASYNTH_* setting; drop truly dead ones Delivery: - README + CHANGELOG; CI format check + coverage gate - keep test media out of the tree; untrack .coverage, __pycache__, egg-info, docs/ and invoice artifacts
59 lines
2.4 KiB
Python
59 lines
2.4 KiB
Python
"""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)
|