2: PostgreSQL, вход Basic -> Bearer, сессии в Redis

This commit is contained in:
kalibr456
2026-10-09 02:35:30 +03:00
parent 65003b6119
commit 8149a608f8
38 changed files with 2228 additions and 18 deletions
+182
View File
@@ -0,0 +1,182 @@
"""Общий код для собственных тестов: маленький HTTP-клиент и работа со стендом.
Только стандартная библиотека Python, ничего ставить не нужно.
Тесты ходят на BASE_URL (по умолчанию http://127.0.0.1:8080) и управляют
контейнерами через `docker compose`, запуская его прямо из Python.
Поэтому всё работает одинаково в PowerShell, cmd и Git Bash на Windows.
Вывод тестов — только латиница, чтобы консоль Windows не ломала кодировку.
"""
import base64
import hashlib
import json
import os
import subprocess
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
PASSWORD = "Test-password-123"
class Response:
def __init__(self, status, headers, data):
self.status = status
self.headers = {name.lower(): value for name, value in headers.items()}
self.data = data
try:
self.json = json.loads(data.decode("utf-8")) if data else None
except ValueError:
self.json = None
def check(condition, message):
if not condition:
raise AssertionError(message)
def call(method, path, expected=200, *, body=None, raw=None, token=None, headers=None):
"""HTTP-запрос к API. expected — код или кортеж кодов, иначе AssertionError.
Заодно проверяет то, что контракт требует от любого ответа:
X-Request-Id, единый формат ошибки, WWW-Authenticate у 401.
"""
all_headers = dict(headers or {})
data = raw
if body is not None:
data = json.dumps(body).encode("utf-8")
if data is not None:
all_headers.setdefault("Content-Type", "application/json")
if token is not None:
all_headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
try:
with urllib.request.urlopen(request, timeout=30) as reply:
response = Response(reply.status, reply.headers, reply.read())
except urllib.error.HTTPError as error:
response = Response(error.code, error.headers, error.read())
expected = expected if isinstance(expected, tuple) else (expected,)
check(response.status in expected,
f"{method} {path}: expected {expected}, got {response.status} {response.data[:200]!r}")
request_id = response.headers.get("x-request-id")
check(request_id, f"{method} {path}: no X-Request-Id header")
if response.status >= 400:
error = (response.json or {}).get("error") or {}
check(error.get("code") and error.get("message"), f"{method} {path}: wrong error format")
check(error.get("request_id") == request_id, f"{method} {path}: request_id differs from header")
if response.status == 401:
check(response.headers.get("www-authenticate"), f"{method} {path}: 401 without WWW-Authenticate")
return response
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(username, password, expected=201):
return call("POST", "/api/v1/auth/sessions", expected, headers={"Authorization": basic(username, password)})
def new_user(prefix="user", password=PASSWORD):
"""Регистрирует пользователя и входит. Возвращает dict: id, username, password, token."""
username = f"{prefix}_{uuid.uuid4().hex[:10]}"
user = call("POST", "/api/v1/users", 201,
body={"username": username, "display_name": prefix.title(), "password": password}).json
session = login(username, password).json
return {**user, "password": password, "token": session["token"]}
def new_chat(owner, *others, title="Test chat"):
member_ids = [owner["id"]] + [user["id"] for user in others]
return call("POST", "/api/v1/chats", 201, token=owner["token"],
body={"title": title, "member_ids": member_ids}).json
def send(user, chat_id, text, expected=201):
return call("POST", f"/api/v1/chats/{chat_id}/messages", expected, token=user["token"], body={"text": text})
def read_history(user, chat_id, limit=100):
"""Вся история чата по страницам. Возвращает (сообщения, число_страниц)."""
items, pages, cursor = [], 0, None
while True:
query = f"?limit={limit}" + (f"&cursor={urllib.parse.quote(cursor, safe='')}" if cursor else "")
page = call("GET", f"/api/v1/chats/{chat_id}/messages{query}", 200, token=user["token"]).json
items += page["items"]
pages += 1
cursor = page["next_cursor"]
if cursor is None:
return items, pages
def wait_ready(seconds=90):
deadline = time.monotonic() + seconds
while True:
try:
with urllib.request.urlopen(BASE_URL + "/health/ready", timeout=3) as reply:
if reply.status == 200:
return
except (urllib.error.URLError, OSError):
pass
check(time.monotonic() < deadline, f"API is not ready after {seconds} s")
time.sleep(0.5)
def compose(*args, env=None):
"""docker compose <args> в корне репозитория. Вывод скрыт: в нём могут быть пути к секретам."""
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def compose_output(*args):
"""docker compose <args> и его вывод (для logs, ps)."""
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, check=True)
return result.stdout.decode("utf-8", "replace") + result.stderr.decode("utf-8", "replace")
def redis_cli(*args):
"""redis-cli внутри контейнера redis. Пароль читается там же из секрета и не попадает в вывод."""
command = "REDISCLI_AUTH=\"$(sed -n 's/^requirepass //p' /run/secrets/redis_auth)\" redis-cli " + " ".join(args)
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "sh", "-c", command],
cwd=ROOT, capture_output=True, check=True)
return result.stdout.decode("utf-8", "replace").strip()
def session_key(token):
"""Ключ сессии в Redis, как его считает auth.py: session:<SHA-256 токена>."""
return "session:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
def psql(sql):
"""Выполняет SQL в контейнере postgres. Возвращает (код выхода, вывод, текст ошибки).
Значения в SQL тестов — только сгенерированные самим тестом (uuid), не ввод пользователя.
"""
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger", "-X", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-c", sql],
cwd=ROOT, capture_output=True, check=False,
)
output = result.stdout.decode("utf-8", "replace").strip()
error = result.stderr.decode("utf-8", "replace").strip()
return result.returncode, output, error
def run_tests(tests):
"""Запускает функции-тесты по очереди. Код выхода 1, если хоть один упал."""
failed = 0
for test in tests:
try:
test()
except Exception as exc: # noqa: BLE001 — нужно напечатать любую ошибку теста
failed += 1
print(f"FAIL: {test.__name__}: {exc}")
print(f"{len(tests) - failed} passed, {failed} failed")
raise SystemExit(1 if failed else 0)
+34
View File
@@ -0,0 +1,34 @@
"""EXPLAIN (ANALYZE, BUFFERS) для истории сообщений на 20 000 сообщений.
python student-tests/explain.py
Отправляет student-tests/explain.sql в psql внутри контейнера postgres
и сохраняет вывод в evidence/explain-history.txt (тестовые данные потом откатываются).
"""
import subprocess
from common import ROOT
OUTPUT = ROOT / "evidence" / "explain-history.txt"
def main():
sql = (ROOT / "student-tests" / "explain.sql").read_bytes()
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-v", "ON_ERROR_STOP=1"],
cwd=ROOT, input=sql, capture_output=True, check=False,
)
OUTPUT.parent.mkdir(exist_ok=True)
OUTPUT.write_bytes(result.stdout + result.stderr)
if result.returncode != 0:
print(result.stderr.decode("utf-8", "replace"))
raise SystemExit("FAIL: psql returned an error, see output above")
for line in result.stdout.decode("utf-8", "replace").splitlines():
if line.startswith("===") or "Buffers" in line or "Execution Time" in line or " Scan " in line:
print(line)
print(f"PASS: full plans saved to {OUTPUT.relative_to(ROOT)}")
if __name__ == "__main__":
main()
+73
View File
@@ -0,0 +1,73 @@
-- Обоснование индекса истории messages_history (migrations/001_init.sql).
-- Запуск: python student-tests/explain.py (результат -> evidence/explain-history.txt)
--
-- Всё в одной транзакции, в конце ROLLBACK: тестовые данные не остаются в базе,
-- скрипт можно запускать сколько угодно раз.
\pset footer off
BEGIN;
-- Тестовые данные: один большой чат на 15 000 сообщений и 50 маленьких по 100,
-- всего 20 000 сообщений. Чужие сообщения в таблице есть, как в настоящей базе.
CREATE TEMP TABLE seed_chats AS
SELECT gen_random_uuid() AS id, n, CASE WHEN n = 0 THEN 15000 ELSE 100 END AS size
FROM generate_series(0, 50) AS n;
CREATE TEMP TABLE seed_user AS SELECT gen_random_uuid() AS id;
INSERT INTO users (id, username, display_name, password_hash)
SELECT id, 'explain_' || substr(md5(random()::text), 1, 10), 'Explain', 'not-a-real-hash' FROM seed_user;
INSERT INTO chats (id, title) SELECT id, 'explain ' || n FROM seed_chats;
INSERT INTO chat_members (chat_id, user_id) SELECT c.id, u.id FROM seed_chats c, seed_user u;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), c.id, u.id, 'message ' || g,
timestamptz '2026-09-01 00:00:00+00' + g * interval '1 second'
FROM seed_chats c, seed_user u, generate_series(1, c.size) AS g;
ANALYZE messages;
SELECT id AS big_chat FROM seed_chats WHERE n = 0 \gset
-- Курсор глубоко в истории: ключ (created_at, id) 10 000-го сообщения большого чата.
SELECT created_at AS cursor_time, id AS cursor_id FROM messages
WHERE chat_id = :'big_chat' ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset
\echo '=== Data volume'
SELECT count(*) AS messages_total,
count(*) FILTER (WHERE chat_id = :'big_chat') AS messages_in_big_chat
FROM messages;
\echo ''
\echo '=== History index'
SELECT indexdef FROM pg_indexes WHERE indexname = 'messages_history';
\echo ''
\echo '=== 1. First page: limit=50, the app asks for 51 rows to know if there is a next page'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id LIMIT 51;
\echo ''
\echo '=== 2. Page after the 10000th message by keyset cursor (this is what the app does)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
ORDER BY created_at, id LIMIT 51;
\echo ''
\echo '=== 3. The same page with OFFSET 10000 (the app does NOT do this)'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat'
ORDER BY created_at, id OFFSET 10000 LIMIT 51;
\echo ''
\echo '=== 4. Query 2 without the index (index is dropped only inside this transaction)'
DROP INDEX messages_history;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = :'big_chat' AND (created_at, id) > (:'cursor_time'::timestamptz, :'cursor_id'::uuid)
ORDER BY created_at, id LIMIT 51;
ROLLBACK;
\echo ''
\echo '=== ROLLBACK: test data removed, index is back'
SELECT count(*) AS explain_users_left FROM users WHERE username LIKE 'explain\_%';
+38
View File
@@ -0,0 +1,38 @@
"""Что лежит в Redis и как он настроен (доказательство для отчёта).
python student-tests/redis_info.py
Входит новым пользователем и показывает: ключ его сессии и остаток TTL,
сколько всего сессий, настройки сохранения на диск и политику памяти,
и что без пароля Redis ничего не отдаёт. Токены и пароли не печатаются:
ключ — это SHA-256 токена.
"""
import subprocess
from common import ROOT, login, new_user, redis_cli, session_key
def without_password():
result = subprocess.run(["docker", "compose", "exec", "-T", "redis", "redis-cli", "get", "anything"],
cwd=ROOT, capture_output=True, check=False)
return (result.stdout + result.stderr).decode("utf-8", "replace").strip()
def main():
user = new_user("info")
token = login(user["username"], user["password"]).json["token"]
key = session_key(token)
print(f"session key: {key[:24]}...; value is the user id: {redis_cli('get', key) == user['id']}")
print(f"TTL of the key, seconds: {redis_cli('ttl', key)}")
keys = redis_cli("--scan", "--pattern", "'session:*'").splitlines()
print(f"sessions in Redis: {len(keys)}")
for name in ("appendonly", "appendfsync", "maxmemory-policy"):
print("config", " = ".join(redis_cli("config", "get", name).split()))
for line in redis_cli("info", "persistence").splitlines():
if line.startswith(("aof_enabled", "aof_last_write_status")):
print(line)
print(f"without password: {without_password()}")
if __name__ == "__main__":
main()
+238
View File
@@ -0,0 +1,238 @@
"""Собственные тесты API (lab1 + lab2). Запуск одной командой при запущенном стенде:
python student-tests/test_api.py
Тесты lab1 переведены с X-User-Id на пароль и Bearer-токен. Добавлены тесты lab2:
вход по Basic, неверный пароль, logout, Bearer на всех защищённых запросах.
"""
import base64
import datetime as dt
import uuid
from common import PASSWORD, basic, call, check, login, new_chat, new_user, read_history, run_tests, send
def parse_time(value):
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
# ---------- lab1 (перенесены, теперь с токенами) ----------
def test_duplicate_username():
body = {"username": "dup_" + uuid.uuid4().hex[:10], "display_name": "First user", "password": PASSWORD}
call("POST", "/api/v1/users", 201, body=body)
call("POST", "/api/v1/users", 409, body=dict(body, display_name="Second user"))
print("PASS: duplicate username returns 409")
def test_invalid_json():
alice = new_user("alice")
chat = new_chat(alice)
call("POST", "/api/v1/users", 400, raw=b'{"username":')
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], raw=b"not json")
print("PASS: invalid JSON returns 400")
def test_wrong_fields():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
call("POST", "/api/v1/users", 400, body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
call("POST", "/api/v1/users", 400,
body={"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "x", "password": PASSWORD, "is_admin": True})
# Отправителя нельзя подставить: он берётся из сессии.
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"],
body={"text": "hi", "sender_id": bob["id"]})
print("PASS: wrong and extra fields return 400")
def test_foreign_chat():
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
chat = new_chat(alice, bob)
call("GET", f"/api/v1/chats/{chat['id']}", 404, token=eve["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, token=eve["token"])
send(eve, chat["id"], "not my chat", expected=404)
# Несуществующий чат выглядит так же, как чужой.
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, token=eve["token"])
print("PASS: foreign chat returns 404")
def test_empty_message():
alice = new_user("alice")
chat = new_chat(alice)
for text in ("", " ", "\n\t"):
send(alice, chat["id"], text, expected=400)
send(alice, chat["id"], "я" * 4001, expected=400)
send(alice, chat["id"], "я" * 4000)
print("PASS: empty and too long messages return 400, 4000 chars is ok")
def test_pagination():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
sent = [send(alice, chat["id"], f"Message {i}").json["id"] for i in range(7)]
history, pages = read_history(bob, chat["id"], limit=2)
check(pages == 4, f"expected 4 pages, got {pages}")
check([m["id"] for m in history] == sent, "pages overlap, lose or reorder messages")
other = new_chat(alice)
for i in range(3):
send(alice, other["id"], f"Other {i}")
first = call("GET", f"/api/v1/chats/{other['id']}/messages?limit=1", token=alice["token"]).json
# Курсор от другого чата и испорченный курсор — 400.
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={first['next_cursor']}", 400, token=alice["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor=broken", 400, token=alice["token"])
print("PASS: pagination works across multiple pages, foreign cursor returns 400")
def test_chat_list_pagination():
alice, bob = new_user("alice"), new_user("bob")
created = [new_chat(alice, bob, title=f"Chat {i}")["id"] for i in range(3)]
seen, cursor = [], None
while True:
query = "?limit=1" + (f"&cursor={cursor}" if cursor else "")
page = call("GET", "/api/v1/chats" + query, token=bob["token"]).json
seen += [chat["id"] for chat in page["items"]]
cursor = page["next_cursor"]
if cursor is None:
break
check(seen == created, "chat list pages are wrong")
print("PASS: chat list pagination")
def test_unicode():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob, title="Чат 👋")
text = "Привет 👋 你好"
check(send(alice, chat["id"], text).json["text"] == text, "text changed on write")
history, _ = read_history(bob, chat["id"])
check(history[-1]["text"] == text, "text changed on read")
print("PASS: unicode text is stored as is")
# ---------- lab2: пароль, вход, Bearer, logout ----------
def test_user_has_no_password():
body = {"username": "np_" + uuid.uuid4().hex[:10], "display_name": "No password", "password": PASSWORD}
user = call("POST", "/api/v1/users", 201, body=body).json
check(set(user) == {"id", "username", "display_name", "created_at"}, f"unexpected fields: {set(user)}")
print("PASS: user response has no password or hash")
def test_password_rules():
def register(password, expected):
body = {"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "Password", "password": password}
call("POST", "/api/v1/users", expected, body=body)
register("x" * 11, 400)
register("x" * 129, 400)
register(" " * 12, 400)
register("x" * 12, 201)
register("я" * 128, 201)
print("PASS: password length 12..128, blank password is rejected")
def test_login_gives_token():
username = "lg_" + uuid.uuid4().hex[:10]
user = call("POST", "/api/v1/users", 201,
body={"username": username, "display_name": "Login", "password": PASSWORD}).json
reply = login(username, PASSWORD)
session = reply.json
check(session["token_type"] == "Bearer", "token_type must be Bearer")
check(session["user"] == user, "session user differs from registered user")
check(len(session["token"]) >= 43, "token is too short")
check(username not in session["token"] and user["id"] not in session["token"], "token is not opaque")
check(reply.headers.get("cache-control") == "no-store", "response with token must not be cached")
left = (parse_time(session["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
check(290 < left <= 3600 + 5, f"unexpected session lifetime: {left:.0f} s")
me = call("GET", "/api/v1/users/me", token=session["token"]).json
check(me == user, "/users/me returned another user")
print("PASS: Basic login returns opaque Bearer token with expiry")
def test_wrong_password():
user = new_user("wp")
wrong = login(user["username"], "Wrong-password-000", expected=401)
unknown = login("nobody_" + uuid.uuid4().hex[:8], PASSWORD, expected=401)
check(wrong.headers["www-authenticate"].lower().startswith("basic"), "login 401 must ask for Basic")
# Одинаковый ответ: по нему нельзя узнать, существует ли такой username.
check(wrong.json["error"]["message"] == unknown.json["error"]["message"], "different answers leak usernames")
print("PASS: wrong password and unknown user both return the same 401")
def test_malformed_basic():
no_colon = base64.b64encode(b"just_username").decode()
for header in (None, "Basic", "Basic !!!", "Basic " + no_colon, "Bearer something"):
headers = {} if header is None else {"Authorization": header}
call("POST", "/api/v1/auth/sessions", 401, headers=headers)
print("PASS: malformed Basic header returns 401")
def test_password_with_colon_and_unicode():
password = "пароль:с:двоеточием 👋"
user = new_user("colon", password=password)
call("GET", "/api/v1/users/me", token=user["token"])
print("PASS: password with colon and unicode works")
def test_bearer_required():
user = new_user("br")
for headers in ({}, {"Authorization": basic(user["username"], user["password"])},
{"X-User-Id": user["id"]}, {"Authorization": "Bearer " + "A" * 43},
{"Authorization": "Bearer"}, {"Authorization": "Token " + user["token"]}):
reply = call("GET", "/api/v1/users/me", 401, headers=headers)
check(reply.headers["www-authenticate"].lower().startswith("bearer"), "401 must ask for Bearer")
call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + user["token"]})
print("PASS: business endpoints need Bearer; Basic and X-User-Id give 401")
def test_x_user_id_ignored():
alice, bob = new_user("alice"), new_user("bob")
me = call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": bob["id"]}).json
check(me["id"] == alice["id"], "X-User-Id changed the current user")
print("PASS: X-User-Id does not change the current user")
def test_auth_before_body():
alice = new_user("alice")
chat = new_chat(alice)
# Без токена всегда 401, даже если тело неверное или чат чужой: сначала «кто ты».
call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, raw=b"not json")
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
print("PASS: 401 comes before 400 and 404")
def test_logout():
user = new_user("lo")
second = login(user["username"], user["password"]).json["token"]
call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
call("GET", "/api/v1/users/me", 401, token=user["token"])
call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"])
call("GET", "/api/v1/users/me", 200, token=second) # другая сессия того же пользователя жива
again = login(user["username"], user["password"]).json["token"]
check(again != user["token"], "new login must give a new token")
call("GET", "/api/v1/users/me", 200, token=again)
print("PASS: logout revokes only the current session")
if __name__ == "__main__":
run_tests([
test_duplicate_username,
test_invalid_json,
test_wrong_fields,
test_foreign_chat,
test_empty_message,
test_pagination,
test_chat_list_pagination,
test_unicode,
test_user_has_no_password,
test_password_rules,
test_login_gives_token,
test_wrong_password,
test_malformed_basic,
test_password_with_colon_and_unicode,
test_bearer_required,
test_x_user_id_ignored,
test_auth_before_body,
test_logout,
])
+92
View File
@@ -0,0 +1,92 @@
"""Проверки на уровне базы данных. Запуск при запущенном стенде:
python student-tests/test_db.py
SQL выполняется в контейнере postgres через `docker compose exec postgres psql`.
1. Откат составной операции: чат с несуществующим участником -> 400, и в базе
не остаётся ни чата, ни участников, хотя строка чата успела вставиться.
2. База сама не даёт записать сообщение от не-участника (внешний ключ).
3. Пароль хранится как хеш Argon2id, а не как текст или быстрый хеш.
4. Миграции: после перезапуска API ничего не применяется повторно.
"""
import time
import uuid
from common import call, check, compose, compose_output, new_user, psql, run_tests, wait_ready
def sql_value(sql):
code, output, error = psql(sql)
check(code == 0, f"psql failed: {error}")
return output
def test_create_chat_rolls_back():
alice = new_user("rollback")
title = "rollback-" + uuid.uuid4().hex[:8]
inserted_before = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
# Второй участник не существует: INSERT чата пройдёт, INSERT участника упадёт на внешнем ключе.
call("POST", "/api/v1/chats", 400, token=alice["token"],
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
left = sql_value(f"SELECT count(*) FROM chats WHERE title = '{title}'")
orphans = sql_value("SELECT count(*) FROM chats c WHERE NOT EXISTS "
"(SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)")
# Статистика PostgreSQL считает и отменённые вставки; она обновляется с задержкой до ~1 с.
inserted_after = inserted_before
deadline = time.monotonic() + 15
while inserted_after == inserted_before and time.monotonic() < deadline:
time.sleep(0.5)
inserted_after = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
print(f"chat with unknown member -> 400; rows with this title: {left}; chats without members: {orphans}; "
f"chats insert counter: {inserted_before} -> {inserted_after}")
check(left == "0" and orphans == "0", "chat row survived the failed transaction")
check(inserted_after > inserted_before, "the chat row was never inserted, rollback is not shown")
print("PASS: chat row was inserted and then rolled back together with members")
def test_message_needs_membership_in_db():
code, _, error = psql("INSERT INTO messages (id, chat_id, sender_id, text) "
f"VALUES ('{uuid.uuid4()}', '{uuid.uuid4()}', '{uuid.uuid4()}', 'direct insert')")
print(f"direct INSERT of a message from a non-member -> exit code {code}: {error.splitlines()[0] if error else ''}")
check(code != 0 and "foreign key" in error, "database accepted a message from a non-member")
print("PASS: the database itself rejects a message from a non-member")
def test_password_is_argon2id():
user = new_user("hash")
stored = sql_value(f"SELECT password_hash FROM users WHERE username = '{user['username']}'")
print(f"stored password: {stored[:31]}... (length {len(stored)})")
check(stored.startswith("$argon2id$") and user["password"] not in stored, "password is not an Argon2id hash")
print("PASS: password is stored as Argon2id hash")
def test_unique_username_constraint():
constraint = sql_value("SELECT pg_get_constraintdef(oid) FROM pg_constraint "
"WHERE conrelid = 'users'::regclass AND contype = 'u'")
print(f"unique constraint on users: {constraint}")
check(constraint == "UNIQUE (username)", "no unique constraint on username")
print("PASS: username is unique in the database")
def test_migrations_are_not_repeated():
versions = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
print(f"applied migrations: {versions}; restarting api")
compose("restart", "api")
wait_ready()
again = sql_value("SELECT string_agg(version, ',' ORDER BY version) FROM schema_migrations")
last_log = [line for line in compose_output("logs", "api").splitlines() if "Migrations applied" in line][-1]
print(f"after restart: {again}; log: {last_log.split('messenger.db: ')[-1]}")
check(again == versions and "none" in last_log, "migrations were applied again")
print("PASS: migrations are applied once, restart does nothing")
if __name__ == "__main__":
run_tests([
test_create_chat_rolls_back,
test_message_needs_membership_in_db,
test_password_is_argon2id,
test_unique_username_constraint,
test_migrations_are_not_repeated,
])
+66
View File
@@ -0,0 +1,66 @@
"""Истечение сессии при коротком SESSION_TTL_SECONDS. Запуск при запущенном стенде:
python student-tests/test_expiry.py
Тест сам пересоздаёт контейнер api с SESSION_TTL_SECONDS=2
(docker compose up -d --no-deps --wait api, переменная берётся из окружения вместо .env),
проверяет, что токен работает до срока и даёт 401 после, а в конце возвращает
обычный TTL из .env. PostgreSQL и Redis при этом не трогаются.
"""
import datetime as dt
import os
import time
from common import call, check, compose, login, new_user, redis_cli, run_tests, session_key, wait_ready
SHORT_TTL = 2
def restart_api(ttl=None):
env = dict(os.environ)
if ttl is None:
env.pop("SESSION_TTL_SECONDS", None) # значение снова из .env
else:
env["SESSION_TTL_SECONDS"] = str(ttl)
compose("up", "-d", "--no-deps", "--wait", "api", env=env)
wait_ready()
def seconds_left(expires_at):
moment = dt.datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
return (moment - dt.datetime.now(dt.timezone.utc)).total_seconds()
def test_session_expires():
print(f"recreating api with SESSION_TTL_SECONDS={SHORT_TTL}")
restart_api(SHORT_TTL)
try:
user = new_user("ttl")
session = login(user["username"], user["password"]).json
token = session["token"]
left = seconds_left(session["expires_at"])
print(f"session issued, expires in {left:.2f} s; Redis TTL of the key: "
f"{redis_cli('pttl', session_key(token))} ms")
check(0 < left <= SHORT_TTL + 0.5, "short TTL instance must issue ~2 second sessions")
call("GET", "/api/v1/users/me", 200, token=token)
print("before expiry: GET /users/me -> 200")
time.sleep(max(0.0, seconds_left(session["expires_at"])) + 1.0)
call("GET", "/api/v1/users/me", 401, token=token)
exists = redis_cli("exists", session_key(token))
print(f"after expiry: GET /users/me -> 401; key exists in Redis: {exists}")
check(exists == "0", "Redis must delete the expired session key")
finally:
print("recreating api with SESSION_TTL_SECONDS from .env")
restart_api()
user = new_user("ttl_back")
left = seconds_left(login(user["username"], user["password"]).json["expires_at"])
print(f"normal API again: new session expires in {left:.0f} s")
check(left > 300, "normal TTL was not restored")
print("PASS: session expires after SESSION_TTL_SECONDS and is rejected with 401")
if __name__ == "__main__":
run_tests([test_session_expires])
+127
View File
@@ -0,0 +1,127 @@
"""Отказ зависимости. Запуск при запущенном стенде:
python student-tests/test_failures.py redis
python student-tests/test_failures.py postgres
python student-tests/test_failures.py (оба по очереди)
Тест сам останавливает контейнер (docker compose stop), проверяет ответы API
и запускает контейнер обратно (docker compose start). Volumes не трогаются.
redis — хранилище сессий недоступно: токен проверить нельзя, поэтому защищённые
запросы получают 503 (а не 200 и не «пропуск»), вход — 503; регистрация работает.
Второй сценарий: Redis убивается без корректной остановки (docker compose kill),
после запуска сессия на месте, потому что AOF пишется на диск до ответа «OK».
postgres — данные недоступны: бизнес-запросы 503, вход 503; без токена и с чужим
токеном — 401, то есть анонимов не пускаем.
После запуска контейнера прежний токен и подтверждённые сообщения на месте.
"""
import sys
import time
import uuid
from common import PASSWORD, basic, call, check, compose, new_chat, new_user, read_history, run_tests, send, wait_ready
FAKE_TOKEN = "A" * 43
def timed(method, path, expected, **kwargs):
started = time.monotonic()
reply = call(method, path, expected, **kwargs)
return reply, (time.monotonic() - started) * 1000
def prepare():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
before = send(alice, chat["id"], "confirmed before outage").json
return alice, bob, chat, before
def recovered(alice, chat, before):
wait_ready()
history, _ = read_history(alice, chat["id"])
check(before in history, "message confirmed before the outage is lost or changed")
call("GET", "/api/v1/users/me", 200, token=alice["token"])
print("after start: the old token works, confirmed messages are in place")
def test_redis_down():
alice, bob, chat, before = prepare()
print("stopping redis")
compose("stop", "redis")
try:
call("GET", "/health/live", 200)
_, ms = timed("GET", "/health/ready", 503)
print(f"/health/live -> 200, /health/ready -> 503 ({ms:.0f} ms)")
reply, ms = timed("GET", "/api/v1/users/me", 503, token=alice["token"])
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
print(f"valid token: GET /users/me -> 503 unavailable ({ms:.0f} ms), session cannot be checked")
call("GET", "/api/v1/chats", 503, token=FAKE_TOKEN)
print("unknown token -> 503, not 200: nobody is trusted without a check")
call("GET", "/api/v1/chats", 401)
print("no token -> 401")
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": basic(alice["username"], PASSWORD)})
print("login -> 503: there is nowhere to store the session")
call("POST", "/api/v1/users", 201,
body={"username": "rd_" + uuid.uuid4().hex[:10], "display_name": "x", "password": PASSWORD})
print("registration -> 201: it needs only PostgreSQL")
finally:
print("starting redis")
compose("start", "redis")
recovered(alice, chat, before)
print("PASS: Redis outage gives 503 and does not let anyone in without a session check")
def test_redis_crash():
alice = new_user("crash")
print("killing redis with SIGKILL (docker compose kill redis): no graceful shutdown")
compose("kill", "redis")
try:
# Обычно 503; 200 возможен, если Docker уже успел поднять Redis по restart policy.
status = call("GET", "/api/v1/users/me", (503, 200), token=alice["token"]).status
print(f"right after the crash: GET /users/me -> {status}")
finally:
print("starting redis")
compose("start", "redis")
wait_ready()
call("GET", "/api/v1/users/me", 200, token=alice["token"])
print("after start: the session issued before the crash still works (AOF, appendfsync always)")
print("PASS: sessions survive a Redis crash, not only a clean restart")
def test_postgres_down():
alice, bob, chat, before = prepare()
print("stopping postgres")
compose("stop", "postgres")
try:
call("GET", "/health/live", 200)
_, ms = timed("GET", "/health/ready", 503)
print(f"/health/live -> 200, /health/ready -> 503 ({ms:.0f} ms)")
for method, path, body in (("GET", "/api/v1/users/me", None),
("GET", "/api/v1/chats", None),
("GET", f"/api/v1/chats/{chat['id']}/messages", None),
("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "will not be saved"})):
reply = call(method, path, 503, token=alice["token"], body=body)
check(reply.json["error"]["code"] == "unavailable", "expected code unavailable")
check("postgres" not in reply.data.decode().lower(), "error must not show database details")
print("valid token: users/me, chats, history, new message -> 503 unavailable, no details")
call("GET", "/api/v1/chats", 401)
call("GET", "/api/v1/chats", 401, token=FAKE_TOKEN)
print("no token -> 401, unknown token -> 401: anonymous users are not let in")
call("POST", "/api/v1/auth/sessions", 503, headers={"Authorization": basic(alice["username"], PASSWORD)})
call("POST", "/api/v1/users", 503,
body={"username": "pd_" + uuid.uuid4().hex[:10], "display_name": "x", "password": PASSWORD})
print("login -> 503, registration -> 503")
finally:
print("starting postgres")
compose("start", "postgres")
recovered(alice, chat, before)
print("PASS: PostgreSQL outage gives limited 503 errors and keeps anonymous users out")
if __name__ == "__main__":
target = sys.argv[1] if len(sys.argv) > 1 else "all"
tests = {"redis": [test_redis_down, test_redis_crash], "postgres": [test_postgres_down],
"all": [test_redis_down, test_redis_crash, test_postgres_down]}
check(target in tests, "usage: python student-tests/test_failures.py [redis|postgres]")
run_tests(tests[target])
+67
View File
@@ -0,0 +1,67 @@
"""Проверка гонок. Запуск при запущенном стенде:
python student-tests/test_race.py
1. 10 клиентов одновременно отправляют по 10 сообщений в один чат (тест из lab1):
в истории ровно 100 сообщений, все id уникальны, ни один текст не потерян.
2. 20 клиентов одновременно регистрируют ОДИН И ТОТ ЖЕ username:
ровно один получает 201, остальные 409. Защищает уникальный индекс в PostgreSQL,
а не проверка «есть ли такой» в коде.
"""
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import PASSWORD, call, check, new_chat, new_user, read_history, run_tests, send
CLIENTS = 10
MESSAGES_PER_CLIENT = 10
REGISTRATIONS = 20
def test_concurrent_messages():
users = [new_user(f"race{i}") for i in range(CLIENTS)]
chat = new_chat(*users, title="race")
barrier = threading.Barrier(CLIENTS) # все клиенты стартуют одновременно
def client(index):
barrier.wait()
for n in range(MESSAGES_PER_CLIENT):
send(users[index], chat["id"], f"client-{index}-message-{n}")
started = time.monotonic()
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
list(pool.map(client, range(CLIENTS))) # list() пробрасывает ошибки из потоков
elapsed = time.monotonic() - started
history, pages = read_history(users[0], chat["id"], limit=30)
ids = {message["id"] for message in history}
expected = {f"client-{i}-message-{n}" for i in range(CLIENTS) for n in range(MESSAGES_PER_CLIENT)}
print(f"sent {CLIENTS * MESSAGES_PER_CLIENT} messages from {CLIENTS} clients in {elapsed:.2f} s; "
f"read {len(history)} in {pages} pages, unique ids: {len(ids)}")
check(len(history) == CLIENTS * MESSAGES_PER_CLIENT, "wrong number of messages")
check(len(ids) == len(history), "duplicate message ids")
check({message["text"] for message in history} == expected, "lost or changed message texts")
print("PASS: 100 concurrent messages from 10 clients, no losses and no duplicates")
def test_concurrent_registration():
username = "race_" + uuid.uuid4().hex[:10]
barrier = threading.Barrier(REGISTRATIONS)
def register(index):
barrier.wait()
body = {"username": username, "display_name": f"Client {index}", "password": PASSWORD}
return 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"{REGISTRATIONS} parallel registrations of one username: 201 x{created}, 409 x{conflicts}")
check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win")
print("PASS: concurrent registration created exactly one user")
if __name__ == "__main__":
run_tests([test_concurrent_messages, test_concurrent_registration])