Prevent revoked session refills and escape proxy error identifiers

This commit is contained in:
Artyom
2026-11-06 01:49:41 +03:00
parent da2f392442
commit 2af24d7762
8 changed files with 312 additions and 28 deletions
+3 -3
View File
@@ -32,9 +32,9 @@ defaults
timeout http-keep-alive 5s
timeout queue 3s
timeout check 1s
http-error status 502 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Upstream replica failed","request_id":"%[var(txn.request_id)]"}}'
http-error status 503 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"No ready API replica","request_id":"%[var(txn.request_id)]"}}'
http-error status 504 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Upstream timeout","request_id":"%[var(txn.request_id)]"}}'
http-error status 502 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Upstream replica failed","request_id":"%[var(txn.request_id),json(ascii)]"}}'
http-error status 503 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"No ready API replica","request_id":"%[var(txn.request_id),json(ascii)]"}}'
http-error status 504 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Upstream timeout","request_id":"%[var(txn.request_id),json(ascii)]"}}'
frontend public
bind :8080
@@ -1,11 +1,11 @@
## 1. Identity: сохранение минимума уровня «3»
- [ ] 1.1 Добавить одноразовый маркер заполнения и атомарную проверку/инвалидацию в Valkey; согласовать DELETE, отзыв и COMMIT с блокирующим чтением сессии.
- [ ] 1.2 Добавить offline-регрессии потери/смены маркера и интеграционные сценарии logout + очистка/вытеснение, включая очистку до COMMIT; выполнить только offline-подмножество pytest.
- [x] 1.1 Добавить одноразовый маркер заполнения и атомарную проверку/инвалидацию в Valkey; согласовать DELETE, отзыв и COMMIT с блокирующим чтением сессии.
- [x] 1.2 Добавить offline-регрессии потери/смены маркера и интеграционные сценарии logout + очистка/вытеснение, включая очистку до COMMIT; выполнить только offline-подмножество pytest.
## 2. Инфраструктура LB
- [ ] 2.1 Применить JSON-конвертер в телах 502/503/504, сохранить заголовок; проверить шаблоны offline на специальных символах.
- [x] 2.1 Применить JSON-конвертер в телах 502/503/504, сохранить заголовок; проверить шаблоны offline на специальных символах.
## 3. Проверки и передача следующему этапу
@@ -69,10 +69,10 @@ class CloseSessionHandler:
self._revocations = revocations
async def __call__(self, command: CloseSession) -> None:
await self._revocations.revoke(command.session)
try:
async with self._uow.transaction():
await self._uow.sessions.remove(command.session.token_hash)
await self._revocations.revoke(command.session)
self._uow.record(SessionClosed(user_id=command.session.user_id))
await self._uow.commit()
except BaseException:
@@ -166,10 +166,12 @@ class PostgresSessionDirectory:
async with self._database.session() as session:
row = (
await session.execute(
select(SessionRow).where(
select(SessionRow)
.where(
SessionRow.token_hash == token_hash,
SessionRow.expires_at > now,
)
.with_for_update(read=True, key_share=True)
)
).scalar_one_or_none()
if row is None:
@@ -1,7 +1,7 @@
import time
from collections.abc import Awaitable
from datetime import datetime, timedelta
from uuid import UUID
from uuid import UUID, uuid4
from redis.asyncio import Redis
from redis.exceptions import RedisError
@@ -13,6 +13,16 @@ from messenger.shared.application.ports import Logger
REVOKED = "-"
FAILURES = (RedisError, OSError)
FILL = """
if redis.call('GET', KEYS[2]) ~= ARGV[1] then return false end
redis.call('DEL', KEYS[2])
if ARGV[2] == '' then return false end
return redis.call('SET', KEYS[1], ARGV[2], 'PXAT', ARGV[3], 'NX')
"""
REVOKE = """
redis.call('SET', KEYS[1], ARGV[1], 'PXAT', ARGV[2])
return redis.call('DEL', KEYS[2])
"""
def key_of(token_hash: bytes) -> str:
@@ -72,18 +82,26 @@ class CachedSessionDirectory:
if cached is not None:
session = decode(token_hash, cached)
return session if session.expires_at > now else None
marker, nonce = f"{key}:fill", uuid4().hex
until = milliseconds(now + self._limit)
reserved = self._closed() and await self._quietly(
self._client.set(marker, nonce, pxat=until, nx=True)
)
session = await self._origin.find(token_hash, now)
if session is not None and self._closed():
until = milliseconds(min(session.expires_at, now + self._limit))
await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True))
if reserved and self._closed():
value = encode(session) if session is not None else ""
if session is not None:
until = min(until, milliseconds(session.expires_at))
await self._quietly(self._client.eval(FILL, 2, key, marker, nonce, value, until))
return session
async def revoke(self, session: Session) -> None:
if not self._closed():
raise Unavailable("кэш сессий недоступен")
key = key_of(session.token_hash)
try:
await self._client.set(
key_of(session.token_hash), REVOKED, pxat=milliseconds(session.expires_at)
await self._client.eval(
REVOKE, 2, key, f"{key}:fill", REVOKED, milliseconds(session.expires_at)
)
except FAILURES as error:
self._trip(error)
+91 -14
View File
@@ -11,7 +11,12 @@ 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 PostgresSessionRepository, SessionRow
from messenger.identity.infrastructure.postgres import (
PostgresIdentityUnitOfWork,
PostgresSessionDirectory,
PostgresSessionRepository,
SessionRow,
)
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.shared.application.errors import Unavailable
@@ -44,7 +49,7 @@ async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None
await cache.aclose()
async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -> None:
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")
@@ -59,19 +64,26 @@ async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -
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
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:
patch.setattr(PostgresSessionRepository, "remove", broken)
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"
@@ -82,8 +94,14 @@ async def test_logout_rejected_by_database_changes_nothing(
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:
@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)
@@ -99,14 +117,73 @@ async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, s
return stale[-1]
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
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
+26
View File
@@ -0,0 +1,26 @@
import json
import shlex
from pathlib import Path
import pytest
CONFIG = Path(__file__).resolve().parents[2] / "infra/haproxy/haproxy.cfg"
@pytest.mark.parametrize("status", [502, 503, 504])
@pytest.mark.parametrize("request_id", ['a"b', "a\\b", "a\tb", "aÿb", "x" * 200])
def test_error_templates_escape_json_without_changing_header(status: int, request_id: str) -> None:
line = next(
line.strip()
for line in CONFIG.read_text().splitlines()
if line.strip().startswith(f"http-error status {status} ")
)
tokens = shlex.split(line)
header = tokens[tokens.index("hdr") + 1 : tokens.index("lf-string")]
assert header == ["X-Request-Id", "%[var(txn.request_id)]"]
template = tokens[tokens.index("lf-string") + 1]
escaped = json.dumps(request_id, ensure_ascii=True)[1:-1]
rendered = template.replace("%[var(txn.request_id),json(ascii)]", escaped)
body = json.loads(rendered)
assert body["error"]["request_id"] == request_id
assert body["error"]["code"] == "unavailable"
+161
View File
@@ -0,0 +1,161 @@
import asyncio
from datetime import UTC, datetime, timedelta
from typing import cast
from unittest.mock import AsyncMock
from uuid import uuid4
import pytest
from redis.asyncio import Redis
from redis.exceptions import ConnectionError as CacheConnectionError
from fakes import NullLogger
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.valkey import (
FILL,
REVOKE,
REVOKED,
CachedSessionDirectory,
key_of,
milliseconds,
)
NOW = datetime(2030, 1, 1, tzinfo=UTC)
class CacheModel:
def __init__(self) -> None:
self.values: dict[str, str] = {}
self.expires: dict[str, int] = {}
async def get(self, key: str) -> str | None:
return self.values.get(key)
async def set(self, key: str, value: str, *, pxat: int, nx: bool = False) -> bool:
if nx and key in self.values:
return False
self.values[key], self.expires[key] = value, pxat
return True
async def delete(self, key: str) -> None:
self.values.pop(key, None)
self.expires.pop(key, None)
async def eval(self, script: str, count: int, key: str, marker: str, *args: str | int) -> bool:
assert count == 2
if script == REVOKE:
value, until = args
assert isinstance(value, str) and isinstance(until, int)
await self.set(key, value, pxat=until)
await self.delete(marker)
return True
assert script == FILL
nonce, value, until = args
assert isinstance(value, str) and isinstance(until, int)
if await self.get(marker) != nonce:
return False
await self.delete(marker)
return bool(value) and await self.set(key, value, pxat=until, nx=True)
def directory(origin: AsyncMock, cache: CacheModel, ttl: int = 300) -> CachedSessionDirectory:
return CachedSessionDirectory(
origin, cast(Redis, cache), NullLogger(), limit=timedelta(seconds=ttl), cooldown=1
)
@pytest.fixture
def session() -> Session:
return Session.issue(user_id=uuid4(), issued_at=NOW, ttl=timedelta(seconds=30))[1]
@pytest.mark.parametrize("ttl", [10, 300])
async def test_cache_hit_keeps_absolute_ttl_without_reading_origin(
session: Session, ttl: int
) -> None:
origin, cache = AsyncMock(), CacheModel()
origin.find.return_value = session
cached = directory(origin, cache, ttl)
assert await cached.find(session.token_hash, NOW) == session
assert await directory(origin, cache, ttl).find(session.token_hash, NOW) == session
origin.find.assert_awaited_once()
assert cache.expires == {
key_of(session.token_hash): milliseconds(
min(session.expires_at, NOW + timedelta(seconds=ttl))
)
}
@pytest.mark.parametrize("loss", ["none", "flushall", "evict", "replacement"])
async def test_delayed_fill_cannot_revive_logged_out_session(session: Session, loss: str) -> None:
origin, cache = AsyncMock(), CacheModel()
origin.find.return_value = session
entered, released = asyncio.Event(), asyncio.Event()
async def stale_find(token_hash: bytes, now: datetime) -> Session:
entered.set()
await released.wait()
return session
slow = AsyncMock()
slow.find.side_effect = stale_find
async with asyncio.TaskGroup() as group:
reader = group.create_task(directory(slow, cache).find(session.token_hash, NOW))
await asyncio.wait_for(entered.wait(), 1)
try:
await directory(origin, cache).revoke(session)
origin.find.return_value = None
key = key_of(session.token_hash)
if loss == "flushall":
cache.values.clear()
elif loss in {"evict", "replacement"}:
await cache.delete(key)
if loss == "replacement":
await cache.set(f"{key}:fill", uuid4().hex, pxat=milliseconds(session.expires_at))
finally:
released.set()
assert reader.result() == session
assert await directory(origin, cache).find(session.token_hash, NOW) is None
assert await cache.get(key) in {None, REVOKED}
async def test_failed_reservation_never_fills_from_stale_database_result(session: Session) -> None:
cache = CacheModel()
origin = AsyncMock()
key = key_of(session.token_hash)
await cache.set(f"{key}:fill", "another-reader", pxat=milliseconds(session.expires_at))
async def find(token_hash: bytes, now: datetime) -> Session:
cache.values.clear()
return session
origin.find.side_effect = find
assert await directory(origin, cache).find(session.token_hash, NOW) == session
assert await cache.get(key) is None
async def test_missing_session_releases_only_its_own_reservation(session: Session) -> None:
origin, cache = AsyncMock(), CacheModel()
origin.find.return_value = None
assert await directory(origin, cache).find(session.token_hash, NOW) is None
assert cache.values == {}
@pytest.mark.parametrize("failed_operation", ["get", "set"])
async def test_cache_recovery_during_database_read_does_not_allow_unreserved_fill(
session: Session, failed_operation: str
) -> None:
origin, cache = AsyncMock(), AsyncMock()
cache.get.return_value = None
getattr(cache, failed_operation).side_effect = CacheConnectionError("offline")
cached = CachedSessionDirectory(
origin, cache, NullLogger(), limit=timedelta(seconds=300), cooldown=1
)
async def find(token_hash: bytes, now: datetime) -> Session:
cached._resume_at = 0.0
return session
origin.find.side_effect = find
assert await cached.find(session.token_hash, NOW) == session
assert cache.set.await_count == (failed_operation == "set")
cache.eval.assert_not_awaited()