Fix replica auth and idempotency races

This commit is contained in:
Tmribob
2026-11-06 16:13:24 +03:00
parent 57c81ea9d5
commit 057877d299
22 changed files with 682 additions and 60 deletions
+7 -13
View File
@@ -271,18 +271,8 @@ async def resolve_session(
"Session token is expired or revoked",
{"WWW-Authenticate": 'Bearer realm="messenger"'},
)
state, payload = await cache.lookup(hashed)
if state == HIT and payload is not None:
if payload["expires_epoch"] > time.time():
try:
user_id = uuid.UUID(payload["user"]["id"])
except (ValueError, TypeError, KeyError):
user_id = None
if user_id is not None:
return user_id, payload["user"]
else:
await cache.revoke(hashed, None)
elif state == TOMBSTONE:
state, _payload = await cache.lookup(hashed)
if state == TOMBSTONE:
raise ApiProblem(
401,
"unauthorized",
@@ -290,6 +280,10 @@ async def resolve_session(
{"WWW-Authenticate": 'Bearer realm="messenger"'},
)
# PostgreSQL is the authoritative revocation store. A cache value can only
# accelerate the immutable user snapshot; it must never be enough to grant
# access on its own. This makes logout durable across API replicas and
# Valkey outages/restores, where a tombstone may not reach shared cache.
async with pool.connection() as connection:
async with connection.cursor() as cursor:
row = await store.session_user(cursor, hashed)
@@ -302,6 +296,7 @@ async def resolve_session(
{"WWW-Authenticate": 'Bearer realm="messenger"'},
)
user = _user_payload(row)
# Refresh an old cache hit after PostgreSQL has confirmed it is still live.
await cache.remember(hashed, user, row["expires_at"])
return uuid.UUID(user["id"]), user
@@ -340,4 +335,3 @@ async def purge_expired_idempotency(pool: AsyncConnectionPool) -> int:
(str(IDEMPOTENCY_TTL_SECONDS),),
)
return cursor.rowcount