"""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}