infrasynth-backend-kit/infrasynth/webhooks/signature.py
jcv-dev 551b42eab5 feat: production-hardening pass across the kit
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
2026-09-24 10:41:21 -05:00

35 lines
1.1 KiB
Python

import hmac
import time
def _algorithm() -> str:
from infrasynth.shared.settings_utils import get_setting
return str(get_setting("INFRASYNTH_WEBHOOKS", "SIGNATURE_ALGORITHM", "sha256"))
def sign_payload(secret: str, payload: str, timestamp: int | None = None) -> str:
ts = timestamp or int(time.time())
message = f"{ts}.{payload}".encode()
digest = hmac.new(secret.encode(), message, _algorithm()).hexdigest()
return f"t={ts},v1={digest}"
def verify_signature(secret: str, payload: str, signature_header: str, tolerance_seconds: int = 300) -> bool:
try:
parts = signature_header.split(",")
ts_part = parts[0]
sig_part = parts[1]
ts = int(ts_part.split("=")[1])
sig = sig_part.split("=")[1]
except (IndexError, ValueError, AttributeError):
return False
now = int(time.time())
if abs(now - ts) > tolerance_seconds:
return False
expected = sign_payload(secret, payload, timestamp=ts)
expected_sig = expected.split(",")[1].split("=")[1]
return hmac.compare_digest(sig, expected_sig)