Исправления по ревью: 415 для не-JSON, logout атомарен с инвалидацией кэша

This commit is contained in:
2026-10-22 13:31:03 +03:00
parent dbdb66456a
commit 9e7c792e9d
6 changed files with 172 additions and 23 deletions
+20 -4
View File
@@ -168,6 +168,15 @@ def _parse_basic(request: Request) -> tuple[str, str]:
return username, password
def require_json(request: Request) -> None:
"""Тип тела проверяем ДО валидации тела: не JSON → 415, а не 400.
Подключается после current_user, поэтому без токена по-прежнему сначала 401.
Параметры вроде '; charset=utf-8' допустимы."""
media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if media_type != "application/json":
raise ApiError(415, "unsupported_media_type", "Content-Type must be application/json")
# ============================================================================
# 4. МОДЕЛИ ВВОДА
# ============================================================================
@@ -252,7 +261,7 @@ async def health_ready(request: Request):
# -------- users и сессии --------
@app.post("/api/v1/users", status_code=201)
async def create_user(body: CreateUser):
async def create_user(body: CreateUser, _json: None = Depends(require_json)):
# Argon2 намеренно медленный — считаем в пуле потоков, чтобы не блокировать event loop.
password_hash = await run_in_threadpool(security.hash_password, body.password)
async with db.get_pool().connection() as conn:
@@ -282,7 +291,12 @@ async def create_session(request: Request):
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def delete_session(request: Request, user: dict = Depends(current_user)):
if not await sessions.revoke(db.get_pool(), request.state.token):
try:
revoked = await sessions.revoke(db.get_pool(), request.state.token)
except sessions.CacheUnavailable:
# 204 только при гарантированном отзыве; иначе ограниченная ошибка, повторить позже.
raise ApiError(503, "unavailable", "session cache unavailable, logout not confirmed")
if not revoked:
raise unauthorized()
return Response(status_code=204)
@@ -294,7 +308,8 @@ async def get_me(user: dict = Depends(current_user)):
# -------- chats --------
@app.post("/api/v1/chats", status_code=201)
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
async def create_chat(body: CreateChat, user: dict = Depends(current_user),
_json: None = Depends(require_json)):
members = body.member_ids
if not (1 <= len(members) <= 100):
raise ApiError(400, "invalid_request", "member_ids must have 1..100 items")
@@ -340,7 +355,8 @@ async def get_chat(chat_id: str, user: dict = Depends(current_user)):
# -------- messages --------
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def send_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user)):
async def send_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user),
_json: None = Depends(require_json)):
async with db.get_pool().connection() as conn:
chat = await accessible_chat(conn, chat_id, user)
# Отправитель — из сессии, а не из тела запроса.