feat: add replicated messenger and reproducible lab3 stand

This commit is contained in:
2026-10-15 13:43:39 +03:00
parent 0ab3a341aa
commit 84dd7fec0a
106 changed files with 17235 additions and 24 deletions
+196
View File
@@ -0,0 +1,196 @@
"""Переход 1 → 2: пароль, вход по Basic, Bearer-сессия, выход.
Единственный модуль, который собирает `Authorization` и `X-User-Id` сам,
а не через `helpers.headers()`: здесь проверяются именно заголовки.
Неверный пароль и logout — в `test_rubric.py` (рубрика уровня «4»),
срок сессии и отказ БД — в `test_failures.py`.
"""
import secrets
from datetime import UTC, datetime
import httpx
import pytest
from helpers import (
BASIC_CHALLENGE,
BEARER_CHALLENGE,
CHATS,
ME,
SESSIONS,
USERS,
assert_error,
assert_unauthorized,
basic_header,
basic_raw,
bearer_header,
create_chat,
headers,
login,
logout,
messages_path,
public,
read_history,
register,
unique_password,
unique_username,
)
def test_login_returns_opaque_session(client: httpx.Client) -> None:
alice = register(client, "alice")
response = client.post(
SESSIONS, headers=basic_header(alice["username"], alice["password"])
)
assert response.status_code == 201, response.text
session = response.json()
assert session["user"] == public(alice)
expires_at = datetime.fromisoformat(session["expires_at"])
assert expires_at > datetime.now(UTC)
# токен ничего не кодирует: ни username, ни id
token = session["token"]
for value in (alice["username"], alice["id"], alice["id"].replace("-", "")):
assert value not in token
me = client.get(ME, headers=bearer_header(token))
assert me.json() == public(alice)
def test_login_ignores_json_body(client: httpx.Client) -> None:
alice, eve = register(client, "alice"), register(client, "eve")
response = client.post(
SESSIONS,
headers=basic_header(alice["username"], alice["password"]),
json={"username": eve["username"], "password": eve["password"]},
)
assert response.status_code == 201, response.text
assert response.json()["user"] == public(alice)
def test_password_with_colon_and_cyrillic(client: httpx.Client) -> None:
"""Пароль — UTF-8, разделитель Basic — первое двоеточие."""
actor = register(client, "utf", password="Пароль:с:двоеточиями-1")
assert client.get(ME, headers=headers(actor)).json() == public(actor)
@pytest.mark.parametrize(
"value",
["short", " " * 12, "x" * 129],
ids=["too-short", "blank", "too-long"],
)
def test_bad_password_on_registration_is_400(client: httpx.Client, value: str) -> None:
body = {
"username": unique_username("pw"),
"display_name": "Тест",
"password": value,
}
assert_error(client.post(USERS, json=body), 400, "invalid_request")
@pytest.mark.parametrize(
"header",
[
{"Authorization": "Basic !!!"},
basic_raw(b"no-colon-here"),
basic_raw(b"\xff\xfe:not-utf-8-password"),
{"Authorization": "Basic"},
bearer_header(secrets.token_urlsafe(32)),
{},
],
ids=["not-base64", "no-colon", "not-utf8", "empty", "bearer", "none"],
)
def test_broken_basic_is_401(client: httpx.Client, header: dict[str, str]) -> None:
assert_unauthorized(client.post(SESSIONS, headers=header), BASIC_CHALLENGE)
def test_basic_on_business_endpoint_is_401(client: httpx.Client) -> None:
alice = register(client, "alice")
response = client.get(
ME, headers=basic_header(alice["username"], alice["password"])
)
assert_unauthorized(response, BEARER_CHALLENGE)
@pytest.mark.parametrize(
"header",
[
{},
{"Authorization": "Bearer"},
bearer_header("x"),
bearer_header(secrets.token_urlsafe(32)),
],
ids=["none", "empty", "short", "unknown"],
)
def test_missing_or_unknown_token_is_401(
client: httpx.Client, header: dict[str, str]
) -> None:
assert_unauthorized(client.get(ME, headers=header), BEARER_CHALLENGE)
def test_x_user_id_gives_no_access(client: httpx.Client) -> None:
alice, eve = register(client, "alice"), register(client, "eve")
# только X-User-Id — 401; вместе с Bearer alice — по-прежнему alice
assert_unauthorized(
client.get(ME, headers={"X-User-Id": alice["id"]}), BEARER_CHALLENGE
)
response = client.get(ME, headers={**headers(alice), "X-User-Id": eve["id"]})
assert response.json() == public(alice)
def test_two_sessions_and_logout_of_one(client: httpx.Client) -> None:
alice = register(client, "alice")
second = {**alice, "token": login(client, alice)}
assert second["token"] != alice["token"]
assert logout(client, alice).status_code == 204
assert_unauthorized(client.get(ME, headers=headers(alice)), BEARER_CHALLENGE)
# другая сессия того же пользователя продолжает работать
assert client.get(ME, headers=headers(second)).json() == public(alice)
def test_revoked_token_is_rejected_everywhere(client: httpx.Client) -> None:
alice, bob = register(client, "alice"), register(client, "bob")
chat = create_chat(client, alice, bob)
assert logout(client, alice).status_code == 204
for method, path in (
("GET", ME),
("GET", CHATS),
("GET", f"{CHATS}/{chat['id']}"),
("GET", messages_path(chat)),
):
response = client.request(method, path, headers=headers(alice))
assert_unauthorized(response, BEARER_CHALLENGE)
response = client.post(
messages_path(chat),
json={"text": "после выхода"},
headers=headers(alice),
)
assert_unauthorized(response, BEARER_CHALLENGE)
items, _ = read_history(client, bob, chat, limit=50)
assert items == []
def test_user_never_contains_password(client: httpx.Client) -> None:
password = unique_password()
actor = register(client, "secret", password=password)
for response in (
client.get(ME, headers=headers(actor)),
client.post(SESSIONS, headers=basic_header(actor["username"], password)),
):
assert password not in response.text
assert "password" not in response.text
def test_security_schemes_in_openapi(client: httpx.Client) -> None:
"""Схемы bearerAuth и basicAuth как в контракте: кнопка Authorize в /docs."""
served = client.get("/openapi.json").json()
schemes = served["components"]["securitySchemes"]
assert schemes["bearerAuth"] == {
"type": "http",
"scheme": "bearer",
"bearerFormat": "opaque session token",
}
assert schemes["basicAuth"] == {"type": "http", "scheme": "basic"}
paths = served["paths"]
assert paths[ME]["get"]["security"] == [{"bearerAuth": []}]
assert paths[SESSIONS]["post"]["security"] == [{"basicAuth": []}]
assert not paths[USERS]["post"].get("security")