Files
mtusi2026lab7-safronov/service-tests/unit/test_user_service.py
T
ricoromaandClaude Opus 5.5 13fdd187c6 feat: harden authentication (Argon2id by measurement, login limits, body limit)
Apply auth-hardening up to the bench_login label: Argon2id parameters
from [auth] chosen by driver.py argon2-params (m=64 MiB, t=2, p=1),
rehash on login, per-process KDF budget with 429, shared login failure
limit in Valkey with a local fallback, X-Forwarded-For from HAProxy,
64 KiB body limit (400) in LB and middleware, bench login profile,
tests, threat model and trust matrix rows. Hypotheses H1-H4 are
committed here before the baseline label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:52:48 +03:00

84 lines
2.5 KiB
Python

"""`UserService`: KDF вне блока, занятый username."""
import pytest
from fakes import FakeDatabase, FakeUnitOfWork
from src.core import exceptions, services
from src.core.services import user as user_module
pytestmark = pytest.mark.anyio
@pytest.fixture(autouse=True)
def cheap_kdf(monkeypatch: pytest.MonkeyPatch, database: FakeDatabase) -> None:
async def hash_password(password: str) -> str:
database.events.append("kdf")
return f"hash:{password}"
monkeypatch.setattr(user_module, "hash_password", hash_password)
async def test_register_stores_user_outside_kdf(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
created = await services.UserService(uow).register(
username="alice",
display_name="Alice",
password="password-1234",
)
assert database.users[created.id] == created
assert database.credentials["alice"].password_hash == "hash:password-1234"
# KDF до блока, соединение не занято
assert database.events[0] == "kdf"
assert database.events[1:] == [
"enter",
"users.insert_user",
"commit",
"exit",
]
async def test_busy_budget_rejects_before_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Бюджет хэшей занят (change auth-hardening, решение 5): 429 до блока,
ни соединения, ни строки."""
async def busy(password: str) -> str: # noqa: ARG001
database.events.append("kdf")
raise exceptions.PasswordHashingBusy(waited_ms=7)
monkeypatch.setattr(user_module, "hash_password", busy)
with pytest.raises(exceptions.PasswordHashingBusy):
await services.UserService(uow).register(
username="alice",
display_name="Alice",
password="password-1234",
)
assert database.events == ["kdf"]
assert database.users == {}
async def test_taken_username_rejected_without_commit(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
service = services.UserService(uow)
await service.register(
username="alice",
display_name="Alice",
password="password-1234",
)
database.events.clear()
with pytest.raises(exceptions.UsernameTaken):
await service.register(
username="alice",
display_name="Other",
password="password-5678",
)
assert "commit" not in database.events
assert len(database.users) == 1