forked from mtusi2026/mtusi2026lab2
Добавить пароли, вход по Basic и Bearer-сессии в Redis
This commit is contained in:
@@ -0,0 +1,38 @@
|
|||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
|
||||||
|
class ApiError(Exception):
|
||||||
|
def __init__(self, status: int, code: str, message: str, headers=None):
|
||||||
|
self.status = status
|
||||||
|
self.code = code
|
||||||
|
self.message = message
|
||||||
|
self.headers = headers
|
||||||
|
|
||||||
|
|
||||||
|
def invalid(message: str) -> ApiError:
|
||||||
|
return ApiError(400, "invalid_request", message)
|
||||||
|
|
||||||
|
|
||||||
|
def bad_credentials() -> ApiError:
|
||||||
|
# один и тот же ответ для неизвестного username и неверного пароля
|
||||||
|
return ApiError(
|
||||||
|
401, "unauthorized", "Неверное имя пользователя или пароль",
|
||||||
|
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def unauthorized() -> ApiError:
|
||||||
|
return ApiError(
|
||||||
|
401, "unauthorized", "Нужен действующий Bearer-токен",
|
||||||
|
{"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def not_found() -> ApiError:
|
||||||
|
# одинаковый ответ для несуществующего и чужого объекта
|
||||||
|
return ApiError(404, "not_found", "Объект не найден")
|
||||||
|
|
||||||
|
|
||||||
|
def error_response(request_id: str, status: int, code: str, message: str, headers=None) -> JSONResponse:
|
||||||
|
body = {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||||
|
return JSONResponse(body, status_code=status, headers=headers)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
"""Проверка для Docker HEALTHCHECK: код 0, если /health/ready отвечает 200."""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
port = os.getenv("APP_PORT", "8080")
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/ready", timeout=4) as response:
|
||||||
|
sys.exit(0 if response.status == 200 else 1)
|
||||||
|
except Exception:
|
||||||
|
sys.exit(1)
|
||||||
+273
@@ -0,0 +1,273 @@
|
|||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
import redis
|
||||||
|
import uvicorn
|
||||||
|
from fastapi import Depends, FastAPI, Query, Request, Response
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from starlette.exceptions import HTTPException
|
||||||
|
|
||||||
|
import config
|
||||||
|
import security
|
||||||
|
from errors import ApiError, bad_credentials, error_response, invalid, not_found, unauthorized
|
||||||
|
from schemas import CreateChat, CreateMessage, CreateUser
|
||||||
|
from sessions import Sessions
|
||||||
|
from store import Store, UnknownMember, UsernameTaken, timestamp
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=config.LOG_LEVEL.upper(),
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
||||||
|
stream=sys.stdout,
|
||||||
|
)
|
||||||
|
log = logging.getLogger("messenger")
|
||||||
|
|
||||||
|
if config.SESSION_STORE != "redis":
|
||||||
|
sys.exit("поддерживается только SESSION_STORE=redis")
|
||||||
|
|
||||||
|
USERNAME = re.compile(r"[a-z0-9_]{3,32}")
|
||||||
|
|
||||||
|
store = Store(config.database_url())
|
||||||
|
sessions = Sessions(config.cache_url())
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
store.open()
|
||||||
|
log.info(
|
||||||
|
"started env=%s listen=%s:%d session_ttl=%ds db_pool_max=%d",
|
||||||
|
config.ENV, config.HOST, config.PORT, config.SESSION_TTL_SECONDS, config.DB_POOL_MAX_SIZE,
|
||||||
|
)
|
||||||
|
yield
|
||||||
|
store.close()
|
||||||
|
sessions.close()
|
||||||
|
log.info("stopped")
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(title="MTUSI Messenger lab2", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def request_context(request: Request, call_next):
|
||||||
|
request_id = uuid.uuid4().hex
|
||||||
|
request.state.request_id = request_id
|
||||||
|
started = time.perf_counter()
|
||||||
|
try:
|
||||||
|
response = await call_next(request)
|
||||||
|
except Exception:
|
||||||
|
log.exception("unhandled error request_id=%s", request_id)
|
||||||
|
response = error_response(request_id, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||||
|
response.headers["X-Request-Id"] = request_id
|
||||||
|
# в лог идут только метод, путь и код ответа: тела запросов, пароли и токены не пишем
|
||||||
|
log.info(
|
||||||
|
"%s %s status=%d duration_ms=%.1f request_id=%s",
|
||||||
|
request.method, request.url.path, response.status_code,
|
||||||
|
(time.perf_counter() - started) * 1000, request_id,
|
||||||
|
)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(ApiError)
|
||||||
|
async def on_api_error(request: Request, exc: ApiError):
|
||||||
|
return error_response(request.state.request_id, exc.status, exc.code, exc.message, exc.headers)
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def on_validation_error(request: Request, exc: RequestValidationError):
|
||||||
|
first = exc.errors()[0]
|
||||||
|
where = ".".join(str(part) for part in first["loc"])
|
||||||
|
return error_response(request.state.request_id, 400, "invalid_request", f"{where}: {first['msg']}")
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(HTTPException)
|
||||||
|
async def on_http_error(request: Request, exc: HTTPException):
|
||||||
|
# сюда попадают ошибки самого фреймворка: неизвестный путь, неподдерживаемый метод
|
||||||
|
if exc.status_code == 404:
|
||||||
|
code, message = "not_found", "Объект не найден"
|
||||||
|
else:
|
||||||
|
code, message = "invalid_request", "Запрос не поддерживается"
|
||||||
|
return error_response(request.state.request_id, exc.status_code, code, message, exc.headers)
|
||||||
|
|
||||||
|
|
||||||
|
# OperationalError — нет связи с PostgreSQL, не дождались соединения из пула или сработал statement_timeout
|
||||||
|
@app.exception_handler(psycopg.OperationalError)
|
||||||
|
async def on_database_down(request: Request, exc: Exception):
|
||||||
|
log.warning("postgres unavailable: %s request_id=%s", type(exc).__name__, request.state.request_id)
|
||||||
|
return error_response(request.state.request_id, 503, "unavailable", "Сервис временно недоступен")
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(redis.RedisError)
|
||||||
|
async def on_cache_down(request: Request, exc: Exception):
|
||||||
|
log.warning("redis unavailable: %s request_id=%s", type(exc).__name__, request.state.request_id)
|
||||||
|
return error_response(request.state.request_id, 503, "unavailable", "Сервис временно недоступен")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Session:
|
||||||
|
user_id: str
|
||||||
|
token: str
|
||||||
|
|
||||||
|
|
||||||
|
def current_session(request: Request) -> Session:
|
||||||
|
# X-User-Id из lab1 здесь не читается вообще, Basic на бизнес-запросах тоже не принимается
|
||||||
|
token = security.parse_bearer(request.headers.get("Authorization"))
|
||||||
|
if token is None:
|
||||||
|
raise unauthorized()
|
||||||
|
# если Redis недоступен, здесь будет исключение и ответ 503: без проверки сессии запрос дальше не идёт
|
||||||
|
user_id = sessions.user_id(token)
|
||||||
|
if user_id is None:
|
||||||
|
raise unauthorized()
|
||||||
|
return Session(user_id, token)
|
||||||
|
|
||||||
|
|
||||||
|
def encode_cursor(scope: str, item: dict) -> str:
|
||||||
|
raw = json.dumps([scope, item["created_at"], item["id"]])
|
||||||
|
return base64.urlsafe_b64encode(raw.encode()).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def decode_cursor(scope: str, cursor):
|
||||||
|
"""Возвращает ключ (created_at, id) последней выданной записи или None для первой страницы."""
|
||||||
|
if cursor is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
cursor_scope, created_at, item_id = json.loads(base64.urlsafe_b64decode(cursor.encode()))
|
||||||
|
key = [datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc), str(UUID(item_id))]
|
||||||
|
except (TypeError, ValueError, AttributeError):
|
||||||
|
raise invalid("Некорректный cursor")
|
||||||
|
# cursor действует только для того списка, в котором был выдан
|
||||||
|
if cursor_scope != scope:
|
||||||
|
raise invalid("Некорректный cursor")
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def page(scope: str, items: list, has_more: bool) -> dict:
|
||||||
|
next_cursor = encode_cursor(scope, items[-1]) if has_more else None
|
||||||
|
return {"items": items, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health/live")
|
||||||
|
def liveness():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health/ready")
|
||||||
|
def readiness():
|
||||||
|
# без PostgreSQL и Redis обязательные запросы не выполнить, поэтому обе зависимости критичны
|
||||||
|
store.ping()
|
||||||
|
sessions.ping()
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/v1/users", status_code=201)
|
||||||
|
def register_user(body: CreateUser):
|
||||||
|
try:
|
||||||
|
return store.create_user(body.username, body.display_name, security.hash_password(body.password))
|
||||||
|
except UsernameTaken:
|
||||||
|
raise ApiError(409, "conflict", "Такой username уже занят")
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||||
|
def create_session(request: Request):
|
||||||
|
credentials = security.parse_basic(request.headers.get("Authorization"))
|
||||||
|
if credentials is None:
|
||||||
|
raise bad_credentials()
|
||||||
|
username, password = credentials
|
||||||
|
user, password_hash = None, None
|
||||||
|
# username, который не мог быть зарегистрирован, в БД не ищем, но пароль всё равно сверяем с пустышкой
|
||||||
|
if USERNAME.fullmatch(username):
|
||||||
|
user, password_hash = store.get_credentials(username)
|
||||||
|
if not security.verify_password(password_hash, password):
|
||||||
|
raise bad_credentials()
|
||||||
|
token = sessions.create(user["id"])
|
||||||
|
expires_at = datetime.now(timezone.utc) + timedelta(seconds=config.SESSION_TTL_SECONDS)
|
||||||
|
return {"token": token, "token_type": "Bearer", "expires_at": timestamp(expires_at), "user": user}
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||||
|
def revoke_session(session: Session = Depends(current_session)):
|
||||||
|
sessions.revoke(session.token)
|
||||||
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/users/me")
|
||||||
|
def get_me(session: Session = Depends(current_session)):
|
||||||
|
user = store.get_user(session.user_id)
|
||||||
|
if user is None:
|
||||||
|
raise unauthorized()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/v1/chats", status_code=201)
|
||||||
|
def create_chat(body: CreateChat, session: Session = Depends(current_session)):
|
||||||
|
member_ids = [str(member) for member in body.member_ids]
|
||||||
|
if len(set(member_ids)) != len(member_ids):
|
||||||
|
raise invalid("member_ids содержит повторы")
|
||||||
|
if session.user_id not in member_ids:
|
||||||
|
raise invalid("Создатель чата должен быть в member_ids")
|
||||||
|
try:
|
||||||
|
return store.create_chat(body.title, member_ids)
|
||||||
|
except UnknownMember:
|
||||||
|
raise invalid("В member_ids есть несуществующий пользователь")
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats")
|
||||||
|
def list_chats(
|
||||||
|
limit: int = Query(50, ge=1, le=100),
|
||||||
|
cursor: str | None = Query(None, min_length=1),
|
||||||
|
session: Session = Depends(current_session),
|
||||||
|
):
|
||||||
|
scope = "chats:" + session.user_id
|
||||||
|
items, has_more = store.list_chats(session.user_id, decode_cursor(scope, cursor), limit)
|
||||||
|
return page(scope, items, has_more)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats/{chat_id}")
|
||||||
|
def get_chat(chat_id: UUID, session: Session = Depends(current_session)):
|
||||||
|
chat = store.get_chat(str(chat_id), session.user_id)
|
||||||
|
if chat is None:
|
||||||
|
raise not_found()
|
||||||
|
return chat
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||||
|
def send_message(chat_id: UUID, body: CreateMessage, session: Session = Depends(current_session)):
|
||||||
|
# отправитель берётся из сессии, в теле запроса его нет
|
||||||
|
message = store.add_message(str(chat_id), session.user_id, body.text)
|
||||||
|
if message is None:
|
||||||
|
raise not_found()
|
||||||
|
return message
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||||
|
def list_messages(
|
||||||
|
chat_id: UUID,
|
||||||
|
limit: int = Query(50, ge=1, le=100),
|
||||||
|
cursor: str | None = Query(None, min_length=1),
|
||||||
|
session: Session = Depends(current_session),
|
||||||
|
):
|
||||||
|
scope = "messages:" + str(chat_id)
|
||||||
|
result = store.list_messages(str(chat_id), session.user_id, decode_cursor(scope, cursor), limit)
|
||||||
|
if result is None:
|
||||||
|
raise not_found()
|
||||||
|
items, has_more = result
|
||||||
|
return page(scope, items, has_more)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
uvicorn.run(
|
||||||
|
app,
|
||||||
|
host=config.HOST,
|
||||||
|
port=config.PORT,
|
||||||
|
log_level=config.LOG_LEVEL,
|
||||||
|
access_log=False,
|
||||||
|
timeout_graceful_shutdown=config.SHUTDOWN_TIMEOUT,
|
||||||
|
)
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||||
|
|
||||||
|
|
||||||
|
def not_blank(value: str) -> str:
|
||||||
|
if not value.strip():
|
||||||
|
raise ValueError("строка не может состоять только из пробелов")
|
||||||
|
# PostgreSQL не хранит символ NUL в text, а одиночные суррогаты нельзя записать в UTF-8
|
||||||
|
if "\x00" in value or any(0xD800 <= ord(char) <= 0xDFFF for char in value):
|
||||||
|
raise ValueError("строка содержит недопустимые символы")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class StrictModel(BaseModel):
|
||||||
|
# лишние поля в JSON считаются ошибкой
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
|
|
||||||
|
class CreateUser(StrictModel):
|
||||||
|
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||||
|
display_name: str = Field(min_length=1, max_length=100)
|
||||||
|
password: str = Field(min_length=12, max_length=128)
|
||||||
|
|
||||||
|
_not_blank = field_validator("display_name", "password")(not_blank)
|
||||||
|
|
||||||
|
|
||||||
|
class CreateChat(StrictModel):
|
||||||
|
title: str = Field(min_length=1, max_length=100)
|
||||||
|
member_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||||
|
|
||||||
|
_title = field_validator("title")(not_blank)
|
||||||
|
|
||||||
|
|
||||||
|
class CreateMessage(StrictModel):
|
||||||
|
text: str = Field(min_length=1, max_length=4000)
|
||||||
|
|
||||||
|
_text = field_validator("text")(not_blank)
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
from argon2.exceptions import InvalidHashError, VerificationError
|
||||||
|
|
||||||
|
# Argon2id, параметры из рекомендаций OWASP: 19 МиБ памяти, 2 прохода, 1 поток
|
||||||
|
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||||
|
# с этим hash сверяется пароль, когда пользователя нет: время ответа не выдаёт, существует ли username
|
||||||
|
DUMMY_HASH = hasher.hash("no-such-user-password")
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
return hasher.hash(password)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(password_hash, password: str) -> bool:
|
||||||
|
try:
|
||||||
|
return hasher.verify(password_hash or DUMMY_HASH, password) and password_hash is not None
|
||||||
|
except (VerificationError, InvalidHashError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def parse_basic(header):
|
||||||
|
"""Разбирает Authorization: Basic base64(username:password). Возвращает пару или None."""
|
||||||
|
scheme, _, value = (header or "").partition(" ")
|
||||||
|
if scheme.lower() != "basic":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
|
||||||
|
except (binascii.Error, UnicodeDecodeError):
|
||||||
|
return None
|
||||||
|
# двоеточие в пароле допустимо, поэтому делим только по первому
|
||||||
|
username, colon, password = decoded.partition(":")
|
||||||
|
if not colon:
|
||||||
|
return None
|
||||||
|
return username, password
|
||||||
|
|
||||||
|
|
||||||
|
def parse_bearer(header):
|
||||||
|
scheme, _, token = (header or "").partition(" ")
|
||||||
|
if scheme.lower() != "bearer" or not token.strip():
|
||||||
|
return None
|
||||||
|
return token.strip()
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import hashlib
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
import redis
|
||||||
|
from redis.backoff import NoBackoff
|
||||||
|
from redis.retry import Retry
|
||||||
|
|
||||||
|
import config
|
||||||
|
|
||||||
|
|
||||||
|
class Sessions:
|
||||||
|
"""Сессии лежат только в Redis: ключ session:<sha256 токена>, значение id пользователя, TTL ставит сам Redis."""
|
||||||
|
|
||||||
|
def __init__(self, url: str):
|
||||||
|
pool = redis.BlockingConnectionPool.from_url(
|
||||||
|
url,
|
||||||
|
max_connections=config.CACHE_POOL_MAX_SIZE,
|
||||||
|
timeout=config.CACHE_TIMEOUT, # ожидание свободного соединения
|
||||||
|
socket_timeout=config.CACHE_TIMEOUT,
|
||||||
|
socket_connect_timeout=config.CACHE_TIMEOUT,
|
||||||
|
decode_responses=True,
|
||||||
|
# одна повторная попытка без паузы: её хватает после перезапуска Redis, а при отказе ответ не затягивается
|
||||||
|
retry=Retry(NoBackoff(), 1),
|
||||||
|
)
|
||||||
|
self.client = redis.Redis(connection_pool=pool)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def key(token: str) -> str:
|
||||||
|
# сам токен в Redis не хранится: по дампу нельзя войти от чужого имени
|
||||||
|
return "session:" + hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
|
||||||
|
def create(self, user_id: str) -> str:
|
||||||
|
token = secrets.token_urlsafe(32) # 256 бит случайности
|
||||||
|
self.client.set(self.key(token), user_id, ex=config.SESSION_TTL_SECONDS)
|
||||||
|
return token
|
||||||
|
|
||||||
|
def user_id(self, token: str):
|
||||||
|
return self.client.get(self.key(token))
|
||||||
|
|
||||||
|
def revoke(self, token: str) -> None:
|
||||||
|
self.client.delete(self.key(token))
|
||||||
|
|
||||||
|
def ping(self) -> None:
|
||||||
|
self.client.ping()
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self.client.close()
|
||||||
Reference in New Issue
Block a user