feat: add password login and bearer sessions
- Argon2id password hashes, KDF in a thread with its own limit - POST /auth/sessions with Basic, DELETE /auth/sessions/current - Bearer sessions in PostgreSQL, X-User-Id ignored - migration drops lab 1 data without passwords - student-tests on tokens, sessions spec and synced specs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+78
-10
@@ -1,5 +1,8 @@
|
||||
"""HTTP-клиент набора: запросы к API и идентификация в одном месте."""
|
||||
|
||||
import base64
|
||||
import dataclasses
|
||||
import secrets
|
||||
import uuid
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
@@ -11,6 +14,7 @@ import httpx
|
||||
from contract import assert_ok
|
||||
|
||||
API = "/api/v1"
|
||||
SESSIONS = f"{API}/auth/sessions"
|
||||
# защита от бесконечного обхода, если next_cursor никогда не станет null
|
||||
MAX_PAGES = 1000
|
||||
|
||||
@@ -20,6 +24,34 @@ def unique_username() -> str:
|
||||
return f"t_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def unique_password() -> str:
|
||||
"""Синтетический пароль из 12–128 символов, свой у каждого вызова."""
|
||||
return f"pw-{uuid.uuid4().hex}"
|
||||
|
||||
|
||||
def registration(
|
||||
username: str,
|
||||
display_name: Any = "Test user",
|
||||
password: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Тело `POST /users`; пароль по умолчанию — новый синтетический."""
|
||||
return {
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"password": unique_password() if password is None else password,
|
||||
}
|
||||
|
||||
|
||||
def basic_auth(username: str, password: str) -> dict[str, str]:
|
||||
"""`Authorization: Basic` из username и пароля в UTF-8."""
|
||||
raw = f"{username}:{password}".encode()
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")}
|
||||
|
||||
|
||||
def bearer_auth(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def order_key(item: dict[str, Any]) -> tuple[datetime, int]:
|
||||
"""Порядок списков API: `(created_at, id)`, id сравнивается как UUID."""
|
||||
created_at = datetime.fromisoformat(item["created_at"])
|
||||
@@ -28,22 +60,36 @@ def order_key(item: dict[str, Any]) -> tuple[datetime, int]:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Actor:
|
||||
"""Зарегистрированный пользователь и то, как он себя называет."""
|
||||
"""Пользователь, его пароль и токен текущей сессии."""
|
||||
|
||||
user: dict[str, Any]
|
||||
password: str
|
||||
token: str
|
||||
|
||||
@classmethod
|
||||
def unregistered(cls) -> "Actor":
|
||||
"""Пользователь, которого нет на сервере."""
|
||||
return cls(user={"id": str(uuid.uuid4())})
|
||||
"""Пользователь, которого нет на сервере, с невыданным токеном."""
|
||||
return cls(
|
||||
user={"id": str(uuid.uuid4()), "username": unique_username()},
|
||||
password=unique_password(),
|
||||
token=secrets.token_urlsafe(32),
|
||||
)
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
return self.user["id"]
|
||||
|
||||
@property
|
||||
def username(self) -> str:
|
||||
return self.user["username"]
|
||||
|
||||
def with_token(self, token: str) -> "Actor":
|
||||
"""Тот же пользователь с другой сессией."""
|
||||
return dataclasses.replace(self, token=token)
|
||||
|
||||
def headers(self) -> dict[str, str]:
|
||||
"""Идентификация: лаба 1 — `X-User-Id`, с лабы 2 — Bearer."""
|
||||
return {"X-User-Id": self.id}
|
||||
"""Идентификация: с лабы 2 — Bearer-токен сессии."""
|
||||
return bearer_auth(self.token)
|
||||
|
||||
|
||||
class Api:
|
||||
@@ -79,16 +125,38 @@ class Api:
|
||||
*,
|
||||
username: str | None = None,
|
||||
display_name: str = "Test user",
|
||||
password: str | None = None,
|
||||
) -> Actor:
|
||||
"""Регистрация и сразу вход: у пользователя есть токен."""
|
||||
password = password or unique_password()
|
||||
resp = self.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={
|
||||
"username": username or unique_username(),
|
||||
"display_name": display_name,
|
||||
},
|
||||
json=registration(
|
||||
username or unique_username(),
|
||||
display_name,
|
||||
password,
|
||||
),
|
||||
)
|
||||
return Actor(assert_ok(resp, 201, "User"))
|
||||
user = assert_ok(resp, 201, "User")
|
||||
return self.login(user, password)
|
||||
|
||||
def login_response(self, username: str, password: str) -> httpx.Response:
|
||||
return self.request(
|
||||
"POST",
|
||||
SESSIONS,
|
||||
headers=basic_auth(username, password),
|
||||
)
|
||||
|
||||
def login(self, user: dict[str, Any], password: str) -> Actor:
|
||||
"""Новая сессия пользователя; ответ проверяется по схеме `Session`."""
|
||||
resp = self.login_response(user["username"], password)
|
||||
session = assert_ok(resp, 201, "Session")
|
||||
assert session["user"] == user, "session user differs from user"
|
||||
return Actor(user=user, password=password, token=session["token"])
|
||||
|
||||
def logout(self, actor: Actor) -> httpx.Response:
|
||||
return self.request("DELETE", f"{SESSIONS}/current", actor=actor)
|
||||
|
||||
def create_chat(
|
||||
self,
|
||||
|
||||
@@ -23,6 +23,10 @@ UUID_RE = re.compile(
|
||||
# RFC 3339 в UTC: шесть знаков долей секунды и суффикс Z
|
||||
CREATED_AT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$")
|
||||
ID_KEYS = frozenset({"id", "chat_id", "sender_id"})
|
||||
TIME_KEYS = frozenset({"created_at", "expires_at"})
|
||||
# WWW-Authenticate у 401 (contracts/README.md): вход и остальные запросы
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
# признаки внутренностей сервиса в error.message
|
||||
LEAK_RE = re.compile(r"Traceback|File \"|\.py\b|/app/|/src/|Error\(")
|
||||
|
||||
@@ -82,7 +86,7 @@ def check_formats(value: Any, path: str = "") -> None:
|
||||
elif key == "member_ids":
|
||||
for number, member in enumerate(item):
|
||||
assert_uuid(member, f"{where}/{number}")
|
||||
elif key == "created_at":
|
||||
elif key in TIME_KEYS:
|
||||
assert_created_at(item, where)
|
||||
else:
|
||||
check_formats(item, where)
|
||||
@@ -135,6 +139,19 @@ def assert_error(resp: httpx.Response, status: int) -> dict[str, Any]:
|
||||
return error
|
||||
|
||||
|
||||
def assert_unauthorized(
|
||||
resp: httpx.Response,
|
||||
challenge: str,
|
||||
) -> dict[str, Any]:
|
||||
"""401 в формате контракта с заданным `WWW-Authenticate`."""
|
||||
error = assert_error(resp, 401)
|
||||
assert resp.headers.get("WWW-Authenticate") == challenge, describe(
|
||||
resp,
|
||||
f"expected WWW-Authenticate {challenge}",
|
||||
)
|
||||
return error
|
||||
|
||||
|
||||
def json_body(resp: httpx.Response) -> Any:
|
||||
"""JSON-тело в UTF-8 и непустой `X-Request-Id`."""
|
||||
request_id = resp.headers.get("X-Request-Id", "")
|
||||
|
||||
@@ -13,6 +13,7 @@ SPECS_DIR = Path(__file__).resolve().parents[1] / "openspec" / "specs"
|
||||
CAPABILITIES = (
|
||||
"api-conventions",
|
||||
"identification",
|
||||
"sessions",
|
||||
"users",
|
||||
"chats",
|
||||
"messages",
|
||||
@@ -48,8 +49,9 @@ EXCLUDED: dict[Scenario, Exclusion] = {
|
||||
),
|
||||
("data-storage", "Прежний пользователь после рестарта"): Exclusion(
|
||||
reason="нужен рестарт стенда, тесты сервер не трогают",
|
||||
check="evidence/storage/restart.md: после scripts/restart.sh "
|
||||
"прежний X-User-Id получает 200, данные и порядок те же",
|
||||
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh: "
|
||||
"прежний токен читает те же данные — "
|
||||
"evidence/storage/test-persistence.md",
|
||||
),
|
||||
("data-storage", "Сбой при добавлении участников"): Exclusion(
|
||||
reason="нужен сбой БД посреди транзакции: штатным запросом его "
|
||||
@@ -80,8 +82,39 @@ EXCLUDED: dict[Scenario, Exclusion] = {
|
||||
),
|
||||
("identification", "Кнопка Authorize в Swagger"): Exclusion(
|
||||
reason="это интерфейс /docs в браузере",
|
||||
check="схему devUser, из которой строится кнопка, проверяет "
|
||||
"тест сценария «Схема в openapi.json»; кнопку — вручную",
|
||||
check="схемы bearerAuth и basicAuth, из которых строится кнопка, "
|
||||
"проверяет тест сценария «Схема в openapi.json»; кнопку — вручную",
|
||||
),
|
||||
("sessions", "Токена нет в хранилище"): Exclusion(
|
||||
reason="нужен доступ к таблицам PostgreSQL, а тесты ходят по HTTP",
|
||||
check="поиск выданного токена по всем таблицам через psql — "
|
||||
"evidence/auth/passwords-and-tokens.md",
|
||||
),
|
||||
("sessions", "Истёкший токен"): Exclusion(
|
||||
reason="нужен сервис со сроком сессии 2 с, а обычный стенд — с 3600 с",
|
||||
check="AUTH__SESSION_TTL_SECONDS=2 — evidence/auth/expiry.md; "
|
||||
"автоматическая проверка — change failure-checks",
|
||||
),
|
||||
("sessions", "Срок не продлевается"): Exclusion(
|
||||
reason="нужен сервис со сроком сессии 2 с",
|
||||
check="запросы каждые 0,5 с при сроке 2 с — "
|
||||
"evidence/auth/expiry.md; автоматическая проверка — change "
|
||||
"failure-checks",
|
||||
),
|
||||
("sessions", "Прежний токен после рестарта"): Exclusion(
|
||||
reason="нужен рестарт стенда, тесты сервер не трогают",
|
||||
check="make test-persistence ACTION_SCRIPT=scripts/restart.sh — "
|
||||
"evidence/storage/test-persistence.md",
|
||||
),
|
||||
("sessions", "БД остановлена при запросе с токеном"): Exclusion(
|
||||
reason="нужно остановить Postgres, тесты стенд не трогают",
|
||||
check="evidence/auth/expiry.md; автоматическая проверка — "
|
||||
"change failure-checks",
|
||||
),
|
||||
("users", "Хэш в БД"): Exclusion(
|
||||
reason="нужен доступ к таблице users, а тесты ходят по HTTP",
|
||||
check="строки users через psql: префикс $argon2id$ и разные "
|
||||
"хэши одинаковых паролей — evidence/auth/passwords-and-tokens.md",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from api_client import API, Actor, Api, unique_username
|
||||
from api_client import API, Actor, Api, registration, unique_username
|
||||
from contract import (
|
||||
assert_created_at,
|
||||
assert_error,
|
||||
@@ -93,7 +93,7 @@ def test_error_request_id_matches_header(
|
||||
resp = api.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={"username": alice.user["username"], "display_name": "Alice"},
|
||||
json=registration(alice.username, "Alice"),
|
||||
)
|
||||
assert_error(resp, 409)
|
||||
|
||||
@@ -103,7 +103,7 @@ def test_no_fastapi_detail(api: Api, alice: Actor) -> None:
|
||||
validation = api.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={"username": "ab", "display_name": "x"},
|
||||
json=registration("ab", "x"),
|
||||
)
|
||||
not_found = api.request("GET", f"{API}/unknown", actor=alice)
|
||||
for resp, status in ((validation, 400), (not_found, 404)):
|
||||
@@ -126,11 +126,7 @@ def test_extra_field(api: Api, alice: Actor) -> None:
|
||||
resp = api.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={
|
||||
"username": unique_username(),
|
||||
"display_name": "Extra",
|
||||
"is_admin": True,
|
||||
},
|
||||
json={**registration(unique_username(), "Extra"), "is_admin": True},
|
||||
)
|
||||
assert_error(resp, 400)
|
||||
resp = api.request(
|
||||
@@ -148,7 +144,7 @@ def test_wrong_type_is_not_coerced(api: Api) -> None:
|
||||
resp = api.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={"username": username, "display_name": 123},
|
||||
json=registration(username, 123),
|
||||
)
|
||||
assert_error(resp, 400)
|
||||
# пользователь не создан: то же имя свободно
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Спек `health`: live и ready без идентификации, вне `/api/v1`."""
|
||||
"""Спек `health`: live и ready без аутентификации, вне `/api/v1`."""
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -21,7 +21,15 @@ def test_ready(api: Api) -> None:
|
||||
|
||||
|
||||
@pytest.mark.spec("health", "Неизвестный X-User-Id")
|
||||
def test_unknown_user_is_ignored(api: Api) -> None:
|
||||
def test_unknown_user_id_is_ignored(api: Api) -> None:
|
||||
ghost = Actor.unregistered()
|
||||
for path in HEALTH:
|
||||
resp = api.request("GET", path, headers={"X-User-Id": ghost.id})
|
||||
assert assert_ok(resp, 200, "Health") == {"status": "ok"}
|
||||
|
||||
|
||||
@pytest.mark.spec("health", "Неизвестный токен")
|
||||
def test_unknown_token_is_ignored(api: Api) -> None:
|
||||
ghost = Actor.unregistered()
|
||||
for path in HEALTH:
|
||||
resp = api.request("GET", path, actor=ghost)
|
||||
|
||||
@@ -1,51 +1,81 @@
|
||||
"""Спек `identification`: заголовок `X-User-Id` лабы 1.
|
||||
"""Спек `identification`: Bearer на защищённых эндпоинтах с лабы 2.
|
||||
|
||||
Единственный модуль, который собирает заголовок сам, а не через
|
||||
`Actor.headers()`: проверяется именно заголовок. На лабе 2 модуль
|
||||
переписывается вместе со спеком.
|
||||
Единственный модуль, который собирает `Authorization` и `X-User-Id`
|
||||
сам, а не через `Actor.headers()`: проверяются именно заголовки.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
import secrets
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from api_client import API, Actor, Api
|
||||
from contract import assert_error, assert_ok, contract
|
||||
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_header(api: Api, alice: Actor) -> None:
|
||||
resp = api.request("GET", ME, headers={"X-User-Id": alice.id})
|
||||
@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_error(api.request("GET", ME), 401)
|
||||
assert_unauthorized(api.request("GET", ME), BEARER_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Не UUID")
|
||||
def test_not_uuid(api: Api) -> None:
|
||||
resp = api.request("GET", ME, headers={"X-User-Id": "not-a-uuid"})
|
||||
assert_error(resp, 401)
|
||||
@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", "Неизвестный пользователь")
|
||||
def test_unknown_user(api: Api) -> None:
|
||||
resp = api.request("GET", ME, headers={"X-User-Id": str(uuid.uuid4())})
|
||||
assert_error(resp, 401)
|
||||
@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_header(api: Api, chat: dict[str, Any]) -> None:
|
||||
assert_error(api.request("GET", f"{API}/chats/{chat['id']}"), 401)
|
||||
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_header(
|
||||
def test_invalid_field_without_token(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
@@ -55,16 +85,16 @@ def test_invalid_field_without_header(
|
||||
f"{API}/chats/{chat['id']}/messages",
|
||||
json={"text": ""},
|
||||
)
|
||||
assert_error(resp, 401)
|
||||
assert_unauthorized(resp, BEARER_CHALLENGE)
|
||||
assert api.all_messages(alice, chat["id"]) == []
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Битый JSON без заголовка")
|
||||
def test_malformed_json_without_header(
|
||||
def test_malformed_json_without_token(
|
||||
api: Api,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
# согласованное расхождение: битый JSON отклоняется до идентификации
|
||||
# согласованное расхождение: битый JSON отклоняется до аутентификации
|
||||
resp = api.request(
|
||||
"POST",
|
||||
f"{API}/chats/{chat['id']}/messages",
|
||||
@@ -75,12 +105,19 @@ def test_malformed_json_without_header(
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Схема в openapi.json")
|
||||
def test_security_scheme_in_openapi(api: Api) -> None:
|
||||
def test_security_schemes_in_openapi(api: Api) -> None:
|
||||
resp = api.request("GET", "/openapi.json")
|
||||
assert resp.status_code == 200
|
||||
served = resp.json()
|
||||
expected = contract()["components"]["securitySchemes"]["devUser"]
|
||||
schemes = served["components"]["securitySchemes"]
|
||||
expected = contract()["components"]["securitySchemes"]
|
||||
|
||||
assert served["components"]["securitySchemes"]["devUser"] == expected
|
||||
assert served["paths"][ME]["get"]["security"] == [{"devUser": []}]
|
||||
assert not served["paths"][f"{API}/users"]["post"].get("security")
|
||||
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")
|
||||
|
||||
@@ -9,7 +9,7 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api_client import API, Api, order_key, unique_username
|
||||
from api_client import API, Api, order_key, registration, unique_username
|
||||
from contract import assert_error, assert_ok
|
||||
|
||||
CLIENTS = 10
|
||||
@@ -113,7 +113,7 @@ def test_same_username_at_once(base_url: str) -> None:
|
||||
resp = own.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={"username": username, "display_name": f"Racer {number}"},
|
||||
json=registration(username, f"Racer {number}"),
|
||||
)
|
||||
return resp, start, time.monotonic()
|
||||
|
||||
|
||||
@@ -5,8 +5,13 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from api_client import API, Actor, Api, order_key
|
||||
from contract import assert_error
|
||||
from api_client import API, Actor, Api, order_key, registration
|
||||
from contract import (
|
||||
BASIC_CHALLENGE,
|
||||
BEARER_CHALLENGE,
|
||||
assert_error,
|
||||
assert_unauthorized,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("api-conventions", "Битый JSON")
|
||||
@@ -75,14 +80,27 @@ def test_duplicate_username(api: Api, alice: Actor) -> None:
|
||||
resp = api.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={
|
||||
"username": alice.user["username"],
|
||||
"display_name": "Другая Алиса",
|
||||
},
|
||||
json=registration(alice.username, "Другая Алиса"),
|
||||
)
|
||||
assert_error(resp, 409)
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "Неверный пароль")
|
||||
def test_wrong_password(api: Api, alice: Actor) -> None:
|
||||
resp = api.login_response(alice.username, alice.password + "-wrong")
|
||||
assert_unauthorized(resp, BASIC_CHALLENGE)
|
||||
assert "token" not in resp.json()
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "Выход")
|
||||
def test_logout(api: Api, alice: Actor) -> None:
|
||||
resp = api.logout(alice)
|
||||
assert resp.status_code == 204, resp.text
|
||||
assert resp.content == b""
|
||||
after = api.request("GET", f"{API}/users/me", actor=alice)
|
||||
assert_unauthorized(after, BEARER_CHALLENGE)
|
||||
|
||||
|
||||
def test_history_walk_across_pages(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Спек `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.request(
|
||||
"POST",
|
||||
f"{API}/chats/{chat['id']}/messages",
|
||||
actor=alice,
|
||||
json={"text": "после выхода"},
|
||||
)
|
||||
assert_unauthorized(resp, BEARER_CHALLENGE)
|
||||
assert api.all_messages(bob, chat["id"]) == []
|
||||
@@ -3,19 +3,25 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api_client import API, Actor, Api, unique_username
|
||||
from contract import assert_error, assert_ok
|
||||
from api_client import API, Actor, Api, registration, unique_username
|
||||
from contract import (
|
||||
BASIC_CHALLENGE,
|
||||
assert_error,
|
||||
assert_ok,
|
||||
assert_unauthorized,
|
||||
)
|
||||
|
||||
|
||||
def register_raw(
|
||||
api: Api,
|
||||
username: str,
|
||||
display_name: str = "User",
|
||||
password: str | None = None,
|
||||
) -> httpx.Response:
|
||||
return api.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={"username": username, "display_name": display_name},
|
||||
json=registration(username, display_name, password),
|
||||
)
|
||||
|
||||
|
||||
@@ -69,3 +75,42 @@ def test_display_name_blank(api: Api) -> None:
|
||||
def test_me_equals_registration(api: Api, alice: Actor) -> None:
|
||||
resp = api.request("GET", f"{API}/users/me", actor=alice)
|
||||
assert assert_ok(resp, 200, "User") == alice.user
|
||||
|
||||
|
||||
@pytest.mark.spec("users", "Нет пароля")
|
||||
def test_password_missing(api: Api) -> None:
|
||||
resp = api.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={"username": unique_username(), "display_name": "User"},
|
||||
)
|
||||
assert_error(resp, 400)
|
||||
|
||||
|
||||
@pytest.mark.spec("users", "Граница длины пароля")
|
||||
def test_password_length(api: Api) -> None:
|
||||
# длина — в code points: «ж» занимает два байта UTF-8
|
||||
for length, status in ((11, 400), (12, 201), (128, 201), (129, 400)):
|
||||
resp = register_raw(api, unique_username(), password="ж" * length)
|
||||
if status == 201:
|
||||
assert_ok(resp, 201, "User")
|
||||
else:
|
||||
assert_error(resp, status)
|
||||
|
||||
|
||||
@pytest.mark.spec("users", "Пароль из пробелов")
|
||||
def test_password_blank(api: Api) -> None:
|
||||
assert_error(register_raw(api, unique_username(), password=" " * 12), 400)
|
||||
# значимые пробелы по краям допустимы и не обрезаются
|
||||
actor = api.register(password=" spaced-pass ")
|
||||
assert api.login(actor.user, " spaced-pass ").user == actor.user
|
||||
|
||||
|
||||
@pytest.mark.spec("users", "Длинный пароль в UTF-8 целиком")
|
||||
def test_long_password_compared_whole(api: Api) -> None:
|
||||
password = "ж" * 128
|
||||
actor = api.register(password=password)
|
||||
changed = password[:-1] + "з"
|
||||
resp = api.login_response(actor.username, changed)
|
||||
assert_unauthorized(resp, BASIC_CHALLENGE)
|
||||
assert api.login(actor.user, password).user == actor.user
|
||||
|
||||
Reference in New Issue
Block a user