Обновила python-код основного приложения. Также обновила collector.yaml
This commit is contained in:
+43
-2
@@ -1,9 +1,9 @@
|
||||
import base64
|
||||
import binascii
|
||||
import os
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from ..models.schemas import Session
|
||||
from ..storage.postgres import storage
|
||||
@@ -13,6 +13,10 @@ router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
|
||||
DEFAULT_TTL_SECONDS = 3600
|
||||
|
||||
# --- lab7: ограничение частоты входов (общее для реплик через Redis) ---
|
||||
LOGIN_WINDOW_SECONDS = int(os.environ.get("LOGIN_WINDOW_SECONDS", "60"))
|
||||
LOGIN_MAX_ATTEMPTS = int(os.environ.get("LOGIN_MAX_ATTEMPTS", "10"))
|
||||
|
||||
|
||||
def _ttl_seconds() -> int:
|
||||
try:
|
||||
@@ -47,6 +51,42 @@ def _parse_basic_header(request: Request) -> tuple[str, str] | None:
|
||||
return username, password
|
||||
|
||||
|
||||
def _login_rate_limit_key(request: Request) -> str:
|
||||
"""Ключ лимита: username + IP клиента (за LB — X-Forwarded-For)."""
|
||||
parsed = _parse_basic_header(request)
|
||||
username = parsed[0] if parsed else "-"
|
||||
fwd = request.headers.get("X-Forwarded-For", "")
|
||||
ip = fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "-")
|
||||
return "loginrl:%s:%s" % (username, ip)
|
||||
|
||||
|
||||
def _check_login_rate_limit(request: Request) -> None:
|
||||
"""Счётчик попыток в Redis. При превышении — 429 с Retry-After."""
|
||||
try:
|
||||
from ..storage.sessions import _redis_client
|
||||
r = _redis_client()
|
||||
except RuntimeError:
|
||||
# Redis недоступен — полагаемся на доступность БД; не блокируем вход.
|
||||
return
|
||||
key = _login_rate_limit_key(request)
|
||||
try:
|
||||
current = r.incr(key)
|
||||
if current == 1:
|
||||
r.expire(key, LOGIN_WINDOW_SECONDS)
|
||||
if current > LOGIN_MAX_ATTEMPTS:
|
||||
ttl = r.ttl(key)
|
||||
raise HTTPException(
|
||||
status_code=429,
|
||||
detail="rate_limited",
|
||||
headers={"Retry-After": str(max(1, int(ttl) if ttl and ttl > 0 else LOGIN_WINDOW_SECONDS))},
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
# Ошибка Redis в счётчике не должна блокировать вход целиком.
|
||||
return
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions",
|
||||
summary="Вход: Basic username:password; выдаёт сессию",
|
||||
@@ -54,6 +94,7 @@ def _parse_basic_header(request: Request) -> tuple[str, str] | None:
|
||||
status_code=201,
|
||||
)
|
||||
def create_session(request: Request) -> Session:
|
||||
_check_login_rate_limit(request)
|
||||
parsed = _parse_basic_header(request)
|
||||
if parsed is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
Reference in New Issue
Block a user