"""Password hashing with Argon2id (memory-hard password KDF; also mandatory in lab 7). * Parameters follow the OWASP minimum for Argon2id: m=19 MiB, t=2, p=1. Unlike bcrypt there is no 72-byte limit, so any 12-128 code point UTF-8 password is hashed whole. * Hashing takes tens of milliseconds of CPU and 19 MiB of RAM. It runs in a worker thread (argon2-cffi releases the GIL), so the event loop keeps serving other requests, and a semaphore caps parallel hashes (memory/CPU DoS protection). * An unknown username is checked against a dummy hash, so "no such user" and "wrong password" take the same time and return the same 401. """ from __future__ import annotations import asyncio from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError _hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1, hash_len=32, salt_len=16) _semaphore: asyncio.Semaphore | None = None _dummy_hash: str | None = None def configure(concurrency: int) -> None: global _semaphore _semaphore = asyncio.Semaphore(concurrency) async def _run(func, *args): if _semaphore is None: configure(2) async with _semaphore: return await asyncio.to_thread(func, *args) async def hash_password(password: str) -> str: return await _run(_hasher.hash, password) def _verify(stored_hash: str, password: str) -> bool: try: return _hasher.verify(stored_hash, password) except (VerifyMismatchError, VerificationError, InvalidHashError): return False async def verify_password(stored_hash: str | None, password: str) -> bool: global _dummy_hash if stored_hash is None: if _dummy_hash is None: _dummy_hash = await hash_password("dummy-password-for-timing") await _run(_verify, _dummy_hash, password) return False return await _run(_verify, stored_hash, password)