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
+20 -9
View File
@@ -334,7 +334,9 @@ async def create_message(
400, "invalid_request", "Idempotency-Key must match "
"^[A-Za-z0-9._:-]{1,128}$"
)
existing = await store.get_idempotency_key(cursor, key)
existing = await store.get_idempotency_key(
cursor, actor_id=actor.user_id, chat_id=normalized, key=key
)
if existing is not None:
if existing["request_sha256"] != request_sha256:
raise ApiProblem(409, "conflict", "Idempotency-Key was already used")
@@ -342,18 +344,27 @@ async def create_message(
original = await store.message_by_id(cursor, existing["message_id"])
if original is not None:
return original
try:
await store.insert_idempotency_key(
cursor, key=key, chat_id=normalized, request_sha256=request_sha256
inserted = await store.insert_idempotency_key(
cursor,
actor_id=actor.user_id,
key=key,
chat_id=normalized,
request_sha256=request_sha256,
)
if not inserted:
# INSERT .. ON CONFLICT keeps this transaction usable. PostgreSQL
# waited for the winning transaction, so its message is committed
# and can be returned as the exact replay result.
existing = await store.get_idempotency_key(
cursor, actor_id=actor.user_id, chat_id=normalized, key=key
)
except ApiProblem:
# Race: another request inserted the key first. Treat as replay.
existing = await store.get_idempotency_key(cursor, key)
if existing is not None and existing["request_sha256"] == request_sha256:
if existing is not None:
if existing["request_sha256"] != request_sha256:
raise ApiProblem(409, "conflict", "Idempotency-Key was already used")
original = await store.message_by_id(cursor, existing["message_id"])
if original is not None:
return original
raise
raise ApiProblem(409, "conflict", "Idempotency-Key is still being stored")
return await store.create_message(
cursor,
actor_id=actor.user_id,