Implement lab 7 transport security and worker containment
This commit is contained in:
@@ -0,0 +1,226 @@
|
||||
import asyncio
|
||||
import time
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from redis.asyncio import Redis
|
||||
from sqlalchemy import select
|
||||
|
||||
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
|
||||
from messenger.identity.application.ports import SessionDirectory
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.identity.infrastructure.postgres import (
|
||||
PostgresIdentityUnitOfWork,
|
||||
PostgresSessionDirectory,
|
||||
PostgresSessionRepository,
|
||||
SessionRow,
|
||||
)
|
||||
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
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))
|
||||
expires_at: datetime = await scalar(
|
||||
select(SessionRow.expires_at).where(SessionRow.user_id == UUID(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_leaves_tombstone_after_commit(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()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["remove", "commit"])
|
||||
async def test_logout_rejected_by_database_changes_nothing(
|
||||
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch, failure: str
|
||||
) -> None:
|
||||
async def broken(self: PostgresSessionRepository, token_hash: bytes) -> None:
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
|
||||
async def broken_commit(self: PostgresIdentityUnitOfWork) -> None:
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
|
||||
cache = Redis.from_url(valkey["url"])
|
||||
logout = "/api/v1/auth/sessions/current"
|
||||
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
|
||||
with monkeypatch.context() as patch:
|
||||
if failure == "remove":
|
||||
patch.setattr(PostgresSessionRepository, "remove", broken)
|
||||
else:
|
||||
patch.setattr(PostgresIdentityUnitOfWork, "commit", broken_commit)
|
||||
failed = await http.delete(logout, headers=actor(alice))
|
||||
assert failed.status_code == 503
|
||||
assert failed.json()["error"]["code"] == "unavailable"
|
||||
assert await cache.get(key_of(token_of(alice))) is None
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
|
||||
assert (await http.delete(logout, headers=actor(alice))).status_code == 204
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
|
||||
await cache.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loss", ["none", "flushall", "evict", "replacement"])
|
||||
async def test_fill_racing_with_logout_does_not_revive_token(
|
||||
valkey: dict[str, str], loss: str
|
||||
) -> None:
|
||||
async with (
|
||||
Redis.from_url(valkey["url"]) as cache,
|
||||
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]
|
||||
|
||||
directory._origin = SlowOrigin()
|
||||
async with asyncio.TaskGroup() as group:
|
||||
reader = group.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
directory._origin = origin
|
||||
assert (
|
||||
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
).status_code == 204
|
||||
key = key_of(token_of(alice))
|
||||
assert await cache.get(f"{key}:fill") is None
|
||||
if loss == "flushall":
|
||||
await cache.flushall()
|
||||
elif loss in {"evict", "replacement"}:
|
||||
await cache.delete(key)
|
||||
if loss == "replacement":
|
||||
await cache.set(f"{key}:fill", "another-reader", px=1000)
|
||||
finally:
|
||||
released.set()
|
||||
assert reader.result().status_code == 200
|
||||
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loss", ["flushall", "evict"])
|
||||
async def test_cache_loss_before_logout_commit_cannot_refill_deleted_session(
|
||||
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch, loss: str
|
||||
) -> None:
|
||||
revoked, release_commit, reading = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
||||
revoke = CachedSessionDirectory.revoke
|
||||
find = PostgresSessionDirectory.find
|
||||
|
||||
async def paused_revoke(self: CachedSessionDirectory, session: Session) -> None:
|
||||
await revoke(self, session)
|
||||
revoked.set()
|
||||
await release_commit.wait()
|
||||
|
||||
async def observed_find(
|
||||
self: PostgresSessionDirectory, token_hash: bytes, now: datetime
|
||||
) -> Session | None:
|
||||
reading.set()
|
||||
return await find(self, token_hash, now)
|
||||
|
||||
async with (
|
||||
Redis.from_url(valkey["url"]) as cache,
|
||||
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
|
||||
monkeypatch.setattr(CachedSessionDirectory, "revoke", paused_revoke)
|
||||
async with asyncio.TaskGroup() as group:
|
||||
logout = group.create_task(
|
||||
http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(revoked.wait(), 5)
|
||||
if loss == "flushall":
|
||||
await cache.flushall()
|
||||
else:
|
||||
await cache.delete(key_of(token_of(alice)))
|
||||
monkeypatch.setattr(PostgresSessionDirectory, "find", observed_find)
|
||||
reader = group.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
|
||||
await asyncio.wait_for(reading.wait(), 5)
|
||||
done, _ = await asyncio.wait({reader}, timeout=0.1)
|
||||
assert not done
|
||||
finally:
|
||||
release_commit.set()
|
||||
assert logout.result().status_code == 204
|
||||
assert reader.result().status_code == 401
|
||||
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")
|
||||
chat = await make_chat(http, alice)
|
||||
posted = await http.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages", json={"text": "без кэша"}, headers=keyed(alice)
|
||||
)
|
||||
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 posted.status_code == 201
|
||||
assert logout.status_code == 503
|
||||
assert logout.json()["error"]["code"] == "unavailable"
|
||||
assert still.status_code == 200
|
||||
Reference in New Issue
Block a user