forked from mtusi2026/mtusi2026lab7
Drop the body-limit rule from HAProxy (user decision 2026-11-18): the
replica middleware answers 400 with X-Instance-Id, tests require the
header again. Widen the failure_checks selection in the trust matrix,
name 13fdd18 in the evidence header, document Valkey LRU eviction of
login counters and the allowlist as trusted X-Forwarded-For senders,
check waited_ms of KDF budget rejections in the queue scenario.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
182 lines
6.6 KiB
Python
182 lines
6.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_error,
|
||
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_login_large_body(api: Api, alice: Actor) -> None:
|
||
"""Предел размера тела (change auth-hardening, решение 8): верный Basic с
|
||
телом больше 64 KiB — 400 до проверки credentials; отказывает реплика по
|
||
Content-Length, с X-Instance-Id (предела в LB нет — решение пользователя
|
||
2026-11-18)."""
|
||
headers = {
|
||
"Authorization": basic_header(
|
||
f"{alice.username}:{alice.password}".encode(),
|
||
)["Authorization"],
|
||
"Content-Type": "application/json",
|
||
}
|
||
resp = api.request(
|
||
"POST",
|
||
SESSIONS,
|
||
headers=headers,
|
||
content=b" " * 65537,
|
||
)
|
||
error = assert_error(resp, 400)
|
||
assert error["message"] == "Request body is too large"
|
||
assert "token" not in resp.text
|
||
|
||
|
||
@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"]) == []
|