@@ -0,0 +1,99 @@
|
||||
"""Интеграционные тесты хранилища на настоящей PostgreSQL (уровень 4).
|
||||
|
||||
Выполняются ВНУТРИ контейнера приложения (там есть psycopg и доступ к БД по сети стенда):
|
||||
make db-test == docker compose --profile tools run --rm db-test
|
||||
|
||||
Что проверяется:
|
||||
- повторный запуск миграций ничего не меняет;
|
||||
- составная операция «создать чат» откатывается целиком, если упала на середине;
|
||||
- одновременная регистрация одного username даёт ровно одного пользователя;
|
||||
- сама база не даёт записать сообщение от не-участника (внешний ключ).
|
||||
"""
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
from unittest import mock
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors as pg_errors
|
||||
|
||||
from messenger import config, db
|
||||
from messenger.errors import Conflict, InvalidRequest
|
||||
from messenger.store import PostgresStore
|
||||
|
||||
|
||||
class StoreIntegrationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
config.validate()
|
||||
db.migrate()
|
||||
cls.pool = db.create_pool()
|
||||
cls.pool.open(wait=True)
|
||||
cls.store = PostgresStore(cls.pool)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.pool.close()
|
||||
|
||||
def scalar(self, sql, *params):
|
||||
with self.pool.connection() as conn:
|
||||
return conn.execute(sql, params).fetchone()[0]
|
||||
|
||||
def new_user(self):
|
||||
return self.store.create_user("db_" + uuid.uuid4().hex[:12], "DB test", "not-a-real-hash")
|
||||
|
||||
def test_migrations_rerun_is_noop(self):
|
||||
versions = self.scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations")
|
||||
users = self.scalar("SELECT count(*) FROM users")
|
||||
self.assertEqual(db.migrate(), []) # второй прогон: применять нечего
|
||||
self.assertEqual(self.scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations"), versions)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM users"), users)
|
||||
print(f"\n schema_migrations: {versions}; повторный migrate() ничего не применил")
|
||||
|
||||
def test_create_chat_rolls_back_when_failing_midway(self):
|
||||
alice = self.new_user()
|
||||
ghost = str(uuid.uuid4()) # такого пользователя нет
|
||||
title = "rollback-" + uuid.uuid4().hex[:8]
|
||||
# Отключаем предварительную проверку участников, чтобы ошибка случилась ВНУТРИ транзакции:
|
||||
# строка чата уже вставлена, а вставка участника-призрака нарушает внешний ключ.
|
||||
with mock.patch.object(PostgresStore, "_check_members_exist", staticmethod(lambda conn, members: None)):
|
||||
with self.assertRaises(InvalidRequest):
|
||||
self.store.create_chat(alice.id, title, [alice.id, ghost])
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chats WHERE title = %s", title), 0)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chat_members WHERE user_id = %s", uuid.UUID(alice.id)), 0)
|
||||
print("\n чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось")
|
||||
|
||||
def test_concurrent_registration_has_one_winner(self):
|
||||
username = "dbrace_" + uuid.uuid4().hex[:10]
|
||||
threads, barrier, results = 20, threading.Barrier(20), []
|
||||
|
||||
def register():
|
||||
barrier.wait()
|
||||
try:
|
||||
self.store.create_user(username, "Race", "not-a-real-hash")
|
||||
results.append("created")
|
||||
except Conflict:
|
||||
results.append("conflict")
|
||||
|
||||
workers = [threading.Thread(target=register) for _ in range(threads)]
|
||||
for w in workers:
|
||||
w.start()
|
||||
for w in workers:
|
||||
w.join()
|
||||
self.assertEqual(results.count("created"), 1)
|
||||
self.assertEqual(results.count("conflict"), threads - 1)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM users WHERE username = %s", username), 1)
|
||||
print(f"\n {threads} параллельных create_user: 1 создан, {threads - 1} получили Conflict (409)")
|
||||
|
||||
def test_database_rejects_message_from_non_member(self):
|
||||
alice, mallory = self.new_user(), self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "fk", [alice.id])
|
||||
with self.assertRaises(pg_errors.ForeignKeyViolation):
|
||||
with psycopg.connect(config.DATABASE_URL) as conn:
|
||||
conn.execute("INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, 'x')",
|
||||
(uuid.uuid4(), uuid.UUID(chat.id), uuid.UUID(mallory.id)))
|
||||
print("\n INSERT сообщения от не-участника напрямую в БД: ForeignKeyViolation")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Демонстрация для защиты (шаг 1 сценария): пользователи, вход, чат, сообщения, logout.
|
||||
|
||||
Запуск: make demo (печатает шаги; пароли и токены не выводятся)
|
||||
"""
|
||||
from helpers import Client, read_history, run
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
api.call("GET", "/health/ready", schema="Health")
|
||||
print("1. /health/ready -> 200: API запущен, PostgreSQL доступна, миграции применены")
|
||||
alice, bob, eve, chat = api.bootstrap() # регистрация с паролем + вход через Basic у каждого
|
||||
for name, actor in (("alice", alice), ("bob", bob), ("eve", eve)):
|
||||
print(f"2. зарегистрирован {name}: {actor['user']['username']}, вход через Basic -> Bearer-токен")
|
||||
print(f"3. alice создала чат {chat['id']} с bob (eve не участник)")
|
||||
api.message(alice, chat, "Привет, Боб! Это сообщение лежит в PostgreSQL")
|
||||
api.message(bob, chat, "Привет, Алиса! Переживёт перезапуск")
|
||||
history, pages = read_history(api, bob, chat["id"], limit=1)
|
||||
print(f"4. история чата (по 1 сообщению на страницу, страниц: {pages}):")
|
||||
names = {alice["id"]: "alice", bob["id"]: "bob"}
|
||||
for m in history:
|
||||
print(f" {m['created_at']} {names[m['sender_id']]}: {m['text']}")
|
||||
api.call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, actor=eve)
|
||||
print("5. eve читает чужой чат -> 404 (существование чата не раскрывается)")
|
||||
api.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
|
||||
print("6. только X-User-Id без токена -> 401 (lab1-способ больше не работает)")
|
||||
api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
print("7. alice logout -> 204, тот же токен -> 401")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Отказ зависимости (уровень 4). Запуск: make failure-valkey или make failure-postgres
|
||||
|
||||
Тест сам останавливает указанный контейнер (docker compose stop), проверяет поведение API
|
||||
и запускает контейнер обратно (docker compose start). Volumes не трогаются.
|
||||
|
||||
valkey — кэш недоступен: API обходит его и работает через PostgreSQL; logout действует сразу.
|
||||
postgres — источник истины недоступен: API отвечает ограниченной ошибкой 503 (без деталей),
|
||||
/health/ready = 503, аноним и неизвестный токен НЕ получают успешный ответ.
|
||||
После запуска БД прежний токен и данные снова доступны.
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import Client, basic, check, compose, read_history, run, wait_ready
|
||||
|
||||
|
||||
def timed(fn):
|
||||
started = time.monotonic()
|
||||
result = fn()
|
||||
return result, (time.monotonic() - started) * 1000
|
||||
|
||||
|
||||
def valkey_down(api, alice, bob, chat):
|
||||
ready, ms = timed(lambda: api.call("GET", "/health/ready", schema="Health"))
|
||||
print(f"/health/ready -> 200 ({ms:.0f} ms): Valkey не критичен, API готов")
|
||||
_, ms = timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice, schema="User"))
|
||||
print(f"existing token: GET /users/me -> 200 ({ms:.0f} ms), сессия проверена по PostgreSQL (этот запрос и обнаружил сбой кэша)")
|
||||
sent = api.message(bob, chat, "во время отказа Valkey")["json"]
|
||||
history, _ = read_history(api, alice, chat["id"])
|
||||
check(sent["id"] in [m["id"] for m in history], "message written during Valkey outage is missing")
|
||||
print("POST message -> 201, история читается")
|
||||
carol = api.user("carol") # регистрация и вход тоже работают без кэша
|
||||
print("register + login new user -> 201")
|
||||
api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=carol)
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=carol)
|
||||
print("logout -> 204, затем тот же токен -> 401 (отзыв записан в PostgreSQL)")
|
||||
latencies = [timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice))[1] for _ in range(10)]
|
||||
print(f"10 x GET /users/me без кэша: max {max(latencies):.0f} ms (кэш не ждём на каждом запросе)")
|
||||
check(max(latencies) < 1000, "requests must not wait for the dead cache on every call")
|
||||
# Фоновая проверка Valkey идёт раз в 5 с. Ждём дольше и убеждаемся, что запросы её не ждут.
|
||||
time.sleep(6)
|
||||
latencies = [timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice))[1] for _ in range(10)]
|
||||
print(f"через 6 с, ещё 10 x GET /users/me: max {max(latencies):.0f} ms (повторные попытки — в фоне)")
|
||||
check(max(latencies) < 1000, "periodic reconnect attempts must not block user requests")
|
||||
return carol
|
||||
|
||||
|
||||
def postgres_down(api, alice, chat):
|
||||
api.call("GET", "/health/live", schema="Health")
|
||||
print("/health/live -> 200: процесс жив")
|
||||
_, ms = timed(lambda: api.call("GET", "/health/ready", 503))
|
||||
print(f"/health/ready -> 503 ({ms:.0f} ms): без PostgreSQL обслуживать нельзя")
|
||||
for method, path in (("GET", "/api/v1/chats"), ("GET", f"/api/v1/chats/{chat['id']}/messages")):
|
||||
error = api.call(method, path, 503, actor=alice)["json"]["error"]
|
||||
check(error["code"] == "unavailable", "expected unavailable error code")
|
||||
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 503, actor=alice, body={"text": "не сохранится"})
|
||||
print("бизнес-запросы с действующим токеном -> 503 unavailable (без SQL и stack trace в ответе)")
|
||||
api.call("GET", "/api/v1/users/me", 401)
|
||||
print("без токена -> 401: аноним не становится доверенным")
|
||||
status = api.call("GET", "/api/v1/users/me", [401, 503], headers={"Authorization": "Bearer " + "x" * 43})["status"]
|
||||
print(f"неизвестный токен -> {status}: не подтверждается ни кэшем, ни базой")
|
||||
status = api.call("POST", "/api/v1/auth/sessions", [401, 503],
|
||||
headers={"Authorization": basic("nobody", "Some-password-1")})["status"]
|
||||
print(f"вход -> {status}: сессию без базы не выдаём")
|
||||
api.call("POST", "/api/v1/users", 503,
|
||||
body={"username": "pg_" + uuid.uuid4().hex[:10], "display_name": "x", "password": "Pg-down-password"})
|
||||
print("регистрация -> 503")
|
||||
|
||||
|
||||
def main():
|
||||
target = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
check(target in ("valkey", "postgres"), "usage: dependency_failure.py valkey|postgres")
|
||||
api = Client()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
before = api.message(alice, chat, "до отказа " + target)["json"]
|
||||
|
||||
print(f"stopping {target} (docker compose stop {target})")
|
||||
compose("stop", target)
|
||||
try:
|
||||
if target == "valkey":
|
||||
carol = valkey_down(api, alice, bob, chat)
|
||||
else:
|
||||
postgres_down(api, alice, chat)
|
||||
finally:
|
||||
print(f"starting {target} again")
|
||||
compose("start", target)
|
||||
|
||||
wait_ready(api)
|
||||
history, _ = read_history(api, alice, chat["id"])
|
||||
check(before in history, "message confirmed before the outage is lost or changed")
|
||||
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
if target == "valkey":
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=carol) # отозванный токен не «воскрес» из кэша
|
||||
print("after recovery: прежний токен работает, подтверждённые сообщения на месте")
|
||||
print(f"PASS: {target} outage handled without trusting anonymous requests")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Проверка истечения сессии при коротком TTL (уровень 4). Запуск: make expiry
|
||||
|
||||
Нужен второй экземпляр API с SESSION_TTL_SECONDS=2 (сервис api-short-ttl на порту 8081,
|
||||
make expiry поднимает его сам). База общая с основным API.
|
||||
|
||||
Сценарий: вход -> токен работает (и попадает в кэш Valkey) -> ждём истечения ->
|
||||
токен отклоняется с 401 и на коротком, и на основном API. Значит, срок жизни — свойство
|
||||
сессии в PostgreSQL, а кэш не продлевает её.
|
||||
"""
|
||||
import datetime as dt
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import Client, check, login, run
|
||||
|
||||
|
||||
def main():
|
||||
short = Client(os.environ.get("BASE_URL_TTL", "http://127.0.0.1:8081"))
|
||||
main_api = Client()
|
||||
body = {"username": "ttl_" + uuid.uuid4().hex[:12], "display_name": "TTL", "password": "Ttl-password-123"}
|
||||
short.call("POST", "/api/v1/users", 201, body=body, schema="User")
|
||||
session = login(short, body["username"], body["password"])
|
||||
auth = {"Authorization": "Bearer " + session["token"]}
|
||||
expires_at = dt.datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
ttl = (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
print(f"session issued by short-TTL API, expires in {ttl:.2f}s")
|
||||
check(0 < ttl <= 3, "short-TTL instance must issue ~2 second sessions")
|
||||
|
||||
for api in (short, short, main_api): # два раза подряд: второй ответ уже из кэша
|
||||
api.call("GET", "/api/v1/users/me", 200, headers=auth, schema="User")
|
||||
print("before expiry: GET /users/me -> 200 (short API twice, main API once)")
|
||||
|
||||
time.sleep(max(0.0, (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()) + 1.0)
|
||||
for api in (short, main_api):
|
||||
api.call("GET", "/api/v1/users/me", 401, headers=auth) # клиент проверяет WWW-Authenticate: Bearer
|
||||
print("after expiry: GET /users/me -> 401 on both instances")
|
||||
print("PASS: session expired after SESSION_TTL_SECONDS; cache did not extend it")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Общие помощники для собственных тестов.
|
||||
|
||||
Переиспользуем публичный HTTP-клиент курса (tests/client.py), а не пишем свой:
|
||||
он уже проверяет X-Request-Id, формат ошибок, WWW-Authenticate и схемы ответов из контракта.
|
||||
С lab2 клиент сам регистрирует пользователя с паролем, входит через Basic
|
||||
и подставляет Bearer-токен (токен живёт только в памяти теста и не печатается).
|
||||
"""
|
||||
import base64
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, Failure, check, run # noqa: E402 (импорт после правки sys.path)
|
||||
|
||||
__all__ = ["Client", "Failure", "check", "run", "read_history", "basic", "login", "compose", "wait_ready", "ROOT"]
|
||||
|
||||
|
||||
def read_history(api, actor, chat_id, limit=100):
|
||||
"""Читает всю историю чата по страницам. Возвращает (сообщения, число_страниц)."""
|
||||
items, pages, cursor = [], 0, None
|
||||
while True:
|
||||
query = f"?limit={limit}" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||||
page = api.call("GET", f"/api/v1/chats/{chat_id}/messages{query}",
|
||||
actor=actor, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
pages += 1
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items, pages
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
"""Значение заголовка Authorization: Basic base64(username:password), пароль в UTF-8."""
|
||||
return "Basic " + base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def login(api, username, password, expected=201):
|
||||
"""POST /auth/sessions; при успехе возвращает тело Session (токен — только в памяти)."""
|
||||
schema = "Session" if expected == 201 else None
|
||||
return api.call("POST", "/api/v1/auth/sessions", expected,
|
||||
headers={"Authorization": basic(username, password)}, schema=schema)["json"]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
"""docker compose <args> из корня репозитория; вывод скрыт (там могут быть имена/секреты)."""
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(api, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
api.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, f"API не стал готов за {seconds} с")
|
||||
time.sleep(0.5)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Проверка гонок (уровень 4). Запуск: make race
|
||||
|
||||
1. 10 клиентов одновременно отправляют по 10 сообщений в один чат:
|
||||
в истории ровно 100 сообщений, все id уникальны, ни один текст не потерян.
|
||||
2. 20 клиентов одновременно регистрируют ОДИН И ТОТ ЖЕ username:
|
||||
ровно один получает 201, остальные 409; в базе один такой пользователь.
|
||||
Защита — уникальный индекс users.username в PostgreSQL, а не проверка в коде.
|
||||
"""
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from helpers import Client, check, read_history, run
|
||||
|
||||
CLIENTS = 10
|
||||
PER_CLIENT = 10
|
||||
REGISTRATIONS = 20
|
||||
|
||||
|
||||
def concurrent_messages(api):
|
||||
users = [api.user(f"race{i}") for i in range(CLIENTS)]
|
||||
chat = api.call("POST", "/api/v1/chats", 201, actor=users[0], schema="Chat",
|
||||
body={"title": "race", "member_ids": [u["id"] for u in users]})["json"]
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
start_together = threading.Barrier(CLIENTS) # все потоки стартуют одновременно
|
||||
|
||||
def send_all(index):
|
||||
client = Client() # у каждого «клиента» свои HTTP-соединения
|
||||
start_together.wait()
|
||||
for n in range(PER_CLIENT):
|
||||
client.call("POST", path, 201, actor=users[index], body={"text": f"client-{index}-msg-{n}"})
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
||||
list(pool.map(send_all, range(CLIENTS))) # list() пробрасывает ошибки из потоков
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
history, pages = read_history(api, users[0], chat["id"], limit=25)
|
||||
expected = {f"client-{i}-msg-{n}" for i in range(CLIENTS) for n in range(PER_CLIENT)}
|
||||
print(f"messages: sent {CLIENTS * PER_CLIENT} from {CLIENTS} parallel clients in {elapsed:.2f}s")
|
||||
print(f"messages: read {len(history)} in {pages} pages, unique ids: {len({m['id'] for m in history})}")
|
||||
check(len(history) == CLIENTS * PER_CLIENT, "wrong number of messages")
|
||||
check(len({m["id"] for m in history}) == len(history), "duplicate message ids")
|
||||
check({m["text"] for m in history} == expected, "lost or corrupted message texts")
|
||||
print("PASS: 100 concurrent messages stored without loss or duplicates")
|
||||
|
||||
|
||||
def concurrent_registration():
|
||||
username = "race_" + uuid.uuid4().hex[:12]
|
||||
start_together = threading.Barrier(REGISTRATIONS)
|
||||
|
||||
def register(index):
|
||||
client = Client()
|
||||
body = {"username": username, "display_name": f"Участник {index}", "password": f"Race-password-{index:03d}"}
|
||||
start_together.wait()
|
||||
return client.call("POST", "/api/v1/users", [201, 409], body=body)["status"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=REGISTRATIONS) as pool:
|
||||
statuses = list(pool.map(register, range(REGISTRATIONS)))
|
||||
created, conflicts = statuses.count(201), statuses.count(409)
|
||||
print(f"registration: {REGISTRATIONS} parallel requests for one username -> 201 x{created}, 409 x{conflicts}")
|
||||
check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win")
|
||||
print("PASS: concurrent registration of the same username created exactly one user")
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
concurrent_messages(api)
|
||||
concurrent_registration()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Собственные тесты API (перенесены из lab1, переведены на пароль и Bearer).
|
||||
|
||||
Тесты «чёрного ящика»: шлют настоящие HTTP-запросы на уже запущенный стенд
|
||||
(BASE_URL, по умолчанию http://127.0.0.1:8080 из Makefile).
|
||||
Запуск вместе с test_auth.py одной командой: make student-test
|
||||
"""
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from helpers import Client, read_history
|
||||
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
class MessengerApiTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap() # eve не состоит в чате
|
||||
|
||||
def messages_path(self, chat_id):
|
||||
return f"/api/v1/chats/{chat_id}/messages"
|
||||
|
||||
def send(self, actor, chat_id, text, expected=201):
|
||||
schema = "Message" if expected == 201 else None # клиент разбирает JSON успешного ответа только со схемой
|
||||
return self.api.call("POST", self.messages_path(chat_id), expected, actor=actor,
|
||||
body={"text": text}, schema=schema)
|
||||
|
||||
def new_chat(self):
|
||||
body = {"title": "Тест", "member_ids": [self.alice["id"], self.bob["id"]]}
|
||||
return self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, body=body, schema="Chat")["json"]
|
||||
|
||||
def test_malformed_json_returns_400(self):
|
||||
json_header = {"Content-Type": "application/json"}
|
||||
for raw in (b'{"username": "abc",', b"not json", b""):
|
||||
self.api.call("POST", "/api/v1/users", 400, raw=raw, headers=json_header)
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 400,
|
||||
actor=self.alice, raw=raw, headers=json_header)
|
||||
|
||||
def test_wrong_types_and_extra_fields_return_400(self):
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": 123, "display_name": "x", "password": PASSWORD})
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "valid_name", "display_name": "x", "password": PASSWORD, "is_admin": True})
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
|
||||
# Отправителя нельзя подставить: он берётся из сессии.
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 400, actor=self.alice,
|
||||
body={"text": "hi", "sender_id": self.bob["id"]})
|
||||
|
||||
def test_outsider_gets_404_for_foreign_chat(self):
|
||||
chat_id = self.chat["id"]
|
||||
self.api.call("GET", f"/api/v1/chats/{chat_id}", 404, actor=self.eve)
|
||||
self.api.call("GET", self.messages_path(chat_id), 404, actor=self.eve)
|
||||
self.send(self.eve, chat_id, "чужое", expected=404)
|
||||
# Несуществующий чат выглядит так же, как чужой: существование не раскрывается.
|
||||
self.api.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, actor=self.eve)
|
||||
|
||||
def test_auth_checked_before_access_and_body(self):
|
||||
# Без токена — всегда 401, даже если тело кривое или чат чужой: сначала «кто ты».
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 401, raw=b"not json",
|
||||
headers={"Content-Type": "application/json"})
|
||||
self.api.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
|
||||
|
||||
def test_empty_blank_and_too_long_messages_return_400(self):
|
||||
for text in ("", " ", "\n\t "):
|
||||
self.send(self.alice, self.chat["id"], text, expected=400)
|
||||
self.send(self.alice, self.chat["id"], "я" * 4001, expected=400)
|
||||
self.send(self.alice, self.chat["id"], "я" * 4000) # ровно на границе — можно
|
||||
|
||||
def test_duplicate_username_returns_409(self):
|
||||
body = {"username": "dup_" + uuid.uuid4().hex[:12], "display_name": "Первый", "password": PASSWORD}
|
||||
self.api.call("POST", "/api/v1/users", 201, body=body)
|
||||
self.api.call("POST", "/api/v1/users", 409, body=dict(body, display_name="Второй"))
|
||||
|
||||
def test_unicode_roundtrip(self):
|
||||
text = "Привет 👋 你好 ﷽ é"
|
||||
sent = self.send(self.alice, self.chat["id"], text)["json"]
|
||||
self.assertEqual(sent["text"], text)
|
||||
history, _ = read_history(self.api, self.bob, self.chat["id"])
|
||||
self.assertIn(text, [m["text"] for m in history])
|
||||
# Длина считается в символах Unicode: 100 эмодзи можно, 101 — нет.
|
||||
name = "n_" + uuid.uuid4().hex[:12]
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": name, "display_name": "👋" * 101, "password": PASSWORD})
|
||||
self.api.call("POST", "/api/v1/users", 201,
|
||||
body={"username": name, "display_name": "👋" * 100, "password": PASSWORD})
|
||||
|
||||
def test_pagination_walks_several_pages(self):
|
||||
chat = self.new_chat()
|
||||
sent = [self.send(self.alice, chat["id"], f"msg {i}")["json"] for i in range(7)]
|
||||
history, pages = read_history(self.api, self.bob, chat["id"], limit=3)
|
||||
self.assertEqual(pages, 3) # 3 + 3 + 1
|
||||
self.assertEqual([m["id"] for m in history], [m["id"] for m in sent]) # без потерь, дублей и перестановок
|
||||
|
||||
def test_chat_list_pagination(self):
|
||||
created = [self.new_chat()["id"] for _ in range(3)]
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
|
||||
page = self.api.call("GET", "/api/v1/chats" + query, actor=self.bob, schema="ChatPage")["json"]
|
||||
seen += [c["id"] for c in page["items"]]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(len(seen), len(set(seen)))
|
||||
self.assertEqual(seen[-3:], created) # новые чаты в конце, порядок (created_at, id)
|
||||
|
||||
def test_bad_cursor_returns_400(self):
|
||||
chat_a, chat_b = self.new_chat(), self.new_chat()
|
||||
for i in range(2):
|
||||
self.send(self.alice, chat_a["id"], f"a{i}")
|
||||
first = self.api.call("GET", self.messages_path(chat_a["id"]) + "?limit=1",
|
||||
actor=self.alice, schema="MessagePage")["json"]
|
||||
foreign_cursor = first["next_cursor"]
|
||||
self.api.call("GET", self.messages_path(chat_b["id"]) + "?cursor=" + foreign_cursor, 400, actor=self.alice)
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?cursor=garbage", 400, actor=self.alice)
|
||||
# Курсор правильной формы, но с испорченным временем/UUID: 400, а не ошибка БД (500).
|
||||
import base64
|
||||
import json
|
||||
for bad in (["messages:" + chat_a["id"], "not-a-time", str(uuid.uuid4())],
|
||||
["messages:" + chat_a["id"], "2026-01-01T00:00:00.000000Z", "not-a-uuid"]):
|
||||
forged = base64.urlsafe_b64encode(json.dumps(bad).encode()).decode()
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?cursor=" + forged, 400, actor=self.alice)
|
||||
for limit in ("0", "101", "abc"):
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?limit=" + limit, 400, actor=self.alice)
|
||||
|
||||
def test_chat_membership_rules(self):
|
||||
alice, bob = self.alice["id"], self.bob["id"]
|
||||
for members in ([bob], [alice, alice], [alice, str(uuid.uuid4())]): # без себя, дубль, неизвестный
|
||||
self.api.call("POST", "/api/v1/chats", 400, actor=self.alice, body={"title": "x", "member_ids": members})
|
||||
chats = self.api.call("GET", "/api/v1/chats?limit=100", actor=self.eve, schema="ChatPage")["json"]
|
||||
self.assertNotIn(self.chat["id"], [c["id"] for c in chats["items"]])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Собственные тесты аутентификации (уровень 4): пароль, Basic -> Bearer, logout.
|
||||
|
||||
Запуск: make student-test (вместе с test_api.py)
|
||||
"""
|
||||
import base64
|
||||
import datetime as dt
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from helpers import Client, basic, login
|
||||
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
def iso(value):
|
||||
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
class AuthTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
|
||||
def register(self, password=PASSWORD, expected=201):
|
||||
body = {"username": "a_" + uuid.uuid4().hex[:12], "display_name": "Auth", "password": password}
|
||||
user = self.api.call("POST", "/api/v1/users", expected, body=body,
|
||||
schema="User" if expected == 201 else None)["json"]
|
||||
return body, user
|
||||
|
||||
def me(self, token, expected=200):
|
||||
return self.api.call("GET", "/api/v1/users/me", expected, headers={"Authorization": "Bearer " + token},
|
||||
schema="User" if expected == 200 else None)
|
||||
|
||||
def test_login_returns_opaque_token_with_expiry(self):
|
||||
body, user = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
self.assertEqual(session["user"], user)
|
||||
token = session["token"]
|
||||
self.assertGreaterEqual(len(token), 43) # 32 случайных байта в base64url
|
||||
self.assertNotIn(body["username"], token)
|
||||
self.assertNotIn(user["id"], token)
|
||||
# Обычный стенд: TTL не меньше 300 с (по умолчанию 3600).
|
||||
left = iso(session["expires_at"]) - dt.datetime.now(dt.timezone.utc)
|
||||
self.assertGreater(left.total_seconds(), 290)
|
||||
self.assertEqual(self.me(token)["json"], user)
|
||||
|
||||
def test_user_never_contains_password(self):
|
||||
body, user = self.register()
|
||||
self.assertEqual(set(user), {"id", "username", "display_name", "created_at"})
|
||||
self.assertNotIn(body["password"], str(user))
|
||||
|
||||
def test_wrong_password_and_unknown_user_look_the_same(self):
|
||||
body, _ = self.register()
|
||||
wrong = login(self.api, body["username"], "Wrong-password-000", expected=401)
|
||||
unknown = login(self.api, "nobody_" + uuid.uuid4().hex[:8], body["password"], expected=401)
|
||||
# Одинаковый код и текст: по ответу нельзя узнать, существует ли username.
|
||||
self.assertEqual(wrong["error"]["code"], unknown["error"]["code"])
|
||||
self.assertEqual(wrong["error"]["message"], unknown["error"]["message"])
|
||||
|
||||
def test_malformed_basic_returns_401(self):
|
||||
path = "/api/v1/auth/sessions"
|
||||
no_colon = base64.b64encode(b"just_username").decode()
|
||||
for header in (None, "Basic", "Basic !!!not-base64!!!", "Basic " + no_colon, "Bearer something"):
|
||||
headers = {} if header is None else {"Authorization": header}
|
||||
self.api.call("POST", path, 401, headers=headers) # клиент проверяет WWW-Authenticate: Basic
|
||||
|
||||
def test_password_with_colon_and_unicode(self):
|
||||
password = "пароль:с:двоеточием 👋"
|
||||
body, user = self.register(password=password)
|
||||
session = login(self.api, body["username"], password)
|
||||
self.assertEqual(session["user"], user)
|
||||
|
||||
def test_password_length_rules(self):
|
||||
self.register(password="x" * 11, expected=400)
|
||||
self.register(password="x" * 129, expected=400)
|
||||
self.register(password=" " * 12, expected=400) # только пробелы — нельзя
|
||||
self.register(password="x" * 12)
|
||||
self.register(password="я" * 128) # 128 символов Unicode — можно
|
||||
|
||||
def test_bearer_required_on_business_endpoints(self):
|
||||
body, user = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
for headers in ({}, {"Authorization": basic(body["username"], body["password"])},
|
||||
{"X-User-Id": user["id"]}, {"Authorization": "Bearer " + "A" * 43},
|
||||
{"Authorization": "Bearer"}, {"Authorization": "Token " + session["token"]}):
|
||||
self.api.call("GET", "/api/v1/users/me", 401, headers=headers) # WWW-Authenticate: Bearer
|
||||
# Схема нечувствительна к регистру (RFC 7235).
|
||||
self.api.call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + session["token"]})
|
||||
|
||||
def test_x_user_id_does_not_change_identity(self):
|
||||
body, user = self.register()
|
||||
_, other = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
me = self.api.call("GET", "/api/v1/users/me", headers={
|
||||
"Authorization": "Bearer " + session["token"], "X-User-Id": other["id"]}, schema="User")["json"]
|
||||
self.assertEqual(me["id"], user["id"])
|
||||
|
||||
def test_logout_revokes_only_current_session(self):
|
||||
body, _ = self.register()
|
||||
first = login(self.api, body["username"], body["password"])["token"]
|
||||
second = login(self.api, body["username"], body["password"])["token"]
|
||||
self.me(first) # запись попадает в кэш Valkey
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, headers={"Authorization": "Bearer " + first})
|
||||
self.me(first, expected=401) # кэш инвалидирован: отозванный токен не принимается сразу
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 401, headers={"Authorization": "Bearer " + first})
|
||||
self.me(second) # другая сессия того же пользователя продолжает работать
|
||||
|
||||
def test_relogin_after_logout(self):
|
||||
body, _ = self.register()
|
||||
token = login(self.api, body["username"], body["password"])["token"]
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, headers={"Authorization": "Bearer " + token})
|
||||
again = login(self.api, body["username"], body["password"])["token"]
|
||||
self.assertNotEqual(token, again)
|
||||
self.me(again)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user