Files
mtusi2026lab7/src/infra/password.py
T
ricoromaandClaude Opus 5.5 089d78609d chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:59:04 +03:00

74 lines
3.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Хэширование паролей: Argon2id в потоке с отдельным лимитом.
Профиль RFC 9106 low-memory (t=3, m=64 MiB, p=4) назван явно, а не взят
умолчанием argon2-cffi: обновление библиотеки не меняет его молча. Один
хэш — около 30 мс CPU и 64 MiB памяти, поэтому он считается в потоке, а
не в event loop, и не больше `[auth] kdf_concurrency` одновременно
(design change `session-auth`, решение 3).
"""
import secrets
import anyio
from anyio import to_thread
from argon2 import PasswordHasher, profiles
from argon2.exceptions import VerifyMismatchError
from src.config import settings
_hasher = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY)
# свой лимит, а не общий пул anyio на 40 потоков: 40 × 64 MiB = 2,5 GiB.
# При отмене запроса место освобождается только после конца потока
_limiter = anyio.CapacityLimiter(settings.auth.kdf_concurrency)
# хэш для неизвестного username: считает lifespan при старте
# (prepare_dummy_hash), иначе — первый такой вход
_dummy_hash: str | None = None
async def hash_password(password: str) -> str:
"""Строка Argon2id с параметрами и солью; пароль — целиком, UTF-8."""
return await to_thread.run_sync(_hasher.hash, password, limiter=_limiter)
async def verify_password(*, password: str, password_hash: str | None) -> bool:
"""Подходит ли пароль к хэшу.
`password_hash` `None` — пользователя нет. Пароль всё равно
проверяется, против фиктивного хэша: время ответа не выдаёт,
существует ли username.
"""
if password_hash is None:
await to_thread.run_sync(
_matches,
await prepare_dummy_hash(),
password,
limiter=_limiter,
)
return False
return await to_thread.run_sync(
_matches,
password_hash,
password,
limiter=_limiter,
)
def _matches(password_hash: str, password: str) -> bool:
# повреждённый хэш (InvalidHashError) — дефект, а не неверный пароль
try:
return _hasher.verify(password_hash, password)
except VerifyMismatchError:
return False
async def prepare_dummy_hash() -> str:
"""Фиктивный хэш для неизвестного username, один на процесс.
Lifespan вызывает его при старте: иначе первый вход с неизвестным
username считал бы хэш и проверку — вдвое дольше неверного пароля.
"""
global _dummy_hash
if _dummy_hash is None:
_dummy_hash = await hash_password(secrets.token_urlsafe(16))
return _dummy_hash