infrasynth-backend-kit/infrasynth/security/throttling.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

82 lines
3.2 KiB
Python

"""Login brute-force protection (``INFRASYNTH_SECURITY``).
Two layers, both cache-backed and tenant-prefix-free by necessity (they run
before a tenant is known, so they key on IP + credential, never on tenant data):
* a short per-credential/IP rate limit (``LOGIN_RATE_LIMIT``, e.g. ``10/m``);
* an IP blacklist that trips after ``IP_BLACKLIST_THRESHOLD`` failures inside
``IP_BLACKLIST_WINDOW_MINUTES`` and blocks the IP for the same window.
Failures are recorded on any rejected login and cleared on success. A blacklisted
IP gets ``429 RATE_LIMIT_EXCEEDED`` with a ``Retry-After`` hint.
"""
from __future__ import annotations
import time
from django.core.cache import cache
from infrasynth.shared.exceptions import RateLimitError
from infrasynth.shared.settings_utils import get_setting
__all__ = ["LoginAttemptGuard"]
def _parse_rate(rate: str) -> tuple[int, int]:
"""Parses ``"10/m"`` into ``(count, seconds)``. Defaults to 10/minute."""
try:
count_part, period = rate.split("/", 1)
count = int(count_part)
except (ValueError, AttributeError):
return 10, 60
seconds = {"s": 1, "m": 60, "h": 3600, "d": 86400}.get(period.strip().lower(), 60)
return count, seconds
class LoginAttemptGuard:
def __init__(self) -> None:
self.rate_count, self.rate_window = _parse_rate(get_setting("INFRASYNTH_SECURITY", "LOGIN_RATE_LIMIT", "10/m"))
self.blacklist_threshold = int(get_setting("INFRASYNTH_SECURITY", "IP_BLACKLIST_THRESHOLD", 100))
self.blacklist_window = int(get_setting("INFRASYNTH_SECURITY", "IP_BLACKLIST_WINDOW_MINUTES", 15)) * 60
@staticmethod
def _ip(request) -> str:
return request.META.get("REMOTE_ADDR", "") or "unknown"
def _blacklist_key(self, ip: str) -> str:
return f"login:blacklist:{ip}"
def _failure_key(self, ip: str, credential: str) -> str:
return f"login:fail:{ip}:{credential}"
def check(self, request, credential: str) -> None:
"""Raises :class:`RateLimitError` when the attempt must be rejected."""
ip = self._ip(request)
if cache.get(self._blacklist_key(ip)):
raise RateLimitError(
"Too many failed login attempts from this address.",
code="RATE_LIMIT_EXCEEDED",
details=[{"field": "ip", "issue": "blacklisted"}],
)
count = cache.get(self._failure_key(ip, credential), 0)
if count >= self.rate_count:
raise RateLimitError(
"Too many failed login attempts.",
code="RATE_LIMIT_EXCEEDED",
details=[{"field": "credential", "issue": "rate_limited"}],
)
def record_failure(self, request, credential: str) -> None:
ip = self._ip(request)
key = self._failure_key(ip, credential)
try:
count = cache.incr(key)
except ValueError:
cache.set(key, 1, self.rate_window)
count = 1
if count >= self.blacklist_threshold:
cache.set(self._blacklist_key(ip), time.time(), self.blacklist_window)
def clear(self, request, credential: str) -> None:
cache.delete(self._failure_key(self._ip(request), credential))