Исправление по замечанию: отзыв сессии выдерживает гонку с наполнением кэша

This commit is contained in:
alenchha
2026-10-23 23:15:21 +03:00
parent 1a60b9cd1f
commit 4ee3cbb4ea
16 changed files with 288 additions and 179 deletions
+78
View File
@@ -3,6 +3,7 @@
import hashlib
import pathlib
import subprocess
import threading
import time
from common import arguments, call, chat_with, expect, member, run
@@ -25,6 +26,15 @@ def session_key(token):
return "session:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
def session_rows(token):
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
done = subprocess.run(
COMPOSE + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-t", "-A",
"-c", "select count(*) from sessions where token_hash = '\\x%s'::bytea" % digest],
cwd=str(ROOT), capture_output=True, text=True, check=True)
return int(done.stdout.strip())
def wait_ready(base, seconds=90):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
@@ -122,12 +132,80 @@ def cache_survives_its_own_restart(base):
expect(valkey("exists", key) == "1", "после рестарта кэш больше не наполняется")
def revoked_session_cannot_be_resurrected_by_a_race(base):
actor = member(base, "race")
token = actor["token"]
key = session_key(token)
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
expect(call(base, "GET", "/api/v1/users/me", token=token)["status"] == 200, "свежая сессия не работает")
expect(valkey("exists", key) == "1", "после входа сессии нет в кэше")
holder = subprocess.Popen(
COMPOSE + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-X", "-q"],
cwd=str(ROOT), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
)
holder.stdin.write("BEGIN;\nSELECT 1 FROM sessions WHERE token_hash = '\\x%s'::bytea FOR UPDATE;\n" % digest)
holder.stdin.flush()
time.sleep(0.5)
outcome = {}
def logout():
outcome["status"] = call(base, "DELETE", "/api/v1/auth/sessions/current", token=token, timeout=30)["status"]
worker = threading.Thread(target=logout)
worker.start()
try:
deadline = time.monotonic() + 5
while time.monotonic() < deadline and valkey("get", key).startswith("{"):
time.sleep(0.05)
during = call(base, "GET", "/api/v1/users/me", token=token)
finally:
holder.stdin.write("COMMIT;\n\\q\n")
holder.stdin.flush()
holder.wait(timeout=15)
worker.join(timeout=30)
expect(outcome.get("status") == 204, "logout вернул %s вместо 204" % outcome.get("status"))
after = call(base, "GET", "/api/v1/users/me", token=token)
expect(after["status"] == 401,
"после подтверждённого logout токен ожил: /users/me дал %s, ttl ключа %s (запрос во время гонки дал %s)"
% (after["status"], valkey("ttl", key), during["status"]))
wrote = call(base, "GET", "/api/v1/chats", token=token)
expect(wrote["status"] == 401, "отозванный токен всё ещё читает список чатов: %s" % wrote["status"])
def failed_logout_leaves_cache_and_database_consistent(base):
actor = member(base, "rollback")
token = actor["token"]
key = session_key(token)
expect(call(base, "GET", "/api/v1/users/me", token=token)["status"] == 200, "свежая сессия не работает")
compose("pause", "postgres")
try:
refused = call(base, "DELETE", "/api/v1/auth/sessions/current", token=token, timeout=60)
expect(refused["status"] == 503, "logout при недоступной базе дал %s вместо 503" % refused["status"])
finally:
compose("unpause", "postgres")
wait_ready(base)
expect(valkey("get", key) != "revoked", "неподтверждённый logout оставил надгробие в кэше")
rows = session_rows(token)
answer = call(base, "GET", "/api/v1/users/me", token=token)["status"]
if rows == 1:
expect(answer == 200, "строка сессии в базе есть, но API отвечает %s" % answer)
expect(call(base, "DELETE", "/api/v1/auth/sessions/current", token=token)["status"] == 204, "повторный logout не прошёл")
expect(call(base, "GET", "/api/v1/users/me", token=token)["status"] == 401, "после подтверждённого logout токен жив")
else:
expect(answer == 401, "строки сессии в базе нет, но API отвечает %s" % answer)
TESTS = [
revoked_session_stays_revoked_after_cache_restart,
logout_is_not_confirmed_while_cache_is_down,
cached_sessions_do_not_cross_users,
cache_is_repopulated_after_a_miss,
cache_survives_its_own_restart,
revoked_session_cannot_be_resurrected_by_a_race,
failed_logout_leaves_cache_and_database_consistent,
hung_database_fails_fast,
]