|
| 1 | +"""Shared concurrency limits for expensive authentication work. |
| 2 | +
|
| 3 | +Password hashing and recovery-code hashing use memory-hard Argon2 work. The |
| 4 | +shared password-operation worker limiter caps concurrent operations per event |
| 5 | +loop (one loop per process for typical servers); worst-case Argon2 memory is |
| 6 | +roughly ``PASSWORD_WORKER_THREAD_LIMIT * Argon2 memory cost`` per loop. With |
| 7 | +the bundled default pwdlib policy, that is the resolved limit times about |
| 8 | +64 MiB. The limiter is loop-scoped because AnyIO capacity limiters hold |
| 9 | +loop-bound waiter events and must not be shared across event loops. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import secrets |
| 15 | +from os import environ |
| 16 | +from threading import Lock as ThreadLock |
| 17 | +from typing import TYPE_CHECKING |
| 18 | +from weakref import WeakKeyDictionary |
| 19 | + |
| 20 | +from anyio import CapacityLimiter |
| 21 | +from anyio.lowlevel import RunVar |
| 22 | +from anyio.to_thread import run_sync as _run_sync_in_worker_thread |
| 23 | + |
| 24 | +from litestar_auth.exceptions import ConfigurationError |
| 25 | + |
| 26 | +if TYPE_CHECKING: |
| 27 | + from collections.abc import Callable |
| 28 | + |
| 29 | + from litestar_auth.password import PasswordHelper |
| 30 | + |
| 31 | +_DEFAULT_PASSWORD_WORKER_THREAD_LIMIT = 8 |
| 32 | +_PASSWORD_WORKER_THREAD_LIMIT_ENV_VAR = "LITESTAR_AUTH_PASSWORD_WORKER_THREAD_LIMIT" # noqa: S105 |
| 33 | + |
| 34 | + |
| 35 | +def _resolve_password_worker_thread_limit(raw_limit: str | None) -> int: |
| 36 | + """Resolve the password worker-thread cap from optional environment input. |
| 37 | +
|
| 38 | + Returns: |
| 39 | + Positive worker-thread limit. |
| 40 | +
|
| 41 | + Raises: |
| 42 | + ConfigurationError: If the configured limit is not a positive integer. |
| 43 | + """ |
| 44 | + if raw_limit is None: |
| 45 | + return _DEFAULT_PASSWORD_WORKER_THREAD_LIMIT |
| 46 | + |
| 47 | + msg = f"{_PASSWORD_WORKER_THREAD_LIMIT_ENV_VAR} must be a positive integer; got {raw_limit!r}." |
| 48 | + try: |
| 49 | + limit = int(raw_limit) |
| 50 | + except ValueError as exc: |
| 51 | + raise ConfigurationError(msg) from exc |
| 52 | + |
| 53 | + if limit < 1: |
| 54 | + raise ConfigurationError(msg) |
| 55 | + return limit |
| 56 | + |
| 57 | + |
| 58 | +# Maximum concurrent memory-hard password operations inside one process. Bounds |
| 59 | +# worst-case Argon2 memory to this limit times the configured memory cost |
| 60 | +# (pwdlib's bundled Argon2 hasher defaults to 64 MiB per operation). |
| 61 | +PASSWORD_WORKER_THREAD_LIMIT = _resolve_password_worker_thread_limit( |
| 62 | + environ.get(_PASSWORD_WORKER_THREAD_LIMIT_ENV_VAR), |
| 63 | +) |
| 64 | + |
| 65 | +# Loop-scoped limiter: asyncio-backed CapacityLimiter waiters are Events bound |
| 66 | +# to the event loop that created them, so one limiter must never serve two loops. |
| 67 | +_PASSWORD_OP_LIMITER: RunVar[CapacityLimiter] = RunVar("litestar_auth_password_op_limiter") |
| 68 | +_DUMMY_HASH_CACHE: WeakKeyDictionary[PasswordHelper, str] = WeakKeyDictionary() |
| 69 | +_DUMMY_HASH_CACHE_GUARD = ThreadLock() |
| 70 | + |
| 71 | + |
| 72 | +def _password_op_limiter() -> CapacityLimiter: |
| 73 | + """Return the current event loop's password-operation capacity limiter. |
| 74 | +
|
| 75 | + Returns: |
| 76 | + The loop-scoped limiter, created on first use within the running loop. |
| 77 | + """ |
| 78 | + try: |
| 79 | + return _PASSWORD_OP_LIMITER.get() |
| 80 | + except LookupError: |
| 81 | + limiter = CapacityLimiter(PASSWORD_WORKER_THREAD_LIMIT) |
| 82 | + _PASSWORD_OP_LIMITER.set(limiter) |
| 83 | + return limiter |
| 84 | + |
| 85 | + |
| 86 | +def build_dummy_hash(password_helper: PasswordHelper) -> str: |
| 87 | + """Return a freshly salted dummy password hash for timing equalization.""" |
| 88 | + return password_helper.hash(secrets.token_urlsafe(32)) |
| 89 | + |
| 90 | + |
| 91 | +def _cached_dummy_hash(password_helper: PasswordHelper) -> str | None: |
| 92 | + """Return a cached dummy hash without keeping the helper alive.""" |
| 93 | + with _DUMMY_HASH_CACHE_GUARD: |
| 94 | + return _DUMMY_HASH_CACHE.get(password_helper) |
| 95 | + |
| 96 | + |
| 97 | +def _cache_dummy_hash(password_helper: PasswordHelper, dummy_hash: str) -> None: |
| 98 | + """Store the helper-scoped dummy hash after worker-thread construction.""" |
| 99 | + with _DUMMY_HASH_CACHE_GUARD: |
| 100 | + _DUMMY_HASH_CACHE[password_helper] = dummy_hash |
| 101 | + |
| 102 | + |
| 103 | +async def run_password_op_in_worker_thread[T](func: Callable[..., T], *args: object) -> T: |
| 104 | + """Run memory-hard password work in AnyIO's worker pool with a dedicated cap. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + The callable result. |
| 108 | + """ |
| 109 | + return await _run_sync_in_worker_thread(func, *args, limiter=_password_op_limiter()) |
| 110 | + |
| 111 | + |
| 112 | +async def get_cached_dummy_hash(password_helper: PasswordHelper) -> str: |
| 113 | + """Return the per-helper dummy hash used to equalize unknown-secret checks.""" |
| 114 | + cached_hash = _cached_dummy_hash(password_helper) |
| 115 | + if cached_hash is not None: |
| 116 | + return cached_hash |
| 117 | + |
| 118 | + dummy_hash = await run_password_op_in_worker_thread(build_dummy_hash, password_helper) |
| 119 | + _cache_dummy_hash(password_helper, dummy_hash) |
| 120 | + return dummy_hash |
0 commit comments