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:
@@ -139,6 +139,12 @@ class Settings(BaseSettings):
|
||||
# conftest il dezactiveaza global, testele care-l vor il pornesc punctual.
|
||||
seed_operatii_enabled: bool = True
|
||||
|
||||
# --- Limita globala corp cerere (P1-4/P1-5, hardening 2026-07-03) ---
|
||||
# Plafon aplicat de un middleware ASGI pur (app/web/body_cap.py) pe TOATE rutele,
|
||||
# INAINTE ca FastAPI sa parseze body-ul (multipart e spooled pe disc altfel).
|
||||
# Verificarea per-endpoint existenta (import_parse.MAX_BYTES, 5MB) ramane strat 2.
|
||||
max_request_bytes: int = 10 * 1024 * 1024 # 10 MB
|
||||
|
||||
@property
|
||||
def rar_base_url(self) -> str:
|
||||
return self.rar_base_url_prod if self.rar_env == "prod" else self.rar_base_url_test
|
||||
@@ -149,6 +155,32 @@ def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
|
||||
def validate_prod_invariants(settings: Settings) -> None:
|
||||
"""Fail-fast la startup: refuza boot-ul in productie cand lipsesc invariantele
|
||||
de securitate obligatorii, in loc sa lase aplicatia sa porneasca intr-o
|
||||
configuratie nesigura descoperita abia dupa deploy (mirror `crypto.validate_creds_key`).
|
||||
|
||||
Conditionat STRICT pe `rar_env=="prod"` — altfel ar opri suita de teste, care
|
||||
ruleaza implicit cu `rar_env="test"` si fara `session_secret`/`require_api_key`.
|
||||
"""
|
||||
if settings.rar_env != "prod":
|
||||
return
|
||||
if not settings.require_api_key:
|
||||
raise RuntimeError(
|
||||
"AUTOPASS_RAR_ENV=prod dar AUTOPASS_REQUIRE_API_KEY nu e activat: in "
|
||||
"productie cheia API e obligatorie pe /v1/*, altfel orice cerere "
|
||||
"neautentificata ajunge pe contul implicit id=1. Seteaza "
|
||||
"AUTOPASS_REQUIRE_API_KEY=true."
|
||||
)
|
||||
if not settings.session_secret:
|
||||
raise RuntimeError(
|
||||
"AUTOPASS_RAR_ENV=prod dar AUTOPASS_SESSION_SECRET nu este setat: fara el, "
|
||||
"secretul de sesiune e efemer per restart si toti userii sunt delogati la "
|
||||
"fiecare redeploy. Genereaza unul persistent cu:\n"
|
||||
" python3 -c \"import secrets; print(secrets.token_hex(32))\""
|
||||
)
|
||||
|
||||
|
||||
def load_test_credentials(settings_xml: Path | None = None) -> dict | None:
|
||||
"""Citeste credentialele <test> din settings.xml (dev local / probe test).
|
||||
|
||||
|
||||
10
app/email.py
10
app/email.py
@@ -11,6 +11,7 @@ import textwrap
|
||||
from email.message import EmailMessage
|
||||
|
||||
from .config import get_settings
|
||||
from .observ import log_event
|
||||
|
||||
|
||||
def notify_signup(admin_emails: list[str], account_id: int, email: str) -> None:
|
||||
@@ -23,10 +24,11 @@ def notify_signup(admin_emails: list[str], account_id: int, email: str) -> None:
|
||||
settings = get_settings()
|
||||
|
||||
if not settings.smtp_host or not admin_emails:
|
||||
print(
|
||||
f"SIGNUP-NOTIFY degradat (fara SMTP) cont={account_id} "
|
||||
f"email={email} admins={len(admin_emails)}",
|
||||
flush=True,
|
||||
log_event(
|
||||
"signup_notify_degradat",
|
||||
account_id=account_id,
|
||||
mesaj="fara SMTP configurat",
|
||||
context={"admins": len(admin_emails)},
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
14
app/main.py
14
app/main.py
@@ -25,12 +25,13 @@ from . import errors
|
||||
from .api.v1.import_router import router as import_v1_router
|
||||
from .api.v1.integrare_router import router as integrare_v1_router
|
||||
from .api.v1.router import router as api_v1_router
|
||||
from .config import get_settings
|
||||
from .config import get_settings, validate_prod_invariants
|
||||
from .crypto import validate_creds_key
|
||||
from .db import get_connection, init_db, queue_depth, read_heartbeat
|
||||
from .observ import log_event, request_id_var
|
||||
from .security import install_log_redaction, scrub_text
|
||||
from .web.middleware import RequestIDMiddleware
|
||||
from .web.body_cap import BodyCapMiddleware
|
||||
from .web.middleware import RequestIDMiddleware, SecurityHeadersMiddleware
|
||||
from .web.routes import router as web_router
|
||||
from .web.auth_routes import router as auth_router
|
||||
from .web.admin_routes import router as admin_router
|
||||
@@ -44,6 +45,9 @@ async def lifespan(app: FastAPI):
|
||||
# Fail-fast: o cheie Fernet setata dar invalida opreste pornirea cu mesaj clar,
|
||||
# in loc de 500 brut la primul POST /v1/prezentari.
|
||||
validate_creds_key()
|
||||
# Fail-fast (prod-only): elimina clasa "am uitat env var in Dokploy" pentru
|
||||
# cheia API si secretul de sesiune, in loc de o instanta descoperita post-deploy.
|
||||
validate_prod_invariants(get_settings())
|
||||
init_db()
|
||||
yield
|
||||
|
||||
@@ -63,6 +67,12 @@ app.add_middleware(
|
||||
# OUTERMOST (add_middleware prepend), deci `X-Request-ID` se pune pe TOATE raspunsurile,
|
||||
# inclusiv 401/404/422/500 produse mai in interior.
|
||||
app.add_middleware(RequestIDMiddleware)
|
||||
# Headere de securitate (P1-4) pe TOATE raspunsurile.
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
# Body-cap (P1-5): ADAUGAT ULTIMUL -> ruleaza CEL MAI OUTERMOST (add_middleware
|
||||
# prepend), deci intercepteaza `receive` inaintea oricarui parser FastAPI/Starlette
|
||||
# (multipart, JSON) — vezi docstring body_cap.py pentru motivul ASGI-pur.
|
||||
app.add_middleware(BodyCapMiddleware)
|
||||
|
||||
|
||||
@app.exception_handler(LoginRequired)
|
||||
|
||||
@@ -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
93
app/web/body_cap.py
Normal 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()})
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user