Source code for s365b.auth.passwords
"""Password and recovery-code hashing (Argon2id) and password policy."""
from __future__ import annotations
import asyncio
import secrets
from collections.abc import Callable
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
[docs]
MIN_PASSWORD_LENGTH = 14
[docs]
RECOVERY_CODE_COUNT = 10
_hasher = PasswordHasher() # Argon2id with library defaults (RFC 9106 low-memory profile)
# Verified against when a username does not exist, so the response time does
# not reveal which usernames exist.
_DUMMY_HASH = _hasher.hash("timing-equaliser")
[docs]
class PasswordPolicyError(ValueError):
"""Raised when a password does not meet the policy."""
[docs]
def check_policy(password: str, username: str) -> None:
"""Check a new password against the policy.
Policy: at least 14 characters, not containing the username. Length is
what matters for an account that is used rarely and written down in a
safe; no composition rules.
Args:
password: Proposed password.
username: The account's username.
Raises:
PasswordPolicyError: With a message suitable for the user.
"""
if len(password) < MIN_PASSWORD_LENGTH:
raise PasswordPolicyError(f"password must be at least {MIN_PASSWORD_LENGTH} characters")
if username and username.lower() in password.lower():
raise PasswordPolicyError("password must not contain the username")
[docs]
def hash_password(password: str) -> str:
"""Hash a password or recovery code.
Args:
password: Plaintext.
Returns:
Argon2id hash string.
"""
return _hasher.hash(password)
[docs]
def verify_password(stored_hash: str | None, password: str) -> bool:
"""Check a password against a stored hash in constant-ish time.
Args:
stored_hash: Hash from the database; ``None`` if the user has none
(a dummy hash is checked so timing does not differ).
password: Plaintext to check.
Returns:
True if it matches.
"""
try:
return _hasher.verify(stored_hash or _DUMMY_HASH, password) and stored_hash is not None
except (VerificationError, InvalidHashError):
return False
[docs]
def generate_recovery_codes() -> tuple[list[str], list[str]]:
"""Create one-time recovery codes for a break-glass account.
Returns:
``(codes, hashes)``: codes to show the user once, and hashes to store.
"""
codes = [f"{secrets.token_hex(3)}-{secrets.token_hex(3)}" for _ in range(RECOVERY_CODE_COUNT)]
return codes, [hash_password(c) for c in codes]
[docs]
def use_recovery_code(hashes: list[str], code: str) -> list[str] | None:
"""Check a recovery code and consume it.
Args:
hashes: Stored hashes of unused codes.
code: Code entered by the user.
Returns:
The remaining hashes if the code was valid, else ``None``.
"""
normalised = code.strip().lower()
for i, h in enumerate(hashes):
if verify_password(h, normalised):
return hashes[:i] + hashes[i + 1 :]
return None
# -- off the event loop ----------------------------------------------------------
# Argon2 takes tens of milliseconds of CPU by design. Run in the event loop,
# each check would stall every other request; unbounded in threads, a burst
# of sign-in attempts would use every core. At most this many run at once.
_slots: asyncio.Semaphore | None = None
async def _in_thread[T](fn: Callable[..., T], *args: object) -> T:
global _slots
if _slots is None:
_slots = asyncio.Semaphore(HASH_SLOTS)
async with _slots:
return await asyncio.to_thread(fn, *args)
[docs]
async def hash_password_async(password: str) -> str:
""":func:`hash_password` in a worker thread (see :data:`HASH_SLOTS`).
Args:
password: Plaintext.
Returns:
Argon2id hash string.
"""
return await _in_thread(hash_password, password)
[docs]
async def verify_password_async(stored_hash: str | None, password: str) -> bool:
""":func:`verify_password` in a worker thread (see :data:`HASH_SLOTS`).
Args:
stored_hash: Hash from the database, or ``None``.
password: Plaintext to check.
Returns:
True if it matches.
"""
return await _in_thread(verify_password, stored_hash, password)
[docs]
async def generate_recovery_codes_async() -> tuple[list[str], list[str]]:
""":func:`generate_recovery_codes` in a worker thread.
Returns:
``(codes, hashes)``.
"""
return await _in_thread(generate_recovery_codes)
[docs]
async def use_recovery_code_async(hashes: list[str], code: str) -> list[str] | None:
""":func:`use_recovery_code` in a worker thread.
Args:
hashes: Stored hashes of unused codes.
code: Code entered by the user.
Returns:
The remaining hashes if the code was valid, else ``None``.
"""
return await _in_thread(use_recovery_code, hashes, code)