Files
mtusi2026lab2/student-tests/test_lab2.py
T
zemilesandClaude Opus 5.5 ffb98242ff ЛР 2: PostgreSQL, Bearer-сессии и кэш сессий в Valkey (на 4)
- Перенесён минимум lab1; переход 1 → 2: password при регистрации,
  Basic только на POST /auth/sessions, Bearer вместо X-User-Id, logout.
- PostgreSQL — источник истины: users, chats, chat_members, messages,
  sessions; миграции с PK/FK/UNIQUE/CHECK и индексами, атомарное
  создание чата, scrypt для паролей, SHA-256 токенов в БД.
- Valkey — кэш проверенных сессий с TTL, tombstone при logout,
  обход кэша и окно недоверия при отказе.
- Ограниченные пулы и таймауты PostgreSQL/Valkey, 503 при отказе БД.
- compose.yaml с Docker secrets и именованным томом, restart hook,
  собственные тесты, EXPLAIN на 110 тыс. сообщений, замер пользы кэша,
  заполненный REPORT.md и evidence/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:15:02 +03:00

365 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Собственные проверки lab2 (только stdlib): аутентификация, границы, транзакции, сохранность.
python3 student-tests/test_lab2.py # граничные проверки, гонка, атомарность
python3 student-tests/test_lab2.py --expiry-url http://localhost:8081 # + истечение (SESSION_TTL_SECONDS=2)
python3 student-tests/test_lab2.py --db-outage # + остановка PostgreSQL -> 503, восстановление
python3 student-tests/test_lab2.py --persistence # + перезапуск API и БД через scripts/restart.sh
Токены и пароли не печатаются. Флаги --db-outage/--persistence управляют docker compose.
"""
import argparse
import base64
import json
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--persistence", action="store_true")
parser.add_argument("--expiry-url", default=None, help="экземпляр API с SESSION_TTL_SECONDS=2")
parser.add_argument("--db-outage", action="store_true")
parser.add_argument("--cache", action="store_true",
help="проверки Valkey: отказ, FLUSHALL, зависание при logout (docker compose)")
args = parser.parse_args()
BASE = args.base_url.rstrip("/")
ROOT = Path(__file__).resolve().parents[1]
fails = 0
def call(method, path, body=None, token=None, headers=None, raw=None, base=None):
h = dict(headers or {})
if token:
h["Authorization"] = "Bearer " + token
data = raw if raw is not None else (json.dumps(body, ensure_ascii=False).encode() if body is not None else None)
if data is not None:
h.setdefault("Content-Type", "application/json")
req = urllib.request.Request((base or BASE) + path, data=data, headers=h, method=method)
try:
resp = urllib.request.urlopen(req, timeout=30)
except urllib.error.HTTPError as err:
resp = err
with resp:
text = resp.read()
assert resp.headers.get("X-Request-Id"), "нет X-Request-Id"
return resp.code, (json.loads(text) if text else None), resp.headers
def expect(name, got, want):
global fails
ok = got == want
fails += not ok
short = lambda v: (str(v)[:40] + "…") if len(str(v)) > 40 else str(v)
print("%-4s %-46s -> %s (ожидалось %s)" % ("OK" if ok else "FAIL", name, short(got), short(want)))
def basic(username, password):
return {"Authorization": "Basic " + base64.b64encode((username + ":" + password).encode()).decode()}
def register(prefix, password):
username = prefix + uuid.uuid4().hex[:8]
code, user, _ = call("POST", "/api/v1/users", {"username": username, "display_name": "Тест", "password": password})
assert code == 201, code
return user
def login(username, password):
code, session, _ = call("POST", "/api/v1/auth/sessions", headers=basic(username, password))
assert code == 201, code
return session["token"]
PW_A, PW_B = "Пароль:с:двоеточием-Ω1", "T3st-" + uuid.uuid4().hex
a, b, e = register("a_", PW_A), register("b_", PW_B), register("e_", PW_B)
ta, tb, te = login(a["username"], PW_A), login(b["username"], PW_B), login(e["username"], PW_B)
# --- регистрация ---
users = "/api/v1/users"
expect("регистрация без password", call("POST", users, {"username": "zz_" + uuid.uuid4().hex[:6], "display_name": "x"})[0], 400)
expect("password 11 символов", call("POST", users, {"username": "zz_" + uuid.uuid4().hex[:6], "display_name": "x", "password": "a" * 11})[0], 400)
expect("password 129 символов", call("POST", users, {"username": "zz_" + uuid.uuid4().hex[:6], "display_name": "x", "password": "a" * 129})[0], 400)
expect("password не строка", call("POST", users, {"username": "zz_" + uuid.uuid4().hex[:6], "display_name": "x", "password": 123456789012})[0], 400)
expect("дубликат username", call("POST", users, {"username": a["username"], "display_name": "x", "password": PW_B})[0], 409)
expect("User не содержит пароль/хеш", sorted(a), ["created_at", "display_name", "id", "username"])
expect("malformed JSON", call("POST", users, raw=b"{bad")[0], 400)
# --- вход ---
sess = "/api/v1/auth/sessions"
code, _, hdr = call("POST", sess, headers=basic(a["username"], "wrong-password-123"))
expect("неверный пароль", code, 401)
expect(" challenge Basic", hdr.get("WWW-Authenticate", "").startswith("Basic"), True)
expect("неизвестный пользователь", call("POST", sess, headers=basic("no_such_user_x", PW_B))[0], 401)
expect("вход без Authorization", call("POST", sess)[0], 401)
expect("вход с Bearer вместо Basic", call("POST", sess, token=ta)[0], 401)
expect("мусор вместо base64", call("POST", sess, headers={"Authorization": "Basic !!!"})[0], 401)
expect("пароль с двоеточием и Unicode", call("GET", "/api/v1/users/me", token=ta)[1]["id"], a["id"])
t1, t2 = login(b["username"], PW_B), login(b["username"], PW_B)
expect("два входа дают разные токены", t1 != t2 and len(t1) >= 43, True)
# --- Bearer ---
me = "/api/v1/users/me"
code, _, hdr = call("GET", me)
expect("без токена", code, 401)
expect(" challenge Bearer", hdr.get("WWW-Authenticate", "").startswith("Bearer"), True)
expect("случайный токен", call("GET", me, token="x" * 43)[0], 401)
expect("Basic на бизнес-endpoint", call("GET", me, headers=basic(a["username"], PW_A))[0], 401)
expect("только X-User-Id", call("GET", me, headers={"X-User-Id": a["id"]})[0], 401)
expect("X-User-Id не меняет владельца", call("GET", me, token=ta, headers={"X-User-Id": e["id"]})[1]["id"], a["id"])
# --- logout ---
expect("logout", call("DELETE", sess + "/current", token=t1)[0], 204)
expect("отозванный токен", call("GET", me, token=t1)[0], 401)
expect("повторный logout", call("DELETE", sess + "/current", token=t1)[0], 401)
expect("другая сессия того же пользователя жива", call("GET", me, token=t2)[0], 200)
# --- чаты и сообщения ---
chats = "/api/v1/chats"
expect("чат: создатель не участник", call("POST", chats, {"title": "t", "member_ids": [b["id"]]}, ta)[0], 400)
expect("чат: неизвестный участник", call("POST", chats, {"title": "t", "member_ids": [a["id"], str(uuid.uuid4())]}, ta)[0], 400)
expect("чат: дубликат участника", call("POST", chats, {"title": "t", "member_ids": [a["id"], a["id"]]}, ta)[0], 400)
chat = call("POST", chats, {"title": "Проверка", "member_ids": [a["id"], b["id"]]}, ta)[1]
chat2 = call("POST", chats, {"title": "t2", "member_ids": [a["id"]]}, ta)[1]
expect("порядок member_ids сохранён", chat["member_ids"], [a["id"], b["id"]])
msgs = "/api/v1/chats/%s/messages" % chat["id"]
expect("чужой чат (Ева)", call("GET", chats + "/" + chat["id"], token=te)[0], 404)
expect("запись в чужой чат (Ева)", call("POST", msgs, {"text": "x"}, te)[0], 404)
expect("пустое сообщение", call("POST", msgs, {"text": " "}, ta)[0], 400)
expect("sender_id в теле", call("POST", msgs, {"text": "x", "sender_id": b["id"]}, ta)[0], 400)
expect("4001 символ", call("POST", msgs, {"text": "я" * 4001}, ta)[0], 400)
errors = []
def send(i):
try:
code, _, _ = call("POST", msgs, {"text": "m%d 👋" % i}, ta if i % 2 else tb)
if code != 201:
errors.append(code)
except Exception as exc:
errors.append(type(exc).__name__)
threads = [threading.Thread(target=send, args=(i,)) for i in range(100)]
[t.start() for t in threads]
[t.join() for t in threads]
def read_all(token, limit=7):
seen, cursor = [], None
while True:
_, page, _ = call("GET", msgs + "?limit=%d" % limit + ("&cursor=" + cursor if cursor else ""), token=token)
seen += page["items"]
cursor = page["next_cursor"]
if not cursor:
return seen
history = read_all(tb)
expect("100 параллельных POST: ошибок", len(errors), 0)
expect("100 параллельных POST: уникальных", len({m["id"] for m in history}), 100)
expect("история отсортирована (created_at, id)",
history == sorted(history, key=lambda m: (m["created_at"], uuid.UUID(m["id"]).int)), True)
first = call("GET", msgs + "?limit=1", token=ta)[1]
expect("cursor от другого чата", call("GET", "/api/v1/chats/%s/messages?cursor=%s" % (chat2["id"], first["next_cursor"]), token=ta)[0], 400)
expect("мусорный cursor", call("GET", msgs + "?cursor=abc", token=ta)[0], 400)
expect("limit=0", call("GET", msgs + "?limit=0", token=ta)[0], 400)
expect("неверный UUID в пути", call("GET", chats + "/xyz", token=ta)[0], 400)
# --- гонка регистрации одного username ---
race_name = "race_" + uuid.uuid4().hex[:10]
race_codes = []
def register_same():
try:
race_codes.append(call("POST", "/api/v1/users",
{"username": race_name, "display_name": "Гонка", "password": PW_B})[0])
except Exception as exc:
race_codes.append(type(exc).__name__)
threads = [threading.Thread(target=register_same) for _ in range(20)]
[t.start() for t in threads]
[t.join() for t in threads]
expect("гонка 20 регистраций: ровно один 201", sorted(race_codes).count(201), 1)
expect("гонка 20 регистраций: остальные 409", sorted(race_codes).count(409), 19)
# --- атомарность создания чата: ошибка не оставляет «полу-чата» ---
def chat_ids(token):
_, page, _ = call("GET", chats + "?limit=100", token=token)
return [c["id"] for c in page["items"]]
fresh_pw = "T3st-" + uuid.uuid4().hex
fresh = register("f_", fresh_pw)
tf = login(fresh["username"], fresh_pw)
before = chat_ids(tf)
before_b = chat_ids(tb)
code = call("POST", chats, {"title": "откат", "member_ids": [fresh["id"], b["id"], str(uuid.uuid4())]}, tf)[0]
expect("чат с неизвестным 3-м участником", code, 400)
expect("после ошибки чат не появился у создателя", chat_ids(tf), before)
expect("после ошибки чат не появился у участника b", chat_ids(tb), before_b)
code, ok_chat, _ = call("POST", chats, {"title": "после отката", "member_ids": [fresh["id"]]}, tf)
expect("следующее создание чата работает", (code, chat_ids(tf)), (201, before + [ok_chat["id"]]))
# --- истечение сессии (отдельный экземпляр API с SESSION_TTL_SECONDS=2) ---
if args.expiry_url:
eb = args.expiry_url.rstrip("/")
code, s, _ = call("POST", sess, headers=basic(a["username"], PW_A), base=eb)
expect("TTL=2: вход", code, 201)
expect("TTL=2: сразу после входа токен работает", call("GET", me, token=s["token"], base=eb)[0], 200)
time.sleep(3)
code, _, hdr = call("GET", me, token=s["token"], base=eb)
expect("TTL=2: через 3 с токен истёк", code, 401)
expect(" challenge Bearer", hdr.get("WWW-Authenticate", "").startswith("Bearer"), True)
expect("TTL=2: истёкший токен не работает и на основном API", call("GET", me, token=s["token"])[0], 401)
# --- недоступность PostgreSQL ---
if args.db_outage:
print("--- остановка PostgreSQL: docker compose stop postgres")
compose = ["docker", "compose", "--env-file", str(ROOT / ".env")]
subprocess.run(compose + ["stop", "postgres"], cwd=ROOT, check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
code, body, _ = call("GET", "/health/ready")
expect("БД нет: /health/ready", (code, body["error"]["code"]), (503, "unavailable"))
expect("БД нет: /health/live", call("GET", "/health/live")[0], 200)
started = time.monotonic()
code, body, _ = call("GET", chats, token=ta)
expect("БД нет: список чатов с токеном -> 503, не 200", (code, body["error"]["code"]), (503, "unavailable"))
expect("БД нет: ответ ограничен по времени (<10 с)", time.monotonic() - started < 10, True)
# /users/me может быть отдан из кэша сессий (копия действующей сессии, отзыв без БД невозможен)
expect("БД нет: /users/me -> 200 из кэша или 503", call("GET", me, token=ta)[0] in (200, 503), True)
expect("БД нет: неизвестный токен не проходит", call("GET", me, token="y" * 43)[0] in (401, 503), True)
expect("БД нет: анонимный запрос не проходит", call("GET", me)[0] in (401, 503), True)
expect("БД нет: вход -> 503", call("POST", sess, headers=basic(a["username"], PW_A))[0], 503)
finally:
subprocess.run(compose + ["start", "postgres"], cwd=ROOT, check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
deadline = time.monotonic() + 60
while call("GET", "/health/ready")[0] != 200:
assert time.monotonic() < deadline, "БД не восстановилась"
time.sleep(1)
expect("БД вернулась: прежний токен работает", call("GET", me, token=ta)[1], a)
# --- Valkey: роль кэша, отказ, flush, зависание при logout ---
if args.cache:
compose = ["docker", "compose", "--env-file", str(ROOT / ".env")]
def dc(*cmd):
subprocess.run(compose + list(cmd), cwd=ROOT, check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def vcli(*cmd):
"""valkey-cli внутри контейнера; пароль читается там же из секрета и не печатается."""
out = subprocess.run(compose + ["exec", "-T", "valkey", "sh", "-c",
'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" '
'/run/secrets/valkey.conf)" "$@"', "_"] + list(cmd),
cwd=ROOT, check=True, capture_output=True, text=True)
return out.stdout.strip()
def stats():
info = dict(l.split(":", 1) for l in vcli("INFO", "stats").splitlines() if ":" in l)
return int(info["keyspace_hits"]), int(info["keyspace_misses"])
import hashlib
def cache_value(token):
return vcli("GET", "sess:" + hashlib.sha256(token.encode()).hexdigest())
pw = "T3st-" + uuid.uuid4().hex
cu = register("c_", pw)
tc = login(cu["username"], pw)
expect("кэш: после входа в Valkey лежит копия сессии", cu["id"] in cache_value(tc), True)
expect("кэш: в Valkey нет самого токена/пароля", tc not in vcli("--scan", "--pattern", "*") and True, True)
h0, m0 = stats()
for _ in range(50):
call("GET", me, token=tc)
h1, m1 = stats()
expect("кэш: 50 запросов -> 50 попаданий в Valkey", (h1 - h0, m1 - m0), (50, 0))
# logout мгновенно виден через кэш
t2 = login(cu["username"], pw)
call("GET", me, token=t2)
expect("кэш: logout", call("DELETE", sess + "/current", token=t2)[0], 204)
expect("кэш: в Valkey tombstone вместо копии", cache_value(t2), "revoked")
expect("кэш: отозванный токен сразу 401", call("GET", me, token=t2)[0], 401)
# FLUSHALL: кэш пуст, сессии читаются из PostgreSQL
vcli("FLUSHALL")
expect("FLUSHALL: действующий токен работает (из БД)", call("GET", me, token=tc)[1], cu)
expect("FLUSHALL: отозванный токен по-прежнему 401", call("GET", me, token=t2)[0], 401)
expect("FLUSHALL: кэш снова заполнен после промаха", cu["id"] in cache_value(tc), True)
# Valkey остановлен: API работает через PostgreSQL
print("--- остановка Valkey: docker compose stop valkey")
dc("stop", "valkey")
try:
expect("Valkey нет: /health/ready 200 (не критичен)", call("GET", "/health/ready")[0], 200)
started = time.monotonic()
expect("Valkey нет: токен работает через БД", call("GET", me, token=tc)[1], cu)
expect("Valkey нет: ответ быстрый (<2 с)", time.monotonic() - started < 2, True)
expect("Valkey нет: список чатов", call("GET", chats, token=tc)[0], 200)
expect("Valkey нет: без токена 401", call("GET", me)[0], 401)
expect("Valkey нет: чужой токен 401", call("GET", me, token="z" * 43)[0], 401)
expect("Valkey нет: отозванный токен 401", call("GET", me, token=t2)[0], 401)
t3 = login(cu["username"], pw)
expect("Valkey нет: вход 201", bool(t3), True)
expect("Valkey нет: logout 204", call("DELETE", sess + "/current", token=t3)[0], 204)
expect("Valkey нет: после logout 401", call("GET", me, token=t3)[0], 401)
finally:
dc("start", "valkey")
deadline = time.monotonic() + 30
while "PONG" not in vcli("PING"):
assert time.monotonic() < deadline, "Valkey не поднялся"
time.sleep(0.5)
time.sleep(6) # дольше CACHE_RETRY_SECONDS: приложение снова опрашивает кэш
expect("Valkey вернулся: токен работает", call("GET", me, token=tc)[1], cu)
expect("Valkey вернулся: кэш снова заполняется", cu["id"] in cache_value(tc), True)
expect("Valkey вернулся: токен, отозванный при отказе, 401", call("GET", me, token=t3)[0], 401)
# Самый опасный случай: Valkey «завис» (pause) во время logout -> tombstone не записан,
# в Valkey осталась положительная копия сессии. Она не должна «воскресить» токен.
t4 = login(cu["username"], pw)
call("GET", me, token=t4)
print("--- зависание Valkey во время logout: docker compose pause valkey")
dc("pause", "valkey")
try:
expect("Valkey завис: logout всё равно 204 (отзыв в БД)", call("DELETE", sess + "/current", token=t4)[0], 204)
finally:
dc("unpause", "valkey")
expect("Valkey ожил: в нём осталась устаревшая копия", cu["id"] in cache_value(t4), True)
time.sleep(6) # breaker закрыт, кэш снова опрашивается
expect("Valkey ожил: устаревшая копия не принята, 401", call("GET", me, token=t4)[0], 401)
expect("Valkey ожил: действующий токен работает", call("GET", me, token=tc)[1], cu)
if args.persistence:
print("--- перезапуск API и PostgreSQL: scripts/restart.sh")
subprocess.run([str(ROOT / "scripts" / "restart.sh")], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
deadline = time.monotonic() + 90
while True:
try:
if call("GET", "/health/ready")[0] == 200:
break
except Exception:
pass
assert time.monotonic() < deadline, "сервер не поднялся"
time.sleep(1)
expect("после рестарта: прежний токен работает", call("GET", me, token=ta)[1], a)
expect("после рестарта: чат на месте", call("GET", chats + "/" + chat["id"], token=tb)[1], chat)
expect("после рестарта: история та же", read_all(tb), history)
expect("после рестарта: отозванный токен всё ещё отозван", call("GET", me, token=t1)[0], 401)
expect("после рестарта: вход по паролю работает", call("POST", sess, headers=basic(a["username"], PW_A))[0], 201)
print("ИТОГО:", "ВСЕ ПРОВЕРКИ ПРОШЛИ" if not fails else "%d ПРОВАЛОВ" % fails)
sys.exit(1 if fails else 0)