infrasynth-backend-kit/infrasynth/api/middleware.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

40 lines
1.3 KiB
Python

"""Request correlation middleware (``API-STANDARD.md`` §7)."""
from __future__ import annotations
import uuid
from collections.abc import Callable
from django.http import HttpRequest, HttpResponse
__all__ = ["RequestIdMiddleware", "RateLimitHeadersMiddleware"]
_HEADER = "X-Request-Id"
class RequestIdMiddleware:
"""Ensures every request has an id, echoed in the response header and meta."""
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
self.get_response = get_response
def __call__(self, request: HttpRequest) -> HttpResponse:
request_id = request.headers.get(_HEADER) or f"req_{uuid.uuid4().hex[:20]}"
request.request_id = request_id # type: ignore[attr-defined]
response = self.get_response(request)
response[_HEADER] = request_id
return response
class RateLimitHeadersMiddleware:
"""Adds ``X-RateLimit-*`` headers whenever a throttle recorded state."""
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None:
self.get_response = get_response
def __call__(self, request: HttpRequest) -> HttpResponse:
from .throttling import apply_rate_limit_headers
response = self.get_response(request)
apply_rate_limit_headers(response, request)
return response