Files
mtusi2026lab7-safronov/service-tests/unit/test_password.py
T
2026-11-17 16:22:11 +03:00

188 lines
6.3 KiB
Python

"""Argon2id из настроек и бюджет хэшей (design change `auth-hardening`,
решения 1, 2, 5; спек `users`, «Пароль хранится только хэшем», спек
`login-protection`, «Бюджет вычисления хэша пароля»).
Параметры маленькие: проверяется устройство, а не стоимость.
"""
import asyncio
import threading
import time
import pytest
from src.core.exceptions import PasswordHashingBusy
from src.infra.password import (
KdfBudget,
PasswordKdf,
build_hasher,
hash_parameters,
)
pytestmark = pytest.mark.anyio
PASSWORD = "synthetic-password-1"
SMALL = {"time_cost": 2, "memory_kib": 1024, "parallelism": 1}
OLD = {"time_cost": 3, "memory_kib": 2048, "parallelism": 2}
def _kdf(
*,
concurrency: int = 2,
max_waiting: int = 4,
wait_timeout_seconds: float = 1,
**parameters: int,
) -> PasswordKdf:
return PasswordKdf(
hasher=build_hasher(**{**SMALL, **parameters}),
budget=KdfBudget(
concurrency=concurrency,
max_waiting=max_waiting,
wait_timeout_seconds=wait_timeout_seconds,
),
)
async def test_hash_has_configured_parameters() -> None:
stored = await _kdf().hash(PASSWORD)
assert stored.startswith("$argon2id$v=19$m=1024,t=2,p=1$")
assert PASSWORD not in stored
other = await _kdf().hash(PASSWORD)
assert other != stored
async def test_old_parameters_need_rehash() -> None:
old_hash = await _kdf(**OLD).hash(PASSWORD)
kdf = _kdf()
check = await kdf.verify(password=PASSWORD, password_hash=old_hash)
assert check.valid
assert check.needs_rehash
assert hash_parameters(old_hash).memory_kib == OLD["memory_kib"]
current = await kdf.hash(PASSWORD)
check = await kdf.verify(password=PASSWORD, password_hash=current)
assert check.valid
assert not check.needs_rehash
async def test_wrong_password_and_unknown_user() -> None:
kdf = _kdf()
stored = await kdf.hash(PASSWORD)
wrong = await kdf.verify(password="other-password-1", password_hash=stored)
assert not wrong.valid
assert not wrong.needs_rehash
unknown = await kdf.verify(password=PASSWORD, password_hash=None)
assert not unknown.valid
# фиктивный хэш — текущими параметрами
dummy = await kdf.prepare_dummy_hash()
assert dummy.startswith("$argon2id$v=19$m=1024,t=2,p=1$")
def _blocking(release: threading.Event, counter: dict[str, int]) -> None:
with counter_lock:
counter["now"] += 1
counter["max"] = max(counter["max"], counter["now"])
release.wait(5)
with counter_lock:
counter["now"] -= 1
counter_lock = threading.Lock()
async def test_full_queue_rejects_at_once() -> None:
budget = KdfBudget(concurrency=1, max_waiting=1, wait_timeout_seconds=5)
release = threading.Event()
counter = {"now": 0, "max": 0}
holder = asyncio.create_task(budget.run(_blocking, release, counter))
await asyncio.sleep(0.05)
waiter = asyncio.create_task(budget.run(_blocking, release, counter))
await asyncio.sleep(0.05)
started = time.monotonic()
with pytest.raises(PasswordHashingBusy) as caught:
await budget.run(_blocking, release, counter)
assert time.monotonic() - started < 0.2
assert caught.value.waited_ms == 0
release.set()
await asyncio.gather(holder, waiter)
assert counter["max"] == 1
async def test_no_waiting_rejects_at_once() -> None:
budget = KdfBudget(concurrency=1, max_waiting=0, wait_timeout_seconds=5)
release = threading.Event()
counter = {"now": 0, "max": 0}
holder = asyncio.create_task(budget.run(_blocking, release, counter))
await asyncio.sleep(0.05)
with pytest.raises(PasswordHashingBusy):
await budget.run(_blocking, release, counter)
release.set()
await holder
async def test_wait_timeout_not_earlier_than_limit() -> None:
budget = KdfBudget(concurrency=1, max_waiting=1, wait_timeout_seconds=0.3)
release = threading.Event()
counter = {"now": 0, "max": 0}
holder = asyncio.create_task(budget.run(_blocking, release, counter))
await asyncio.sleep(0.05)
started = time.monotonic()
with pytest.raises(PasswordHashingBusy) as caught:
await budget.run(_blocking, release, counter)
elapsed = time.monotonic() - started
assert elapsed >= 0.3
assert caught.value.waited_ms >= 300
release.set()
await holder
async def test_cancelled_waiter_frees_queue() -> None:
budget = KdfBudget(concurrency=1, max_waiting=1, wait_timeout_seconds=5)
release = threading.Event()
counter = {"now": 0, "max": 0}
holder = asyncio.create_task(budget.run(_blocking, release, counter))
await asyncio.sleep(0.05)
waiter = asyncio.create_task(budget.run(_blocking, release, counter))
await asyncio.sleep(0.05)
waiter.cancel()
with pytest.raises(asyncio.CancelledError):
await waiter
# место в очереди освободилось: следующий ждёт, а не получает отказ
second = asyncio.create_task(budget.run(_blocking, release, counter))
await asyncio.sleep(0.05)
assert not second.done()
release.set()
await asyncio.gather(holder, second)
assert counter["max"] == 1
async def test_threads_not_more_than_slots() -> None:
budget = KdfBudget(concurrency=2, max_waiting=10, wait_timeout_seconds=5)
release = threading.Event()
counter = {"now": 0, "max": 0}
tasks = [
asyncio.create_task(budget.run(_blocking, release, counter))
for _ in range(8)
]
await asyncio.sleep(0.2)
assert counter["now"] == 2
release.set()
await asyncio.gather(*tasks)
assert counter["max"] == 2
async def test_cancelled_holder_releases_after_thread() -> None:
budget = KdfBudget(concurrency=1, max_waiting=1, wait_timeout_seconds=5)
release = threading.Event()
counter = {"now": 0, "max": 0}
holder = asyncio.create_task(budget.run(_blocking, release, counter))
await asyncio.sleep(0.05)
holder.cancel()
await asyncio.sleep(0.05)
# поток ещё идёт: место не отдано, отмена ждёт его конца
assert not holder.done()
release.set()
with pytest.raises(asyncio.CancelledError):
await holder
assert counter["now"] == 0