Source: mtusi2026lab5-safronov, solution/bvt2301-safronov, 046ec9e. Contracts, public tests and evidence of lab 5 are not carried over. The compose project, image and CI prefix are renamed to lab6; the first broker start defect is recorded in KNOWN_ISSUES.md; PLAN.md outlines the OpenSpec changes of lab 6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
158 lines
5.6 KiB
Python
158 lines
5.6 KiB
Python
"""Спек `sessions`: вход по Basic, токен, отказ во входе, отзыв.
|
|
|
|
Истечение, рестарт и недоступность БД требуют особого стенда — это
|
|
исключения в `spec_coverage.py`. Неверный пароль и выход — в
|
|
`test_rubric.py` (обязательные сценарии уровня «4»).
|
|
"""
|
|
|
|
import base64
|
|
from datetime import UTC, datetime
|
|
|
|
import pytest
|
|
|
|
from api_client import (
|
|
API,
|
|
SESSIONS,
|
|
Actor,
|
|
Api,
|
|
bearer_auth,
|
|
unique_username,
|
|
)
|
|
from contract import (
|
|
BASIC_CHALLENGE,
|
|
BEARER_CHALLENGE,
|
|
assert_ok,
|
|
assert_unauthorized,
|
|
)
|
|
|
|
ME = f"{API}/users/me"
|
|
|
|
|
|
def basic_header(raw: bytes) -> dict[str, str]:
|
|
"""`Authorization: Basic` из произвольных байтов, в том числе битых."""
|
|
return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")}
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Успешный вход")
|
|
def test_login(api: Api, alice: Actor) -> None:
|
|
resp = api.login_response(alice.username, alice.password)
|
|
session = assert_ok(resp, 201, "Session")
|
|
|
|
assert session["token_type"] == "Bearer"
|
|
assert session["user"] == alice.user
|
|
expires_at = datetime.fromisoformat(session["expires_at"])
|
|
assert expires_at > datetime.now(UTC)
|
|
me = api.request("GET", ME, headers=bearer_auth(session["token"]))
|
|
assert assert_ok(me, 200, "User") == alice.user
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Успешный вход")
|
|
def test_login_ignores_body(api: Api, alice: Actor, eve: Actor) -> None:
|
|
# тело не читается: вход определяет только Basic
|
|
resp = api.request(
|
|
"POST",
|
|
SESSIONS,
|
|
headers=basic_header(f"{alice.username}:{alice.password}".encode()),
|
|
json={"username": eve.username, "password": eve.password},
|
|
)
|
|
assert assert_ok(resp, 201, "Session")["user"] == alice.user
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Двоеточие и не-ASCII в пароле")
|
|
def test_password_with_colon_and_cyrillic(api: Api) -> None:
|
|
password = "Пароль:с:двоеточиями-1"
|
|
actor = api.register(password=password)
|
|
resp = api.request("GET", ME, actor=actor)
|
|
assert assert_ok(resp, 200, "User") == actor.user
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Несколько сессий")
|
|
def test_two_sessions(api: Api, alice: Actor) -> None:
|
|
second = api.login(alice.user, alice.password)
|
|
|
|
assert second.token != alice.token
|
|
for actor in (alice, second):
|
|
resp = api.request("GET", ME, actor=actor)
|
|
assert assert_ok(resp, 200, "User") == alice.user
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Токен не выводится из данных пользователя")
|
|
def test_token_is_opaque(api: Api, alice: Actor) -> None:
|
|
second = api.login(alice.user, alice.password)
|
|
for token in (alice.token, second.token):
|
|
assert len(token) >= 32
|
|
for value in (alice.username, alice.id, alice.id.replace("-", "")):
|
|
assert value not in token
|
|
assert alice.token != second.token
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Неизвестный пользователь")
|
|
def test_unknown_user_same_as_wrong_password(api: Api, alice: Actor) -> None:
|
|
wrong = assert_unauthorized(
|
|
api.login_response(alice.username, "Wrong-password-1"),
|
|
BASIC_CHALLENGE,
|
|
)
|
|
unknown = assert_unauthorized(
|
|
api.login_response(unique_username(), "Wrong-password-1"),
|
|
BASIC_CHALLENGE,
|
|
)
|
|
assert (unknown["code"], unknown["message"]) == (
|
|
wrong["code"],
|
|
wrong["message"],
|
|
)
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Битый Basic")
|
|
def test_broken_basic(api: Api, alice: Actor) -> None:
|
|
headers = (
|
|
{"Authorization": "Basic !!!"},
|
|
basic_header(b"no-colon-here"),
|
|
basic_header(b"\xff\xfe:not-utf-8-password"),
|
|
{"Authorization": "Basic"},
|
|
bearer_auth(alice.token),
|
|
{},
|
|
)
|
|
for header in headers:
|
|
resp = api.request("POST", SESSIONS, headers=header)
|
|
assert_unauthorized(resp, BASIC_CHALLENGE)
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Повторный выход")
|
|
def test_logout_twice(api: Api, alice: Actor) -> None:
|
|
assert api.logout(alice).status_code == 204
|
|
assert_unauthorized(api.logout(alice), BEARER_CHALLENGE)
|
|
# без токена выход тоже 401 с вызовом Bearer
|
|
resp = api.request("DELETE", f"{SESSIONS}/current")
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
|
|
|
|
@pytest.mark.spec("sessions", "Другая сессия остаётся")
|
|
def test_other_session_survives_logout(api: Api, alice: Actor) -> None:
|
|
second = api.login(alice.user, alice.password)
|
|
assert api.logout(alice).status_code == 204
|
|
|
|
assert_unauthorized(api.request("GET", ME, actor=alice), BEARER_CHALLENGE)
|
|
resp = api.request("GET", ME, actor=second)
|
|
assert assert_ok(resp, 200, "User") == alice.user
|
|
|
|
|
|
def test_revoked_token_rejected_everywhere(
|
|
api: Api,
|
|
alice: Actor,
|
|
bob: Actor,
|
|
) -> None:
|
|
"""Отозванный токен не проходит ни на одном защищённом эндпоинте."""
|
|
chat = api.create_chat(alice, bob)
|
|
assert api.logout(alice).status_code == 204
|
|
for method, path in (
|
|
("GET", ME),
|
|
("GET", f"{API}/chats"),
|
|
("GET", f"{API}/chats/{chat['id']}"),
|
|
("GET", f"{API}/chats/{chat['id']}/messages"),
|
|
):
|
|
resp = api.request(method, path, actor=alice)
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
resp = api.post_message(alice, chat["id"], json={"text": "после выхода"})
|
|
assert_unauthorized(resp, BEARER_CHALLENGE)
|
|
assert api.all_messages(bob, chat["id"]) == []
|