from __future__ import annotations import asyncio import base64 import binascii import hashlib import secrets from datetime import datetime, timezone from typing import Optional, Tuple from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError from starlette.concurrency import run_in_threadpool from app import config from app.cache import REVOKED, SessionCache from app.errors import BASIC_CHALLENGE, ApiError, unauthorized from app.storage import Store, fmt_ts, user_row _hasher = PasswordHasher() _hash_slots = asyncio.Semaphore(config.PASSWORD_HASH_CONCURRENCY) _DUMMY_HASH = _hasher.hash("dummy-password-for-timing") async def hash_password(password: str) -> str: async with _hash_slots: return await run_in_threadpool(_hasher.hash, password) async def verify_password(password_hash: str, password: str) -> bool: def verify() -> bool: try: return _hasher.verify(password_hash, password) except (VerificationError, InvalidHashError): return False async with _hash_slots: return await run_in_threadpool(verify) def token_digest(token: str) -> bytes: return hashlib.sha256(token.encode("ascii")).digest() def parse_basic(header: Optional[str]) -> Tuple[str, str]: bad = unauthorized("invalid credentials", BASIC_CHALLENGE) if not header: raise bad scheme, _, value = header.partition(" ") if scheme.lower() != "basic" or not value.strip(): raise bad try: decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8") except (binascii.Error, UnicodeDecodeError): raise bad from None username, sep, password = decoded.partition(":") if not sep or not username.isascii() or not 12 <= len(password) <= 128: raise bad return username, password def parse_bearer(header: Optional[str]) -> str: if not header: raise unauthorized("bearer token required") scheme, _, token = header.partition(" ") token = token.strip() if scheme.lower() != "bearer" or not token or not token.isascii() or len(token) > 256: raise unauthorized("bearer token required") return token async def login(store: Store, header: Optional[str]) -> dict: username, password = parse_basic(header) row = await store.get_credentials(username) if row is None: await verify_password(_DUMMY_HASH, password) raise unauthorized("invalid credentials", BASIC_CHALLENGE) if not await verify_password(row["password_hash"], password): raise unauthorized("invalid credentials", BASIC_CHALLENGE) token = secrets.token_urlsafe(32) expires_at = await store.create_session(token_digest(token), row["id"], config.SESSION_TTL_SECONDS) return {"token": token, "token_type": "Bearer", "expires_at": fmt_ts(expires_at), "user": user_row(row)} async def authenticate(store: Store, cache: SessionCache, header: Optional[str]) -> dict: digest = token_digest(parse_bearer(header)) cached = await cache.get(digest) if cached == REVOKED: raise unauthorized("session expired or revoked") if isinstance(cached, dict): expires_at = datetime.fromisoformat(cached["expires_at"].replace("Z", "+00:00")) if expires_at > datetime.now(timezone.utc): return cached["user"] raise unauthorized("session expired or revoked") row = await store.find_session(digest) if row is None: raise unauthorized("session expired or revoked") user = user_row(row) remaining = int((row["expires_at"] - datetime.now(timezone.utc)).total_seconds()) await cache.put(digest, {"user": user, "expires_at": fmt_ts(row["expires_at"])}, remaining) return user async def logout(store: Store, cache: SessionCache, header: Optional[str]) -> None: await authenticate(store, cache, header) digest = token_digest(parse_bearer(header)) expires_at = await store.revoke_session(digest) if expires_at is None: raise unauthorized("session expired or revoked") remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1 if not await cache.revoke(digest, remaining): raise ApiError(503, "unavailable", "logout not confirmed by session cache, retry later")