ЛР2: PostgreSQL, сессии, Redis-кэш, трек 5.2

This commit is contained in:
2026-10-26 21:20:34 +03:00
parent 65003b6119
commit cf4a7ad142
56 changed files with 4209 additions and 14 deletions
+111
View File
@@ -0,0 +1,111 @@
"""Общая обвязка собственных проверок студента (stdlib, Python 3.9+).
Переиспользует HTTP-клиент публичных тестов (tests/client.py), не изменяя его. Команды управления
стендом и доступа к SQL задаются переменными окружения; по умолчанию — Compose из этого репозитория.
"""
import base64
import json
import os
import shlex
import subprocess
import sys
import time
import traceback
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
DC = os.environ.get("COMPOSE", "docker compose --env-file .env")
PSQL = os.environ.get("PSQL", DC + " exec -T postgres psql -U messenger -d messenger")
COMMANDS = {
"stop_db": os.environ.get("STOP_DB", DC + " stop postgres"),
"start_db": os.environ.get("START_DB", DC + " start postgres"),
"stop_cache": os.environ.get("STOP_CACHE", DC + " stop redis"),
"start_cache": os.environ.get("START_CACHE", DC + " start redis"),
}
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
TTL_BASE_URL = os.environ.get("TTL_BASE_URL", "http://localhost:8081")
TTL_SECONDS = float(os.environ.get("TTL_SECONDS", "2"))
def sh(name_or_cmd, timeout=90):
cmd = COMMANDS.get(name_or_cmd, name_or_cmd)
subprocess.run(shlex.split(cmd), cwd=ROOT, check=True, timeout=timeout,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def sql(query):
"""Одна SQL-команда через psql (-At); возвращает строки результата. Только синтетические данные."""
out = subprocess.run(shlex.split(PSQL) + ["-X", "-At", "-v", "ON_ERROR_STOP=1", "-c", query],
cwd=ROOT, check=True, capture_output=True, text=True, timeout=60)
return [line for line in out.stdout.splitlines() if line]
def basic(username, password):
return "Basic " + base64.b64encode((username + ":" + password).encode("utf-8")).decode()
def new_user(c, label="s", password=None):
username = ("st_" + label + "_" + uuid.uuid4().hex[:10])[:32]
password = password or ("Pw-" + uuid.uuid4().hex)
user = c.call("POST", "/api/v1/users", 201, schema="User",
body={"username": username, "display_name": "Тест " + label, "password": password})["json"]
return {"id": user["id"], "user": user, "username": username, "password": password}
def login(c, actor, expected=201):
r = c.call("POST", "/api/v1/auth/sessions", expected, headers={"Authorization": basic(actor["username"], actor["password"])},
schema="Session" if expected == 201 else None)
if expected == 201:
actor["token"] = r["json"]["token"]
actor["expires_at"] = r["json"]["expires_at"]
return r
def wait_until(probe, timeout=60, interval=0.5):
deadline = time.monotonic() + timeout
last = None
while time.monotonic() < deadline:
try:
if probe():
return time.monotonic()
except Failure as exc:
last = exc
time.sleep(interval)
raise Failure("condition not reached in %ss (%s)" % (timeout, last))
class Suite:
def __init__(self, name):
self.name, self.results = name, []
def case(self, title):
def decorator(fn):
self.results.append((title, fn))
return fn
return decorator
def run(self):
passed = failed = 0
print("## " + self.name)
for title, fn in self.results:
start = time.monotonic()
try:
note = fn()
passed += 1
print("PASS %-62s %6.2fs%s" % (title, time.monotonic() - start, (" " + note) if note else ""))
except Exception as exc: # noqa: BLE001
failed += 1
print("FAIL %-62s %s" % (title, exc))
if os.environ.get("DEBUG"):
traceback.print_exc()
print("summary: %d passed, %d failed" % (passed, failed))
raise SystemExit(1 if failed else 0)
__all__ = ["Client", "Failure", "check", "sh", "sql", "basic", "new_user", "login", "wait_until", "Suite",
"BASE_URL", "TTL_BASE_URL", "TTL_SECONDS", "json"]
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env python3
"""Негативные и контрактные проверки уровня 3/4: аутентификация, KDF, валидация, ACL, пагинация,
атомарность/rollback создания чата, гонка регистрации, параметризация SQL."""
import hashlib
import threading
import uuid
from urllib.parse import quote
from common import BASE_URL, Client, Suite, basic, check, login, new_user, sql
c = Client(BASE_URL)
s = Suite("API, auth, validation, ACL, transactions (" + BASE_URL + ")")
alice = new_user(c, "alice"); login(c, alice)
bob = new_user(c, "bob"); login(c, bob)
eve = new_user(c, "eve"); login(c, eve)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "student-tests", "member_ids": [alice["id"], bob["id"]]})["json"]
CHAT = "/api/v1/chats/" + chat["id"]
@s.case("password stored only as scrypt KDF hash; User has no secret fields")
def _():
row = sql("SELECT password_hash FROM users WHERE id = '%s'" % alice["id"])[0]
check(row.startswith("$scrypt$ln=15,r=8,p=3$"), "unexpected hash format")
check(alice["password"] not in row, "plaintext password in DB")
check(set(alice["user"]) == {"id", "username", "display_name", "created_at"}, "User leaks fields")
other = new_user(c, "same", password=alice["password"])
h2 = sql("SELECT password_hash FROM users WHERE id = '%s'" % other["id"])[0]
check(h2 != row, "same password produced same hash: salt missing")
@s.case("wrong password and unknown user: identical 401 + Basic challenge")
def _():
r1 = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(alice["username"], "wrong-password-123")})
r2 = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("no_such_user_x", "wrong-password-123")})
check(r1["json"]["error"]["message"] == r2["json"]["error"]["message"], "messages differ")
check(r1["headers"]["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"', "challenge mismatch")
@s.case("malformed Basic / Bearer on /auth/sessions / body on login")
def _():
for value in ("Basic", "Basic !!!", "Basic " + "bm9jb2xvbg==", "Bearer " + "x" * 43):
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": value})
c.call("POST", "/api/v1/auth/sessions", 401)
c.call("POST", "/api/v1/auth/sessions", 400, body={"username": alice["username"]},
headers={"Authorization": basic(alice["username"], alice["password"])})
@s.case("password with ':' and non-ASCII UTF-8 works (RFC 7617)")
def _():
u = new_user(c, "colon", password="пароль:с:двоеточием-😀")
login(c, u)
me = c.call("GET", "/api/v1/users/me", actor=u, schema="User")["json"]
check(me["id"] == u["id"], "wrong user")
@s.case("opaque 256-bit token, unique per login, DB stores only SHA-256")
def _():
a, b = dict(alice), dict(alice)
login(c, a); login(c, b)
check(a["token"] != b["token"] and len(a["token"]) == 43, "token not unique/opaque")
check(a["token"] not in (alice["id"], alice["username"]), "token derived from identity")
digest = hashlib.sha256(a["token"].encode()).hexdigest()
check(sql("SELECT count(*) FROM sessions WHERE token_hash = decode('%s','hex')" % digest) == ["1"], "hash not found")
check(sql("SELECT count(*) FROM information_schema.columns WHERE table_name = 'sessions'"
" AND data_type IN ('text', 'character varying')") == ["0"], "sessions has a text column for raw token")
@s.case("only Bearer accepted; Basic and X-User-Id never authenticate")
def _():
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": basic(alice["username"], alice["password"])})
c.call("GET", "/api/v1/chats", 401, headers={"X-User-Id": alice["id"]})
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "A" * 43})
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer short"})
me = c.call("GET", "/api/v1/users/me", actor=bob, headers={"X-User-Id": alice["id"]}, schema="User")["json"]
check(me["id"] == bob["id"], "X-User-Id overrode session")
@s.case("logout revokes only the current session; repeat -> 401")
def _():
u = new_user(c, "logout"); first = dict(u); second = dict(u)
login(c, first); login(c, second)
c.call("GET", "/api/v1/users/me", actor=first, schema="User") # прогреть кэш
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=first)
for path in ("/api/v1/users/me", "/api/v1/chats"):
c.call("GET", path, 401, actor=first)
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=first)
c.call("GET", "/api/v1/users/me", actor=second, schema="User")
check(sql("SELECT count(*) FROM sessions WHERE user_id='%s' AND revoked_at IS NOT NULL" % u["id"]) == ["1"],
"revocation not persisted")
@s.case("strict JSON validation -> 400")
def _():
base = {"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "X", "password": "p" * 12}
bad = [dict(base, extra=1), dict(base, username="UPPER"), dict(base, username="ab"),
dict(base, display_name=" "), dict(base, display_name="x" * 101), dict(base, password="p" * 11),
dict(base, password="p" * 129), dict(base, display_name=5), {"username": base["username"]}]
for body in bad:
c.call("POST", "/api/v1/users", 400, body=body)
c.call("POST", "/api/v1/users", 400, raw=b'{"username": ', headers={"Content-Type": "application/json"})
c.call("POST", "/api/v1/users", 400, raw=b'[1,2]', headers={"Content-Type": "application/json"})
c.call("POST", "/api/v1/users", 400, raw=b'{"username":"a","username":"b"}', headers={"Content-Type": "application/json"})
c.call("POST", "/api/v1/users", 400, raw=b'username=x', headers={"Content-Type": "application/x-www-form-urlencoded"})
c.call("POST", "/api/v1/users", 413, raw=b'{"x":"' + b"a" * 70000 + b'"}', headers={"Content-Type": "application/json"})
@s.case("message text: 4000 code points OK, 4001 / whitespace / sender_id -> 400")
def _():
msg = c.message(alice, chat, "😀" * 4000)["json"]
check(len(msg["text"]) == 4000, "text truncated")
for body in ({"text": "a" * 4001}, {"text": " \n\t "}, {"text": "x", "sender_id": bob["id"]}, {"text": None}, {}):
c.call("POST", CHAT + "/messages", 400, actor=alice, body=body)
@s.case("SQL is parameterized: injection payloads stored verbatim")
def _():
payload = "'); DROP TABLE messages; -- \" \\ %s $1"
msg = c.message(alice, chat, payload)["json"]
check(msg["text"] == payload, "payload altered")
c.call("GET", CHAT + "/messages?limit=1", actor=alice, schema="MessagePage")
c.call("GET", "/api/v1/chats/" + quote("' OR 1=1 --", safe=""), 400, actor=alice)
@s.case("ACL: outsider gets 404 everywhere (even for invalid body)")
def _():
c.call("GET", CHAT, 404, actor=eve)
c.call("GET", CHAT + "/messages", 404, actor=eve)
c.call("POST", CHAT + "/messages", 404, actor=eve, body={"text": "x"})
c.call("POST", CHAT + "/messages", 404, actor=eve, body={"text": ""})
c.call("GET", "/api/v1/chats/" + str(uuid.uuid4()), 404, actor=alice)
c.call("GET", "/api/v1/chats/not-a-uuid", 400, actor=alice)
got = c.call("GET", CHAT, actor=bob, schema="Chat")["json"]
check(got["member_ids"] == [alice["id"], bob["id"]], "member order/content changed")
@s.case("create chat validation: duplicates, caller missing, unknown member")
def _():
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": [alice["id"], alice["id"]]})
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": [bob["id"]]})
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": []})
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": " ", "member_ids": [alice["id"]]})
@s.case("compound create-chat rolls back on FK failure (no orphan chat)")
def _():
title = "rollback-" + uuid.uuid4().hex
before = sql("SELECT count(*) FROM chats")[0]
c.call("POST", "/api/v1/chats", 400, actor=alice,
body={"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]})
check(sql("SELECT count(*) FROM chats WHERE title = '%s'" % title) == ["0"], "orphan chat committed")
check(sql("SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL") == ["0"],
"orphan membership")
return "chats before=%s, failed insert left 0 rows" % before
@s.case("registration race: 20 parallel same username -> exactly one 201")
def _():
username = "race_" + uuid.uuid4().hex[:12]
statuses, lock = [], threading.Lock()
barrier = threading.Barrier(20)
def worker():
local = Client(BASE_URL, timeout=30)
barrier.wait()
r = local.call("POST", "/api/v1/users", [201, 409],
body={"username": username, "display_name": "R", "password": "Race-password-123"})
with lock:
statuses.append(r["status"])
threads = [threading.Thread(target=worker) for _ in range(20)]
[t.start() for t in threads]; [t.join() for t in threads]
check(sorted(statuses) == [201] + [409] * 19, "statuses: %s" % sorted(statuses))
check(sql("SELECT count(*) FROM users WHERE username = '%s'" % username) == ["1"], "duplicate rows")
return "201x1, 409x19, rows=1"
@s.case("keyset pagination: 120 msgs, varying limit, no gaps/duplicates")
def _():
room = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "pages", "member_ids": [alice["id"], bob["id"]]})["json"]
path = "/api/v1/chats/" + room["id"] + "/messages"
sent = [c.message(alice if i % 2 else bob, room, "m%03d" % i)["json"] for i in range(120)]
got, cursor, limits, n = [], None, [7, 1, 50, 100, 3], 0
while True:
q = "?limit=%d" % limits[n % len(limits)] + ("&cursor=" + quote(cursor, safe="") if cursor else "")
page = c.call("GET", path + q, actor=bob, schema="MessagePage")["json"]
got.extend(page["items"]); cursor = page["next_cursor"]; n += 1
if cursor is None:
break
check([m["id"] for m in got] == [m["id"] for m in sent], "order/completeness mismatch")
first = c.call("GET", path + "?limit=2", actor=bob, schema="MessagePage")["json"]
c.call("GET", CHAT + "/messages?cursor=" + quote(first["next_cursor"], safe=""), 400, actor=alice)
for q in ("?limit=0", "?limit=101", "?limit=abc", "?limit=-1", "?limit=1&limit=2", "?cursor=garbage", "?cursor="):
c.call("GET", path + q, 400, actor=bob)
default = c.call("GET", path, actor=bob, schema="MessagePage")["json"]
check(len(default["items"]) == 50 and default["next_cursor"], "default limit must be 50")
return "%d pages" % n
@s.case("chat list: only own chats, ordered, cursor bound to user")
def _():
u = new_user(c, "lister"); login(c, u)
made = [c.call("POST", "/api/v1/chats", 201, actor=u, schema="Chat",
body={"title": "c%d" % i, "member_ids": [u["id"]]})["json"]["id"] for i in range(3)]
got, cursor = [], None
while True:
page = c.call("GET", "/api/v1/chats?limit=1" + ("&cursor=" + quote(cursor, safe="") if cursor else ""),
actor=u, schema="ChatPage")["json"]
got += [x["id"] for x in page["items"]]; cursor = page["next_cursor"]
if cursor is None:
break
foreign = cursor
check(got == made, "chat list mismatch")
c.call("GET", "/api/v1/chats?cursor=" + quote(foreign, safe=""), 400, actor=alice)
@s.case("read-after-write: confirmed message visible to next read")
def _():
m = c.message(bob, chat, "raw-" + uuid.uuid4().hex)["json"]
items, cursor = [], None
while True:
page = c.call("GET", CHAT + "/messages?limit=100" + ("&cursor=" + quote(cursor, safe="") if cursor else ""),
actor=alice, schema="MessagePage")["json"]
items += page["items"]; cursor = page["next_cursor"]
if not cursor:
break
check(items[-1] == m, "last message is not the just-written one")
@s.case("unknown route 404 / wrong method 405 in error format")
def _():
c.call("GET", "/api/v1/nope", 404)
r = c.call("PUT", "/api/v1/users", 405, body={})
check(r["json"]["error"]["code"] == "invalid_request", "405 code")
if __name__ == "__main__":
s.run()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""In-process проверки политики кэша сессий против настоящего Redis/Valkey (нужен CACHE_URL[_FILE]).
Сценарий гонки: запрос A прочитал сессию из PostgreSQL ДО logout, а записать её в кэш пытается ПОСЛЕ
logout. Без защиты отозванный токен жил бы в кэше до SESSION_CACHE_TTL_SECONDS. Защита — «надгробие»
и атомарный Lua SET-if-not-revoked. Запуск в Compose: make test-cache-race.
"""
import asyncio
import os
import secrets
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
os.environ.setdefault("DATABASE_URL", "postgresql://unused") # БД этому тесту не нужна
from messenger.config import load # noqa: E402
from messenger.sessions import KEY, TOMBSTONE, Principal, SessionCache # noqa: E402
async def main():
settings = load()
if not settings.cache_enabled:
raise SystemExit("CACHE_URL or CACHE_URL_FILE is required")
cache = SessionCache(settings)
cache.degraded = False
user = {"id": "00000000-0000-4000-8000-000000000000", "username": "cache_test", "display_name": "t",
"created_at": "2026-01-01T00:00:00.000000Z"}
failures = 0
def report(ok, title, note=""):
nonlocal failures
failures += 0 if ok else 1
print(("PASS " if ok else "FAIL ") + title + ((" " + note) if note else ""))
th = secrets.token_bytes(32)
p = Principal(user=user, expires_at=time.time() + 3600, token_hash=th)
await cache.put(p)
report((await cache.get(th)) is not None, "read-through put makes entry readable")
ttl = await cache.client.pttl(KEY + th.hex())
report(0 < ttl <= settings.session_cache_ttl_seconds * 1000, "entry TTL capped by SESSION_CACHE_TTL_SECONDS",
"pttl=%dms" % ttl)
await cache.invalidate(th) # logout
report((await cache.get(th)) is None, "invalidate removes entry")
await cache.put(p) # «опоздавший» read-through после logout
report((await cache.client.exists(KEY + th.hex())) == 0, "late put after logout is refused by tombstone")
tomb = await cache.client.pttl(TOMBSTONE + th.hex())
report(tomb > settings.session_cache_ttl_seconds * 1000, "tombstone outlives any cache entry", "pttl=%dms" % tomb)
th2 = secrets.token_bytes(32)
await cache.put(Principal(user=user, expires_at=time.time() + 1.2, token_hash=th2))
ttl2 = await cache.client.pttl(KEY + th2.hex())
report(0 < ttl2 <= 1200, "entry never outlives session expiry", "pttl=%dms" % ttl2)
await asyncio.sleep(1.3)
report((await cache.get(th2)) is None, "expired session not served from cache")
th3 = secrets.token_bytes(32)
await cache.put(Principal(user=user, expires_at=time.time() + 3600, token_hash=th3))
cache._fail("test", ConnectionError("simulated"))
report((await cache.get(th3)) is None, "degraded mode: cache is not read until outbox drained")
await cache.client.delete(KEY + th.hex(), TOMBSTONE + th.hex(), KEY + th3.hex())
await cache.close()
print("summary: %s" % ("all passed" if not failures else "%d failed" % failures))
raise SystemExit(1 if failures else 0)
if __name__ == "__main__":
asyncio.run(main())
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Истечение сессии при коротком SESSION_TTL_SECONDS (экземпляр api-ttl, профиль compose `ttl`).
Проверяет и путь через кэш Redis (запись кэша прогрета сразу после входа), и путь через PostgreSQL:
TTL записи в кэше = min(SESSION_CACHE_TTL_SECONDS, остаток сессии), поэтому кэш не продлевает сессию.
"""
import datetime as dt
import time
from common import TTL_BASE_URL, TTL_SECONDS, Client, Suite, check, login, new_user, sql
c = Client(TTL_BASE_URL)
s = Suite("session expiry, SESSION_TTL_SECONDS=%g (%s)" % (TTL_SECONDS, TTL_BASE_URL))
@s.case("expires_at = now + SESSION_TTL_SECONDS")
def _():
u = new_user(c, "ttl"); login(c, u)
left = dt.datetime.fromisoformat(u["expires_at"][:-1] + "+00:00") - dt.datetime.now(dt.timezone.utc)
check(0 < left.total_seconds() <= TTL_SECONDS + 0.5, "unexpected TTL: %s" % left)
return "remaining %.2fs" % left.total_seconds()
@s.case("token valid before expiry, 401 Bearer after (cache warmed)")
def _():
u = new_user(c, "ttl2"); login(c, u)
c.call("GET", "/api/v1/users/me", actor=u, schema="User") # заполняет кэш
c.call("GET", "/api/v1/chats", actor=u, schema="ChatPage")
time.sleep(TTL_SECONDS + 1.0)
r = c.call("GET", "/api/v1/users/me", 401, actor=u)
check(r["headers"]["WWW-Authenticate"].startswith("Bearer"), "challenge")
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=u)
rows = sql("SELECT (expires_at < clock_timestamp())::text, (revoked_at IS NULL)::text FROM sessions s"
" JOIN users u ON u.id = s.user_id WHERE u.username = '%s'" % u["username"])
check(rows == ["true|true"], "expiry must come from expires_at, not deletion/revocation: %s" % rows)
@s.case("re-login after expiry issues a new valid session")
def _():
u = new_user(c, "ttl3"); login(c, u)
old = u["token"]
time.sleep(TTL_SECONDS + 1.0)
c.call("GET", "/api/v1/users/me", 401, actor=u)
login(c, u)
check(u["token"] != old, "token reused")
c.call("GET", "/api/v1/users/me", actor=u, schema="User")
if __name__ == "__main__":
s.run()
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Отказы зависимостей: Redis (кэш) и PostgreSQL (источник истины).
ВНИМАНИЕ: тест останавливает и снова запускает контейнеры redis и postgres (по умолчанию через
docker compose; команды переопределяются STOP_DB/START_DB/STOP_CACHE/START_CACHE). Volumes не трогает.
"""
import time
import uuid
from common import BASE_URL, Client, Failure, Suite, basic, check, login, new_user, sh, sql, wait_until
c = Client(BASE_URL, timeout=10)
s = Suite("dependency failures (" + BASE_URL + ")")
alice = new_user(c, "fa"); login(c, alice)
bob = new_user(c, "fb"); login(c, bob)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "failures", "member_ids": [alice["id"], bob["id"]]})["json"]
PATH = "/api/v1/chats/" + chat["id"] + "/messages"
def timed(fn):
t = time.monotonic(); r = fn(); return r, time.monotonic() - t
@s.case("Redis down: API bypasses cache via PostgreSQL, no anonymous trust")
def _():
c.call("GET", "/api/v1/users/me", actor=alice, schema="User") # запись в кэше есть
victim = new_user(c, "fv"); login(c, victim)
c.call("GET", "/api/v1/users/me", actor=victim, schema="User")
sh("stop_cache")
try:
_, took = timed(lambda: c.call("GET", "/api/v1/users/me", actor=alice, schema="User"))
check(took < 2.0, "fallback too slow: %.2fs" % took)
c.call("GET", "/health/ready", schema="Health") # кэш не критичен
c.message(alice, chat, "while redis is down")
fresh = new_user(c, "fn"); login(c, fresh) # вход без Redis
c.call("GET", "/api/v1/users/me", actor=fresh, schema="User")
c.call("GET", "/api/v1/users/me", 401) # аноним — 401
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "B" * 43})
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=victim) # logout при мёртвом Redis
c.call("GET", "/api/v1/users/me", 401, actor=victim)
pending = sql("SELECT count(*) FROM session_cache_invalidations")[0]
finally:
sh("start_cache")
# После возврата Redis старая запись кэша victim не должна «воскресить» отозванный токен.
wait_until(lambda: sql("SELECT count(*) FROM session_cache_invalidations") == ["0"], timeout=30)
for _ in range(10):
c.call("GET", "/api/v1/users/me", 401, actor=victim)
time.sleep(0.3)
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
return "fallback latency %.3fs; outbox rows during outage=%s, drained after recovery" % (took, pending)
@s.case("PostgreSQL down: bounded 503 in error format; anonymous still 401")
def _():
before = len(c.call("GET", PATH + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"])
sh("stop_db")
observed = {}
try:
c.call("GET", "/health/live", schema="Health")
r, took = timed(lambda: c.call("GET", "/health/ready", 503))
observed["ready"] = round(took, 2)
for name, call in {
"post_message": lambda: c.call("POST", PATH, 503, actor=alice, body={"text": "db down"}),
"history": lambda: c.call("GET", PATH, 503, actor=bob),
"login": lambda: c.call("POST", "/api/v1/auth/sessions", 503,
headers={"Authorization": basic(alice["username"], alice["password"])}),
"register": lambda: c.call("POST", "/api/v1/users", 503,
body={"username": "x" + uuid.uuid4().hex[:10], "display_name": "x", "password": "p" * 12}),
}.items():
r, took = timed(call)
check(r["json"]["error"]["code"] == "unavailable", name + ": wrong code")
check(took < 5.0, name + ": not bounded (%.2fs)" % took)
check("psycopg" not in r["json"]["error"]["message"].lower(), "leaks internals")
observed[name] = round(took, 2)
c.call("GET", "/api/v1/users/me", 401) # без токена — 401
r = c.call("GET", "/api/v1/chats", [401, 503], headers={"Authorization": "Bearer " + "C" * 43})
check(r["status"] != 200, "unknown token accepted")
finally:
sh("start_db")
t0 = time.monotonic()
wait_until(lambda: c.call("GET", "/health/ready", [200, 503])["status"] == 200, timeout=90)
recovered = time.monotonic() - t0
after = c.call("GET", PATH + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"]
check(len(after) == before, "data changed across DB outage")
c.message(alice, chat, "after db recovery")
return "latency(s)=%s; ready again in %.1fs" % (observed, recovered)
if __name__ == "__main__":
try:
s.run()
except Failure as exc:
print("FAIL", exc)
raise SystemExit(1)