fix(auth): avoid redundant password hashing in registration races
This commit is contained in:
+18
-5
@@ -2,6 +2,7 @@ import base64
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
@@ -62,6 +63,7 @@ class MessengerService:
|
||||
self.repository = repository
|
||||
self.passwords = passwords
|
||||
self.session_ttl = session_ttl
|
||||
self.registration_locks = [threading.Lock() for _ in range(64)]
|
||||
|
||||
def identify(self, *, value: str | None) -> User:
|
||||
token = bearer(value)
|
||||
@@ -74,11 +76,22 @@ class MessengerService:
|
||||
def register(
|
||||
self, *, username: str, display_name: str, password: str
|
||||
) -> User:
|
||||
encoded = self.passwords.hash(password=password)
|
||||
return self.repository.add_user(
|
||||
user=User(uuid4(), username, display_name, utcnow()),
|
||||
password_hash=encoded,
|
||||
)
|
||||
# Bound lock memory and avoid running Argon2 for every local duplicate.
|
||||
# Different replicas still race safely through PostgreSQL UNIQUE.
|
||||
stripe = hashlib.sha256(username.encode()).digest()[0] % 64
|
||||
lock = self.registration_locks[stripe]
|
||||
if not lock.acquire(timeout=8):
|
||||
raise DomainError(503, "unavailable", "Registration busy")
|
||||
try:
|
||||
if self.repository.username_exists(username=username):
|
||||
raise DomainError(409, "conflict", "Username already exists")
|
||||
encoded = self.passwords.hash(password=password)
|
||||
return self.repository.add_user(
|
||||
user=User(uuid4(), username, display_name, utcnow()),
|
||||
password_hash=encoded,
|
||||
)
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
def login(self, *, authorization: str | None):
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user