wip: apply auth-hardening (interrupted by session end)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 16:22:11 +03:00
co-authored by Claude Opus 5.5
parent f014f7bc0d
commit cf0f6256d3
26 changed files with 1728 additions and 64 deletions
+3
View File
@@ -48,6 +48,9 @@ os.environ.update(
"DATABASE__POOL_TIMEOUT_SECONDS": "1",
"DATABASE__REQUEST_TIMEOUT_SECONDS": str(BLOCK_SECONDS),
"AUTH__KDF_CONCURRENCY": "1",
# меньше срока запроса BLOCK_SECONDS, иначе Settings не загрузится
# (change auth-hardening, design, решение 5)
"AUTH__KDF_WAIT_TIMEOUT_SECONDS": str(BLOCK_SECONDS / 2),
},
)
+19
View File
@@ -93,6 +93,25 @@ class FakeUserRepository(_FakeRepository, AbstractUserRepository):
) -> dataclasses.UserCredentialsDTO | None:
return self._db.credentials.get(username)
async def update_password_hash(
self,
*,
user_id: UUID,
old_hash: str,
new_hash: str,
) -> bool:
user = self._db.users.get(user_id)
if user is None:
return False
stored = self._db.credentials[user.username]
if stored.password_hash != old_hash:
return False
self._db.credentials[user.username] = dataclasses.UserCredentialsDTO(
user=user,
password_hash=new_hash,
)
return True
async def get_existing_user_ids(
self,
*,
+42
View File
@@ -1512,6 +1512,48 @@ async def check_job_replays(new_uow: NewUow) -> None:
assert none == []
async def check_update_password_hash(new_uow: NewUow) -> None:
"""Пересчёт хэша при входе (change `auth-hardening`, решение 2):
обновление только при неизменном хранимом хэше."""
user = user_dto()
new_hash = PASSWORD_HASH.replace("t=3,p=4", "t=2,p=1")
async with new_uow() as uow:
await uow.users.insert_user(user=user, password_hash=PASSWORD_HASH)
await uow.commit()
async with new_uow() as uow:
stale = await uow.users.update_password_hash(
user_id=user.id,
old_hash=new_hash,
new_hash=PASSWORD_HASH,
)
missing = await uow.users.update_password_hash(
user_id=uuid4(),
old_hash=PASSWORD_HASH,
new_hash=new_hash,
)
await uow.commit()
async with new_uow() as uow:
unchanged = await uow.users.get_user_credentials(
username=user.username,
)
assert stale is False
assert missing is False
assert unchanged is not None
assert unchanged.password_hash == PASSWORD_HASH
async with new_uow() as uow:
updated = await uow.users.update_password_hash(
user_id=user.id,
old_hash=PASSWORD_HASH,
new_hash=new_hash,
)
await uow.commit()
async with new_uow() as uow:
stored = await uow.users.get_user_credentials(username=user.username)
assert updated is True
assert stored is not None
assert stored.password_hash == new_hash
CHECKS = tuple(
check
for name, check in sorted(globals().items())
+187
View File
@@ -0,0 +1,187 @@
"""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
+137
View File
@@ -21,6 +21,7 @@ from src.config.settings import (
BASE_DIR,
ApiTls,
App,
Auth,
Settings,
Telemetry,
Uploads,
@@ -261,3 +262,139 @@ def test_example_toml_loads_as_config_toml() -> None:
loaded = _ExampleToml()
assert loaded.telemetry.trace_sample_ratio == 1
assert loaded.telemetry.metric_buckets is MetricBucketsEnum.DEFAULT
# параметры пароля и входа (design change `auth-hardening`, решения 1, 3, 5;
# спек `service-configuration`, «Параметры пароля и входа»)
# итог замеров: строка «Выбрано» evidence/auth/argon2-params.md и сводка
# метки профиля login (QUESTIONS.md, раздел auth-hardening)
MEASURED_AUTH_DEFAULTS = {
"argon2_time_cost": 2,
"argon2_memory_kib": 65536,
"argon2_parallelism": 1,
"kdf_concurrency": 1,
"kdf_max_waiting": 16,
"kdf_wait_timeout_seconds": 2,
"login_window_seconds": 300,
"login_max_failures_per_account": 10,
"login_max_failures_per_address": 200,
}
EVIDENCE_ARGON2 = BASE_DIR.joinpath("evidence/auth/argon2-params.md")
def test_auth_defaults_match_measurements() -> None:
loaded = Auth()
assert {
field: getattr(loaded, field) for field in MEASURED_AUTH_DEFAULTS
} == MEASURED_AUTH_DEFAULTS
def test_argon2_defaults_named_in_evidence() -> None:
"""Строка выбора evidence совпадает с умолчаниями (задача 2.3)."""
text = EVIDENCE_ARGON2.read_text(encoding="utf-8")
chosen = (
f"Выбрано: m={MEASURED_AUTH_DEFAULTS['argon2_memory_kib']} KiB, "
f"t={MEASURED_AUTH_DEFAULTS['argon2_time_cost']}, "
f"p={MEASURED_AUTH_DEFAULTS['argon2_parallelism']}"
)
assert chosen in text
def test_example_toml_keeps_auth_defaults() -> None:
loaded = _ExampleToml()
assert loaded.auth == Auth()
@pytest.mark.parametrize(
("field", "value"),
[
("argon2_memory_kib", 19455),
("argon2_memory_kib", 8192),
("argon2_time_cost", 1),
("argon2_parallelism", 0),
("kdf_concurrency", 0),
("kdf_max_waiting", -1),
("kdf_wait_timeout_seconds", 0),
("kdf_wait_timeout_seconds", float("inf")),
("login_window_seconds", 0),
("login_max_failures_per_account", -1),
("login_max_failures_per_address", -1),
],
)
def test_wrong_auth_value_names_field(field: str, value: object) -> None:
with pytest.raises(ValidationError) as caught:
Auth(**{field: value})
assert [error["loc"] for error in caught.value.errors()] == [(field,)]
@pytest.mark.parametrize(
("field", "value"),
[
("argon2_memory_kib", 19456),
("argon2_time_cost", 2),
("argon2_parallelism", 1),
("kdf_max_waiting", 0),
("login_max_failures_per_account", 0),
("login_max_failures_per_address", 0),
],
)
def test_auth_lower_bounds_accepted(field: str, value: object) -> None:
assert getattr(Auth(**{field: value}), field) == value
@pytest.mark.parametrize("wait", [6, 7])
def test_kdf_wait_not_shorter_than_request_names_field(wait: float) -> None:
with pytest.raises(ValidationError) as caught:
_ArgumentsOnly(
database={"request_timeout_seconds": 6},
auth={"kdf_wait_timeout_seconds": wait},
)
errors = caught.value.errors()
assert [error["loc"] for error in errors] == [("auth",)]
assert "auth.kdf_wait_timeout_seconds" in errors[0]["msg"]
# в ошибке нет значения секции database (там пароль)
assert "password" not in str(caught.value)
def test_kdf_wait_shorter_than_request() -> None:
loaded = _ArgumentsOnly(
database={"request_timeout_seconds": 2},
auth={"kdf_wait_timeout_seconds": 1},
)
assert loaded.auth.kdf_wait_timeout_seconds == 1
def test_auth_from_environment_over_file(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Any,
) -> None:
toml = tmp_path.joinpath("config.toml")
toml.write_text(
"[auth]\nlogin_max_failures_per_account = 7\n",
encoding="utf-8",
)
class _EnvAndToml(_ArgumentsOnly):
model_config = SettingsConfigDict(
**{**_ArgumentsOnly.model_config, "toml_file": toml},
)
@classmethod
def settings_customise_sources(
cls,
settings_cls: type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
*args: PydanticBaseSettingsSource, # noqa: ARG003
**kwargs: Any, # noqa: ARG003
) -> tuple[PydanticBaseSettingsSource, ...]:
return (
init_settings,
env_settings,
TomlConfigSettingsSource(settings_cls),
)
assert _EnvAndToml().auth.login_max_failures_per_account == 7
monkeypatch.setenv("AUTH__LOGIN_MAX_FAILURES_PER_ACCOUNT", "3")
assert _EnvAndToml().auth.login_max_failures_per_account == 3