This commit is contained in:
@@ -15,7 +15,6 @@ class Settings(BaseSettings):
|
||||
session_ttl_seconds: int = 3600
|
||||
idempotency_ttl_seconds: int = 86400
|
||||
|
||||
# Секреты загружаются из OpenBao
|
||||
database_url: str = ""
|
||||
s3_access_key: str = ""
|
||||
s3_secret_key: str = ""
|
||||
|
||||
+11
-83
@@ -1,48 +1,17 @@
|
||||
import base64
|
||||
import json
|
||||
import redis
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import Response
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import connection
|
||||
from ..errors import ApiError
|
||||
from ..security import (
|
||||
new_session_token,
|
||||
session_expiry,
|
||||
token_digest,
|
||||
verify_password,
|
||||
)
|
||||
from ..serializers import row_to_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
|
||||
WWW_BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||||
WWW_BEARER = 'Bearer realm="messenger"'
|
||||
|
||||
# Подключение к Redis
|
||||
redis_client = redis.Redis.from_url(get_settings().redis_url, decode_responses=True)
|
||||
|
||||
def _parse_basic(header: str | None) -> tuple[str, str]:
|
||||
if not header or not header.lower().startswith("basic "):
|
||||
raise ApiError(401, "unauthorized", "Требуется Basic", {"WWW-Authenticate": WWW_BASIC})
|
||||
try:
|
||||
decoded = base64.b64decode(header[6:].strip(), validate=True).decode("utf-8")
|
||||
except Exception:
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
|
||||
|
||||
if ":" not in decoded:
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
|
||||
|
||||
username, password = decoded.split(":", 1)
|
||||
return username, password
|
||||
|
||||
@router.post("/auth/sessions", status_code=201)
|
||||
def create_session(request: Request):
|
||||
header = request.headers.get("Authorization")
|
||||
username, password = _parse_basic(header)
|
||||
|
||||
# Rate Limiting: не более 5 попыток в минуту
|
||||
redis_key = f"login_attempts:{username}"
|
||||
attempts = int(redis_client.get(redis_key) or 0)
|
||||
if attempts >= 5:
|
||||
raise ApiError(429, "rate_limited", "Слишком много попыток входа", {"Retry-After": "60"})
|
||||
|
||||
redis_client.incr(redis_key)
|
||||
redis_client.expire(redis_key, 60)
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
@@ -60,53 +29,12 @@ def create_session(request: Request):
|
||||
ttl = settings.session_ttl_seconds
|
||||
digest = token_digest(token)
|
||||
|
||||
# СОХРАНЯЕМ В REDIS
|
||||
redis_client.setex(f"session:{digest}", ttl, str(row["id"]))
|
||||
redis_client.delete(redis_key) # Сбрасываем счетчик при успешном входе
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session_expiry(ttl).isoformat().replace("+00:00", "Z"),
|
||||
"user": row_to_user(row),
|
||||
}
|
||||
|
||||
def _extract_bearer(request: Request) -> str:
|
||||
header = request.headers.get("Authorization")
|
||||
if not header or not header.lower().startswith("bearer "):
|
||||
raise ApiError(401, "unauthorized", "Требуется Bearer", {"WWW-Authenticate": WWW_BEARER})
|
||||
token = header[7:].strip()
|
||||
if not token:
|
||||
raise ApiError(401, "unauthorized", "Требуется Bearer", {"WWW-Authenticate": WWW_BEARER})
|
||||
return token
|
||||
|
||||
def require_actor(request: Request) -> dict:
|
||||
token = _extract_bearer(request)
|
||||
digest = token_digest(token)
|
||||
|
||||
# ЧИТАЕМ ИЗ REDIS
|
||||
user_id = redis_client.get(f"session:{digest}")
|
||||
if user_id is None:
|
||||
raise ApiError(401, "unauthorized", "Сессия недействительна или истекла", {"WWW-Authenticate": WWW_BEARER})
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if row is None:
|
||||
raise ApiError(401, "unauthorized", "Пользователь не найден", {"WWW-Authenticate": WWW_BEARER})
|
||||
|
||||
return {
|
||||
"user": row_to_user(row),
|
||||
"user_id": user_id,
|
||||
"token_hash": digest,
|
||||
}
|
||||
|
||||
@router.delete("/auth/sessions/current", status_code=204)
|
||||
def revoke_session(request: Request, actor: dict = Depends(require_actor)):
|
||||
# УДАЛЯЕМ ИЗ REDIS
|
||||
redis_client.delete(f"session:{actor['token_hash']}")
|
||||
return Response(status_code=204)
|
||||
}
|
||||
+2
-2
@@ -8,8 +8,8 @@ def get_s3_client():
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=s.s3_endpoint,
|
||||
aws_access_key_id=s.s3_access_key,
|
||||
aws_secret_access_key=s.s3_secret_key,
|
||||
aws_access_key_id=s.aws_access_key,
|
||||
aws_secret_access_key=s.aws_secret_key,
|
||||
region_name=s.s3_region,
|
||||
config=Config(signature_version="s3v4"),
|
||||
)
|
||||
|
||||
+8
-8
@@ -1,17 +1,21 @@
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
_ph = PasswordHasher() # Argon2id по умолчанию
|
||||
|
||||
# Явные параметры Argon2id для lab7
|
||||
_ph = PasswordHasher(
|
||||
time_cost=2,
|
||||
memory_cost=19456, # 19 MiB
|
||||
parallelism=1,
|
||||
hash_len=32,
|
||||
salt_len=16
|
||||
)
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _ph.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
try:
|
||||
return _ph.verify(password_hash, password)
|
||||
@@ -20,15 +24,11 @@ def verify_password(password: str, password_hash: str) -> bool:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def new_session_token() -> str:
|
||||
# 32 байта = 256 бит энтропии; url-safe hex без паддинга.
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_digest(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def session_expiry(ttl_seconds: int) -> datetime:
|
||||
return datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)
|
||||
+1
-1
@@ -11,7 +11,7 @@ def get_secrets() -> dict:
|
||||
token = os.environ.get("OPENBAO_TOKEN", "")
|
||||
|
||||
if not token:
|
||||
logger.warning("OPENBAO_TOKEN is not set. Using fallback default values.")
|
||||
logger.warning("OPENBAO_TOKEN is not set. Using fallback.")
|
||||
return {
|
||||
"db_password": "messenger_password",
|
||||
"s3_access_key": "minioadmin",
|
||||
|
||||
Reference in New Issue
Block a user