fix(securitate): hardening prod — headere, body-cap, non-root, backup

Findings security-review P1/P2 (2026-07-03):
- headere de securitate pe toate raspunsurile (nosniff, X-Frame-Options,
  Referrer-Policy, HSTS doar pe HTTPS) + teste
- body-cap global 10MB ca middleware ASGI pur (413 inainte de parserul
  multipart/JSON; verificarea per-endpoint ramane strat 2)
- imagine Docker non-root (uid 10001), port 8010 aliniat, loguri pe
  volumul /data
- fail-fast la boot cu rar_env=prod fara AUTOPASS_REQUIRE_API_KEY sau
  AUTOPASS_SESSION_SECRET
- compose: env-uri critice obligatorii (:?) ca api/worker sa nu diverga
  tacit; FORWARDED_ALLOW_IPS ca rate-limit-ul sa vada IP-ul real dupa
  Traefik
- signup fara PII in stdout: log_event in loc de print cu email (idem
  notify degradat)
- ratelimit: sterge cheile fara timestamp-uri valide (crestere monotona
  a memoriei pe IP-uri reale)
- backup criptat SQLite (backup online API, gpg AES256) + verificare
  restore + docs/backup.md

Suita completa verde: 1557 passed, 1 skipped (live).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Claude Agent
2026-07-06 12:46:49 +00:00
parent fa52468a80
commit 63b6cbc01d
19 changed files with 957 additions and 29 deletions

View File

@@ -15,6 +15,7 @@ from ..auth import create_api_key
from ..config import get_settings
from ..db import get_connection
from ..email import notify_signup
from ..observ import log_event
from ..users import count_admins, create_user, list_admin_emails, verify_password
from ..web.csrf import get_csrf_token, verify_csrf
from ..web.ratelimit import check_rate_limit
@@ -157,7 +158,7 @@ async def signup_post(
conn.close()
set_session(request, account_id, user_id)
print(f"SIGNUP cont={account_id} email={email}", flush=True)
log_event("signup", account_id=account_id, mesaj="cont nou creat")
# Notificare email admin (best-effort, nu blocheaza signup-ul)
try:

93
app/web/body_cap.py Normal file
View File

@@ -0,0 +1,93 @@
"""Middleware ASGI PUR: plafon global pe dimensiunea corpului cererii (P1-5).
`BaseHTTPMiddleware` nu poate refuza devreme: pentru a construi un `Request`
reconstituie intregul flux `receive()`, iar FastAPI parseaza deja COMPLET
multipart-ul (spooled pe disc peste prag) INAINTE sa ruleze endpointul — o
verificare per-endpoint (chiar si citire pe chunk-uri) nu repara cauza, doar
simptomul. Un middleware ASGI pur intercepteaza `receive` inaintea oricarui
parser: Content-Length peste limita -> 413 fara sa citeasca nimic din body;
altfel numara cumulativ octetii mesajelor `http.request` si intrerupe la
depasire. Cererile fara body (GET etc.) trec netaxate.
Verificarea per-endpoint existenta (`import_router.py`, `import_parse.MAX_BYTES`)
ramane NEATINSA ca strat 2 — acopera orice cale care ar ocoli acest middleware.
"""
from __future__ import annotations
import json
from starlette.datastructures import Headers
from .. import errors
from ..config import get_settings
class _BodyTooLarge(Exception):
pass
def _error_body() -> bytes:
payload = errors.eroare(
"CERERE_PREA_MARE",
cauza="Corpul cererii depaseste limita permisa.",
)
return json.dumps(payload, ensure_ascii=False).encode("utf-8")
class BodyCapMiddleware:
"""Limiteaza corpul cererii la `settings.max_request_bytes`, pe TOATE rutele.
Limita se citeste din `get_settings()` LA FIECARE CERERE (nu o data la
construirea middleware-ului): `app.add_middleware` ruleaza o singura data per
proces (modulul `app.main` e importat o singura data si in teste), deci un
`max_bytes` fixat in `__init__` ar ramane inghetat la valoarea de la primul
import si ar ignora `AUTOPASS_MAX_REQUEST_BYTES` schimbat ulterior (teste).
"""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
max_bytes = get_settings().max_request_bytes
content_length = Headers(scope=scope).get("content-length")
if content_length is not None:
try:
declared = int(content_length)
except ValueError:
declared = None
if declared is not None and declared > max_bytes:
await self._send_413(send)
return
total = 0
async def capped_receive():
nonlocal total
message = await receive()
if message["type"] == "http.request":
total += len(message.get("body") or b"")
if total > max_bytes:
raise _BodyTooLarge()
return message
try:
await self.app(scope, capped_receive, send)
except _BodyTooLarge:
await self._send_413(send)
@staticmethod
async def _send_413(send) -> None:
await send(
{
"type": "http.response.start",
"status": 413,
"headers": [(b"content-type", b"application/json")],
}
)
await send({"type": "http.response.body", "body": _error_body()})

View File

@@ -31,3 +31,23 @@ class RequestIDMiddleware(BaseHTTPMiddleware):
request_id_var.reset(token)
response.headers["X-Request-ID"] = request_id
return response
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""Headere de securitate pe TOATE raspunsurile (P1-4, hardening 2026-07-03).
HSTS se pune DOAR pe HTTPS: pe HTTP browserul l-ar ignora oricum, dar l-am
omis explicit ca sa nu sugereze o garantie falsa in dev/smoke pe HTTP simplu.
Nu suprascrie un header deja setat explicit de raspuns (setdefault).
"""
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "DENY")
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
if request.url.scheme == "https":
response.headers.setdefault(
"Strict-Transport-Security", "max-age=31536000; includeSubDomains"
)
return response

View File

@@ -7,10 +7,9 @@ Configurabil prin AUTOPASS_signup_rate_max / AUTOPASS_signup_rate_window_s (conf
from __future__ import annotations
import time
from collections import defaultdict
# ip/key -> lista de timestamps (time.monotonic) ale cererilor din fereastra activa
_hits: dict[str, list[float]] = defaultdict(list)
_hits: dict[str, list[float]] = {}
def check_rate_limit(key: str, max_hits: int, window_s: int) -> bool:
@@ -19,13 +18,21 @@ def check_rate_limit(key: str, max_hits: int, window_s: int) -> bool:
Curata timestamp-urile expirate la fiecare apel (O(n) per cheie, acceptabil
pentru trafic de signup). Thread-safety: GIL Python protejeaza list ops simple;
suficient pentru un singur proces uvicorn.
Cheile fara timestamp-uri valide sunt sterse din `_hits` (nu doar golite), altfel
dictionarul creste monoton pe viata procesului odata ce cheia devine IP-uri reale
de internet (F5). Foloseste `.get` in loc de acces direct pe dict pentru a nu
reintroduce o cheie doar prin citire.
"""
now = time.monotonic()
cutoff = now - window_s
timestamps = _hits[key]
# Sterge intrari expirate
_hits[key] = [t for t in timestamps if t > cutoff]
if len(_hits[key]) >= max_hits:
filtered = [t for t in _hits.get(key, []) if t > cutoff]
if len(filtered) >= max_hits:
if filtered:
_hits[key] = filtered
else:
_hits.pop(key, None)
return False
_hits[key].append(now)
filtered.append(now)
_hits[key] = filtered
return True