Перенести приложение мессенджера с сессиями и идемпотентностью в PostgreSQL

Пользователи, аутентификация Argon2id, Bearer-сессии с TTL и отзывом,
транзакционный репозиторий, keyset-пагинация, идемпотентные отправки
(advisory lock + message_requests), версияемые миграции 001/002.
This commit is contained in:
2026-11-17 03:37:07 +00:00
parent ec540a1a72
commit 4b23b44eb8
15 changed files with 795 additions and 0 deletions
+60
View File
@@ -0,0 +1,60 @@
"""Password KDF and HTTP credential parsing, without framework dependencies."""
import base64
import binascii
import hashlib
import re
import secrets
from argon2 import PasswordHasher, Type
from argon2.exceptions import VerificationError, InvalidHashError
from .domain import ApiError, invalid, string
class Authentication:
def __init__(self, repository, ttl):
self.repository = repository
self.ttl = ttl
self.hasher = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=2,
hash_len=32, salt_len=16, type=Type.ID)
self._dummy = self.hasher.hash(secrets.token_urlsafe(32))
@staticmethod
def password(value):
string(value, 128)
if len(value) < 12:
invalid('Password must contain 12 to 128 Unicode characters')
return value
@staticmethod
def digest(token):
return hashlib.sha256(token.encode('ascii')).hexdigest()
def bearer(self, header):
parts = (header or '').split()
if len(parts) != 2 or parts[0].lower() != 'bearer' or not re.fullmatch(r'[A-Za-z0-9_-]{43}', parts[1]):
raise ApiError(401, 'unauthorized', 'Valid Bearer session required')
token_hash = self.digest(parts[1])
return self.repository.session_user(token_hash), token_hash
def login(self, header):
def denied():
raise ApiError(401, 'unauthorized', 'Invalid credentials')
try:
parts = (header or '').split()
if len(parts) != 2 or parts[0].lower() != 'basic':
denied()
username, password = base64.b64decode(parts[1], validate=True).decode('utf-8').split(':', 1)
if not re.fullmatch(r'[a-z0-9_]{3,32}', username) or not 12 <= len(password) <= 128:
denied()
except (ValueError, UnicodeError, binascii.Error):
denied()
row = self.repository.credentials(username)
try:
self.hasher.verify(row['password_hash'] if row else self._dummy, password)
except (VerificationError, InvalidHashError):
denied()
if row is None:
denied()
user = {key: value for key, value in row.items() if key != 'password_hash'}
token = secrets.token_urlsafe(32)
expires_at = self.repository.create_session(user['id'], self.digest(token), self.ttl)
return {'token': token, 'token_type': 'Bearer', 'expires_at': expires_at, 'user': user}