ЛР 2: PostgreSQL, сессии в Valkey, трек 2
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4/5: revocation must outlive the cache and outages must never grant trust."""
|
||||
import pathlib
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from common import arguments, call, chat_with, expect, member, run
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(COMPOSE + list(args), cwd=str(ROOT), check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(base, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if call(base, "GET", "/health/ready")["status"] == 200:
|
||||
return
|
||||
except AssertionError:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("API не стал ready за %d с" % seconds)
|
||||
|
||||
|
||||
def revoked_session_stays_revoked_after_cache_restart(base):
|
||||
actor = member(base, "revoke")
|
||||
expect(call(base, "GET", "/api/v1/users/me", token=actor["token"])["status"] == 200, "свежая сессия не работает")
|
||||
expect(call(base, "DELETE", "/api/v1/auth/sessions/current", token=actor["token"])["status"] == 204, "logout не вернул 204")
|
||||
compose("restart", "valkey")
|
||||
wait_ready(base)
|
||||
after = call(base, "GET", "/api/v1/users/me", token=actor["token"])
|
||||
expect(after["status"] == 401, "отозванная сессия вернула доступ после рестарта кэша: %s" % after["status"])
|
||||
|
||||
|
||||
def logout_is_not_confirmed_while_cache_is_down(base):
|
||||
actor = member(base, "logoutdown")
|
||||
expect(call(base, "GET", "/api/v1/users/me", token=actor["token"])["status"] == 200, "свежая сессия не работает")
|
||||
compose("stop", "valkey")
|
||||
try:
|
||||
refused = call(base, "DELETE", "/api/v1/auth/sessions/current", token=actor["token"])
|
||||
expect(refused["status"] == 503, "logout без кэша дал %s вместо 503" % refused["status"])
|
||||
still = call(base, "GET", "/api/v1/users/me", token=actor["token"])
|
||||
expect(still["status"] == 200, "сессия не отозвана, но доступ уже потерян: %s" % still["status"])
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
wait_ready(base)
|
||||
expect(call(base, "DELETE", "/api/v1/auth/sessions/current", token=actor["token"])["status"] == 204, "повторный logout не прошёл")
|
||||
expect(call(base, "GET", "/api/v1/users/me", token=actor["token"])["status"] == 401, "после подтверждённого logout токен жив")
|
||||
|
||||
|
||||
def cached_sessions_do_not_cross_users(base):
|
||||
alice = member(base, "cross")
|
||||
bob = member(base, "cross2")
|
||||
for _ in range(3):
|
||||
first = call(base, "GET", "/api/v1/users/me", token=alice["token"])["json"]
|
||||
second = call(base, "GET", "/api/v1/users/me", token=bob["token"])["json"]
|
||||
expect(first["id"] == alice["id"] and second["id"] == bob["id"], "кэш перепутал владельцев сессий")
|
||||
chat = chat_with(base, alice, bob)
|
||||
sent = call(base, "POST", "/api/v1/chats/%s/messages" % chat["id"], body={"text": "от боба"}, token=bob["token"])
|
||||
expect(sent["json"]["sender_id"] == bob["id"], "sender_id взят не из сессии")
|
||||
|
||||
|
||||
def hung_database_fails_fast(base):
|
||||
actor = member(base, "hang")
|
||||
compose("pause", "postgres")
|
||||
try:
|
||||
started = time.monotonic()
|
||||
result = call(base, "GET", "/api/v1/chats", token=actor["token"], timeout=60)
|
||||
elapsed = time.monotonic() - started
|
||||
expect(result["status"] == 503, "зависшая БД дала %s вместо 503" % result["status"])
|
||||
expect(elapsed < 10, "ответ пришёл за %.1f с при заявленном клиентском лимите 6 с" % elapsed)
|
||||
ready = call(base, "GET", "/health/ready", timeout=60)
|
||||
expect(ready["status"] == 503, "/health/ready при зависшей БД дал %s" % ready["status"])
|
||||
expect(call(base, "GET", "/health/live", timeout=60)["status"] == 200, "/health/live упал вместе с БД")
|
||||
finally:
|
||||
compose("unpause", "postgres")
|
||||
wait_ready(base)
|
||||
expect(call(base, "GET", "/api/v1/chats", token=actor["token"])["status"] == 200, "после возврата БД доступ не восстановился")
|
||||
|
||||
|
||||
TESTS = [
|
||||
revoked_session_stays_revoked_after_cache_restart,
|
||||
logout_is_not_confirmed_while_cache_is_down,
|
||||
cached_sessions_do_not_cross_users,
|
||||
hung_database_fails_fast,
|
||||
]
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TESTS, arguments(__doc__).base_url)
|
||||
Reference in New Issue
Block a user