7 — Т2302 — ебедев — на 5
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
#!/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 import vault # noqa: E402
|
||||
from messenger.config import load # noqa: E402
|
||||
from messenger.sessions import KEY, TOMBSTONE, Principal, SessionCache # noqa: E402
|
||||
|
||||
|
||||
async def main():
|
||||
client = vault.init("api") # lab7: ACL-учётные данные Redis — из OpenBao (AppRole сервиса api)
|
||||
settings = load(client.data if client else None)
|
||||
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())
|
||||
Reference in New Issue
Block a user