Files
mtusi2026lab2/student-tests/api/test_cache.py
T
ArtyomandClaude Opus 5.5 416ce4f9db Carry over the lab 2 solution
Bring the application, own tests, Dockerfile, toolchain, compose
stack, migrations, secret generator, restart hook, evidence scripts and
CI job from the lab 2 solution commit 8cddb09 unchanged, merge the lab
2 Makefile targets into the lab 3 skeleton Makefile without touching
its targets, and append the lab 2 solution variables to the skeleton
.env.example. The package version follows the contract version 1.3.0.

This is the starting point of the lab 3 cycle: lint, own tests and the
offline skeleton check pass before any lab 3 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 11:26:15 +03:00

119 lines
5.1 KiB
Python

import asyncio
import time
from datetime import datetime
from hashlib import sha256
from redis.asyncio import Redis
from conftest import actor, bearer, register, resolve, running_app, scalar
from messenger.identity.application.ports import SessionDirectory
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
BEARER = 'Bearer realm="messenger"'
def key_of(token: str) -> str:
return f"session:{sha256(token.encode()).hexdigest()}"
def token_of(user: dict) -> str:
return actor(user)["Authorization"].split()[1]
async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
hits = (await cache.info("stats"))["keyspace_hits"]
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
key = key_of(token_of(alice))
stored = str(await cache.get(key))
sql = "SELECT expires_at FROM sessions WHERE user_id = $1::uuid"
expires_at: datetime = await scalar(sql, alice["id"])
assert alice["id"] in stored and token_of(alice) not in stored
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
await cache.aclose()
async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
).status_code == 204
assert await cache.get(key_of(token_of(alice))) == b"-"
response = await http.get("/api/v1/users/me", headers=actor(alice))
assert response.status_code == 401
assert response.headers["WWW-Authenticate"] == BEARER
await cache.aclose()
async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, str]) -> None:
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
directory = await resolve(http, SessionDirectory)
assert isinstance(directory, CachedSessionDirectory)
origin = directory._origin
stale: list[Session | None] = []
entered, released = asyncio.Event(), asyncio.Event()
class SlowOrigin:
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
stale.append(await origin.find(token_hash, now))
entered.set()
await released.wait()
return stale[-1]
async def invalidate(self, session: Session) -> None:
await origin.invalidate(session)
directory._origin = SlowOrigin()
reader = asyncio.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
await entered.wait()
directory._origin = origin
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
).status_code == 204
released.set()
assert (await reader).status_code == 200
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
async def test_flushall_loses_nothing(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
bob = await register(http, "bob")
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(bob))
).status_code == 204
await cache.flushall()
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await http.get("/api/v1/users/me", headers=actor(bob))).status_code == 401
await cache.aclose()
async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
async with running_app(cache_url="redis://127.0.0.1:1/0") as http:
alice = await register(http, "alice")
started = time.perf_counter()
me = await http.get("/api/v1/users/me", headers=actor(alice))
stranger = await http.get("/api/v1/users/me", headers=bearer("x" * 43))
elapsed = time.perf_counter() - started
ready = await http.get("/health/ready")
logout = await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
still = await http.get("/api/v1/users/me", headers=actor(alice))
assert me.json() == alice
assert stranger.status_code == 401
assert stranger.headers["WWW-Authenticate"] == BEARER
assert elapsed < 1
assert ready.status_code == 200
assert logout.status_code == 503
assert logout.json()["error"]["code"] == "unavailable"
assert still.status_code == 200