From 5ce43c33159f68eb11abb1e808406978245eb972 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D1=8F=D0=BA=D0=B8=D1=88=D0=B5=D0=B2=20=D0=92=D0=BB?= =?UTF-8?q?=D0=B0=D0=B4=D0=B8=D1=81=D0=BB=D0=B0=D0=B2?= Date: Wed, 21 Oct 2026 10:46:20 +0300 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=85=D0=BE=D0=B4:=20=D0=BE=D1=82=D0=BA?= =?UTF-8?q?=D0=BB=D0=BE=D0=BD=D1=8F=D1=82=D1=8C=20POST=20/auth/sessions=20?= =?UTF-8?q?=D1=81=20=D1=82=D0=B5=D0=BB=D0=BE=D0=BC=20(400)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Контракт задаёт вход без тела; раньше лишний JSON игнорировался, и запрос с правильным Basic создавал сессию. Добавлен отрицательный тест. --- app/api/dependencies.py | 6 ++++++ app/api/v1/auth_rout.py | 5 +++-- student-tests/test_auth_api.py | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/app/api/dependencies.py b/app/api/dependencies.py index 5cbbbba1..79777b4e 100644 --- a/app/api/dependencies.py +++ b/app/api/dependencies.py @@ -26,6 +26,12 @@ basic_scheme = RawBasicHeader(scheme_name="basicAuth", auto_error=False) bearer_scheme = RawBearerHeader(scheme_name="bearerAuth", auto_error=False) +async def require_empty_body(request: Request) -> None: + # Контракт задаёт вход без тела: лишний JSON не игнорируем молча, а отклоняем. + if await request.body(): + raise HTTPException(status_code=400, detail="Тело запроса не допускается") + + def unauthorized() -> HTTPException: return HTTPException(status_code=401, detail="Нужен действительный Bearer-токен", headers=BEARER_CHALLENGE) diff --git a/app/api/v1/auth_rout.py b/app/api/v1/auth_rout.py index bce0828e..89e1abbc 100644 --- a/app/api/v1/auth_rout.py +++ b/app/api/v1/auth_rout.py @@ -4,7 +4,7 @@ import binascii from fastapi import APIRouter, Depends, HTTPException, Response, Security from sqlalchemy.orm import Session -from api.dependencies import basic_scheme, get_current_session +from api.dependencies import basic_scheme, get_current_session, require_empty_body from core.config import settings from core.db import get_db from core.logger import logger @@ -43,7 +43,8 @@ def parse_basic(authorization: str | None) -> tuple[str, str]: return username, password -@roter.post("/sessions", status_code=201, response_model=SessionResponse) +# Тело проверяется до пароля: зависимости маршрута выполняются раньше параметров. +@roter.post("/sessions", status_code=201, response_model=SessionResponse, dependencies=[Depends(require_empty_body)]) def create_session_api(authorization: str | None = Security(basic_scheme), db: Session = Depends(get_db)): username, password = parse_basic(authorization) diff --git a/student-tests/test_auth_api.py b/student-tests/test_auth_api.py index a3c7fda1..1c91a857 100644 --- a/student-tests/test_auth_api.py +++ b/student-tests/test_auth_api.py @@ -1,9 +1,11 @@ import time import jwt +from sqlalchemy import text from conftest import PASSWORD, assert_error, basic, bearer, login from core.config import settings +from core.db import engine def assert_challenge(response, scheme): @@ -44,6 +46,18 @@ def test_malformed_basic_returns_401(client): assert_challenge(response, "Basic") +def test_login_with_body_returns_400_and_creates_no_session(client, alice): + with engine.connect() as connection: + before = connection.scalar(text("SELECT count(*) FROM sessions")) + for kwargs in ({"json": {"unexpected": True}}, {"json": {}}, {"content": b"x"}): + response = client.post("/api/v1/auth/sessions", headers=basic("alice", PASSWORD), **kwargs) + assert_error(response, 400, "invalid_request") + with engine.connect() as connection: + assert connection.scalar(text("SELECT count(*) FROM sessions")) == before + # Без тела вход по-прежнему работает. + assert login(client, "alice")["user"]["id"] == alice["id"] + + def test_password_with_colon_and_unicode(client): password = "пароль:с:двоеточиями 👋" client.post("/api/v1/users", json={"username": "colon", "display_name": "C", "password": password})