- carry the lab 3 solution over from mtusi2026lab3-safronov (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests, bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts, Dockerfile, compose, pyproject and uv lock - merge Makefile, .gitignore and .dockerignore (the lab 3 versions only add lines to the skeleton, which is the same in lab 4) and .env.example (lab 4 skeleton names listed in the header) - rename the compose project to mtusi-lab4 and the image to :lab4 so the stand does not reuse the lab 3 containers and volumes - update AGENTS.md for lab 4: current lab, origin commit, contract and test files of the new skeleton Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
121 lines
4.2 KiB
Python
121 lines
4.2 KiB
Python
"""Спек `identification`: Bearer на защищённых эндпоинтах с лабы 2.
|
|
|
|
Единственный модуль, который собирает `Authorization` и `X-User-Id`
|
|
сам, а не через `Actor.headers()`: проверяются именно заголовки.
|
|
"""
|
|
|
|
import secrets
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from api_client import API, Actor, Api, basic_auth, bearer_auth
|
|
from contract import (
|
|
BEARER_CHALLENGE,
|
|
assert_error,
|
|
assert_ok,
|
|
assert_unauthorized,
|
|
contract,
|
|
)
|
|
|
|
ME = f"{API}/users/me"
|
|
|
|
|
|
@pytest.mark.spec("identification", "Действующий токен")
|
|
def test_valid_token(api: Api, alice: Actor) -> None:
|
|
resp = api.request("GET", ME, headers=bearer_auth(alice.token))
|
|
assert assert_ok(resp, 200, "User") == alice.user
|
|
|
|
|
|
@pytest.mark.spec("identification", "Нет заголовка")
|
|
def test_no_header(api: Api) -> None:
|
|
assert_unauthorized(api.request("GET", ME), BEARER_CHALLENGE)
|
|
|
|
|
|
@pytest.mark.spec("identification", "Неизвестный токен")
|
|
def test_unknown_token(api: Api) -> None:
|
|
for token in (secrets.token_urlsafe(32), "x"):
|
|
resp = api.request("GET", ME, headers=bearer_auth(token))
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
# схема без токена — тот же ответ
|
|
resp = api.request("GET", ME, headers={"Authorization": "Bearer"})
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
|
|
|
|
@pytest.mark.spec("identification", "Basic на бизнес-эндпоинте")
|
|
def test_basic_on_business_endpoint(api: Api, alice: Actor) -> None:
|
|
resp = api.request(
|
|
"GET",
|
|
ME,
|
|
headers=basic_auth(alice.username, alice.password),
|
|
)
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
|
|
|
|
@pytest.mark.spec("identification", "Только X-User-Id")
|
|
def test_only_user_id_header(api: Api, alice: Actor) -> None:
|
|
resp = api.request("GET", ME, headers={"X-User-Id": alice.id})
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
|
|
|
|
@pytest.mark.spec("identification", "X-User-Id не меняет владельца")
|
|
def test_user_id_header_ignored(api: Api, alice: Actor, eve: Actor) -> None:
|
|
resp = api.request(
|
|
"GET",
|
|
ME,
|
|
headers={**bearer_auth(alice.token), "X-User-Id": eve.id},
|
|
)
|
|
assert assert_ok(resp, 200, "User") == alice.user
|
|
|
|
|
|
@pytest.mark.spec("identification", "Чужой чат без заголовка")
|
|
def test_chat_without_token(api: Api, chat: dict[str, Any]) -> None:
|
|
resp = api.request("GET", f"{API}/chats/{chat['id']}")
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
|
|
|
|
@pytest.mark.spec("identification", "Невалидное поле без заголовка")
|
|
def test_invalid_field_without_token(
|
|
api: Api,
|
|
alice: Actor,
|
|
chat: dict[str, Any],
|
|
) -> None:
|
|
# с ключом: кроме токена в запросе неверно только поле
|
|
resp = api.post_message(None, chat["id"], json={"text": ""})
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
assert api.all_messages(alice, chat["id"]) == []
|
|
|
|
|
|
@pytest.mark.spec("identification", "Битый JSON без заголовка")
|
|
def test_malformed_json_without_token(
|
|
api: Api,
|
|
chat: dict[str, Any],
|
|
) -> None:
|
|
# согласованное расхождение: битый JSON отклоняется до аутентификации
|
|
resp = api.post_message(
|
|
None,
|
|
chat["id"],
|
|
headers={"Content-Type": "application/json"},
|
|
content=b"{bad",
|
|
)
|
|
assert_error(resp, 400)
|
|
|
|
|
|
@pytest.mark.spec("identification", "Схема в openapi.json")
|
|
def test_security_schemes_in_openapi(api: Api) -> None:
|
|
resp = api.request("GET", "/openapi.json")
|
|
assert resp.status_code == 200
|
|
served = resp.json()
|
|
schemes = served["components"]["securitySchemes"]
|
|
expected = contract()["components"]["securitySchemes"]
|
|
|
|
assert schemes["bearerAuth"] == expected["bearerAuth"]
|
|
assert schemes["basicAuth"] == expected["basicAuth"]
|
|
assert "devUser" not in schemes
|
|
paths = served["paths"]
|
|
assert paths[ME]["get"]["security"] == [{"bearerAuth": []}]
|
|
assert paths[f"{API}/auth/sessions"]["post"]["security"] == [
|
|
{"basicAuth": []},
|
|
]
|
|
assert not paths[f"{API}/users"]["post"].get("security")
|