527 lines
19 KiB
Python
527 lines
19 KiB
Python
"""Лаба 7, защита входа: настройки `ARGON2_*` / `KDF_*` / `LOGIN_*`, бюджет
|
|
хэшей, пересчёт старого хэша, предел неудачных входов (Valkey и счётчики
|
|
процесса), адрес клиента от LB, порядок проверок входа, предел тела.
|
|
|
|
Без стенда. Valkey — подделка `Cache`, которая выполняет те же два сценария
|
|
Lua на словаре (их смысл; сами сценарии против настоящего Valkey проверяют
|
|
тесты `make failure-checks` и `student-tests/test_login_protection.py`).
|
|
Argon2id — настоящий, с минимальными параметрами рубрики (быстро).
|
|
"""
|
|
|
|
import asyncio
|
|
import json
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from dataclasses import dataclass, field
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import httpx
|
|
import pytest
|
|
from argon2 import PasswordHasher, profiles
|
|
|
|
from src.api.body_limit import BODY_TOO_LARGE, BodyLimitMiddleware
|
|
from src.api.deps import client_address
|
|
from src.config import Auth, ConfigError, Settings
|
|
from src.domain import Credentials, Session, User
|
|
from src.errors import (
|
|
InvalidCredentials,
|
|
LoginRateLimited,
|
|
PasswordHashingBusy,
|
|
Unavailable,
|
|
)
|
|
from src.login_limit import (
|
|
ACQUIRE_SCRIPT,
|
|
LocalLoginLimiter,
|
|
LoginLimiter,
|
|
address_part,
|
|
login_keys,
|
|
)
|
|
from src.passwords import KdfBudget, Passwords, hash_parameters
|
|
from src.services.sessions import SessionService
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
FAST = Auth(argon2_memory_kib=19456, argon2_iterations=2, argon2_parallelism=1)
|
|
|
|
|
|
# --- настройки ---------------------------------------------------------------
|
|
|
|
|
|
def test_auth_defaults_and_bounds() -> None:
|
|
auth = Settings.from_env({}).auth
|
|
assert auth.argon2_iterations >= 2
|
|
assert auth.argon2_memory_kib >= 19456
|
|
assert auth.argon2_parallelism >= 1
|
|
assert (
|
|
auth.login_window,
|
|
auth.login_max_failures_per_account,
|
|
auth.login_max_failures_per_address,
|
|
) == (300, 10, 200)
|
|
for name, value in (
|
|
("ARGON2_MEMORY_KIB", "19455"),
|
|
("ARGON2_ITERATIONS", "1"),
|
|
("ARGON2_PARALLELISM", "0"),
|
|
("KDF_CONCURRENCY", "0"),
|
|
("KDF_MAX_WAITING", "-1"),
|
|
("KDF_WAIT_TIMEOUT", "0"),
|
|
("KDF_WAIT_TIMEOUT", "6"),
|
|
("LOGIN_WINDOW_SECONDS", "0"),
|
|
("LOGIN_MAX_FAILURES_PER_ACCOUNT", "-1"),
|
|
):
|
|
with pytest.raises(ConfigError, match=name):
|
|
Settings.from_env({name: value})
|
|
override = Settings.from_env(
|
|
{"LOGIN_MAX_FAILURES_PER_ACCOUNT": "3", "ARGON2_MEMORY_KIB": "19456"}
|
|
).auth
|
|
assert override.login_max_failures_per_account == 3
|
|
assert override.argon2_memory_kib == 19456
|
|
|
|
|
|
# --- Argon2id и бюджет -------------------------------------------------------
|
|
|
|
|
|
def test_hash_carries_configured_parameters_and_rehash_flag() -> None:
|
|
passwords = Passwords(FAST)
|
|
password = "correct horse battery"
|
|
|
|
async def scenario() -> None:
|
|
current = await passwords.hash(password)
|
|
assert current.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
|
assert hash_parameters(current) == passwords.parameters
|
|
check = await passwords.verify(password=password, password_hash=current)
|
|
assert (check.valid, check.needs_rehash) == (True, False)
|
|
# прежние параметры лабы 6 (RFC 9106 low memory) — верен, нужен пересчёт
|
|
old = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY).hash(
|
|
password
|
|
)
|
|
check = await passwords.verify(password=password, password_hash=old)
|
|
assert (check.valid, check.needs_rehash) == (True, True)
|
|
wrong = await passwords.verify(password="wrong password!", password_hash=old)
|
|
assert (wrong.valid, wrong.needs_rehash) == (False, False)
|
|
unknown = await passwords.verify(password=password, password_hash=None)
|
|
assert unknown.valid is False
|
|
|
|
asyncio.run(scenario())
|
|
|
|
|
|
def test_kdf_budget_limits_threads_and_queue() -> None:
|
|
budget = KdfBudget(concurrency=1, max_waiting=1, wait_timeout=0.3)
|
|
active = {"now": 0, "peak": 0}
|
|
lock = threading.Lock()
|
|
|
|
def slow() -> int:
|
|
with lock:
|
|
active["now"] += 1
|
|
active["peak"] = max(active["peak"], active["now"])
|
|
time.sleep(0.2)
|
|
with lock:
|
|
active["now"] -= 1
|
|
return 1
|
|
|
|
async def scenario() -> list:
|
|
return await asyncio.gather(
|
|
*(budget.run(slow) for _ in range(4)), return_exceptions=True
|
|
)
|
|
|
|
results = asyncio.run(scenario())
|
|
busy = [r for r in results if isinstance(r, PasswordHashingBusy)]
|
|
# одно место и одно ждущее: двое выполнены, двое сразу — 429
|
|
assert results.count(1) == 2, results
|
|
assert len(busy) == 2
|
|
assert all(error.waited_ms == 0 for error in busy)
|
|
assert active["peak"] == 1
|
|
|
|
|
|
def test_kdf_budget_wait_timeout_and_cancelled_waiter() -> None:
|
|
budget = KdfBudget(concurrency=1, max_waiting=4, wait_timeout=0.2)
|
|
|
|
async def scenario() -> None:
|
|
holder = asyncio.create_task(budget.run(time.sleep, 0.6))
|
|
await asyncio.sleep(0.05)
|
|
started = time.monotonic()
|
|
with pytest.raises(PasswordHashingBusy) as caught:
|
|
await budget.run(time.sleep, 0)
|
|
assert time.monotonic() - started >= 0.19
|
|
assert caught.value.waited_ms >= 190
|
|
# отменённый ждущий место не занимает
|
|
waiter = asyncio.create_task(budget.run(time.sleep, 0))
|
|
await asyncio.sleep(0.05)
|
|
waiter.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await waiter
|
|
await holder
|
|
assert budget._waiting == 0
|
|
await budget.run(time.sleep, 0)
|
|
|
|
asyncio.run(scenario())
|
|
|
|
|
|
# --- предел неудачных входов -------------------------------------------------
|
|
|
|
|
|
@dataclass
|
|
class FakeCache:
|
|
"""Сценарии `login_limit` на словаре: значение и срок ключа."""
|
|
|
|
namespace: str = "messenger"
|
|
down: bool = False
|
|
data: dict[str, list] = field(default_factory=dict)
|
|
calls: int = 0
|
|
|
|
async def run_script(self, script, *, keys, args): # noqa: ANN001
|
|
self.calls += 1
|
|
if self.down:
|
|
return None
|
|
now = time.monotonic()
|
|
for key in list(self.data):
|
|
if self.data[key][1] <= now:
|
|
del self.data[key]
|
|
if script == ACQUIRE_SCRIPT:
|
|
window, limits = int(args[0]), [int(a) for a in args[1:]]
|
|
wait = 0
|
|
for key, limit in zip(keys, limits, strict=True):
|
|
value = self.data.get(key)
|
|
if value and value[0] >= limit:
|
|
wait = max(wait, max(1, int(value[1] - now)))
|
|
if wait:
|
|
return wait
|
|
for key in keys:
|
|
value = self.data.setdefault(key, [0, now + window])
|
|
value[0] += 1
|
|
return 0
|
|
for key, mode in zip(keys, args, strict=True):
|
|
value = self.data.get(key)
|
|
if value is None:
|
|
continue
|
|
value[0] -= 1
|
|
if mode == "del" or value[0] <= 0:
|
|
del self.data[key]
|
|
return 1
|
|
|
|
|
|
def _limiter(cache: FakeCache, account: int = 3, address: int = 6) -> LoginLimiter:
|
|
return LoginLimiter(
|
|
cache,
|
|
window=10,
|
|
max_failures_per_account=account,
|
|
max_failures_per_address=address,
|
|
)
|
|
|
|
|
|
def test_keys_hold_no_username_or_address() -> None:
|
|
account, address = login_keys(
|
|
namespace="messenger", username="alice_1", address="198.51.100.7"
|
|
)
|
|
assert account.startswith("messenger:v1:messenger:login:ua:")
|
|
assert address.startswith("messenger:v1:messenger:login:a:")
|
|
for key in (account, address):
|
|
assert "alice_1" not in key
|
|
assert "198.51.100.7" not in key
|
|
assert address_part("2001:db8:1:2:3:4:5:6") == "2001:db8:1:2::/64"
|
|
assert address_part("::ffff:192.0.2.1") == "192.0.2.1"
|
|
assert address_part("192.0.2.1") == "192.0.2.1"
|
|
|
|
|
|
def test_account_limit_reserve_and_reset() -> None:
|
|
cache = FakeCache()
|
|
limiter = _limiter(cache)
|
|
|
|
async def scenario() -> None:
|
|
for _ in range(3):
|
|
attempt = await limiter.acquire(username="u", address="192.0.2.1")
|
|
assert attempt.allowed
|
|
await limiter.settle(attempt, "failed")
|
|
limited = await limiter.acquire(username="u", address="192.0.2.1")
|
|
assert not limited.allowed
|
|
assert 1 <= limited.retry_after <= 10
|
|
# другой username с того же адреса — ещё можно (предел адреса 6)
|
|
other = await limiter.acquire(username="v", address="192.0.2.1")
|
|
assert other.allowed
|
|
# успех возвращает резерв адреса и сбрасывает пару
|
|
await limiter.settle(other, "succeeded")
|
|
assert len(cache.data) == 2 # пара u и адрес, ключей v нет
|
|
# обрыв (503, 429 бюджета) — тоже возврат
|
|
aborted = await limiter.acquire(username="w", address="192.0.2.1")
|
|
await limiter.settle(aborted, "aborted")
|
|
assert len(cache.data) == 2
|
|
|
|
asyncio.run(scenario())
|
|
|
|
|
|
def test_concurrent_attempts_do_not_overtake_limit() -> None:
|
|
limiter = _limiter(FakeCache())
|
|
|
|
async def scenario() -> list:
|
|
return await asyncio.gather(
|
|
*(limiter.acquire(username="u", address="192.0.2.2") for _ in range(10))
|
|
)
|
|
|
|
attempts = asyncio.run(scenario())
|
|
assert sum(a.allowed for a in attempts) == 3
|
|
|
|
|
|
def test_address_limit_and_zero_disables() -> None:
|
|
limiter = _limiter(FakeCache(), account=0, address=2)
|
|
|
|
async def scenario() -> None:
|
|
for name in ("a", "b"):
|
|
attempt = await limiter.acquire(username=name, address="192.0.2.3")
|
|
assert attempt.allowed
|
|
assert attempt.account_key is None
|
|
assert not (await limiter.acquire(username="c", address="192.0.2.3")).allowed
|
|
assert (await limiter.acquire(username="c", address="192.0.2.4")).allowed
|
|
|
|
asyncio.run(scenario())
|
|
|
|
|
|
def test_valkey_down_uses_process_counters_and_back(
|
|
caplog: pytest.LogCaptureFixture,
|
|
) -> None:
|
|
cache = FakeCache(down=True)
|
|
limiter = _limiter(cache)
|
|
|
|
async def scenario() -> None:
|
|
for _ in range(3):
|
|
attempt = await limiter.acquire(username="u", address="192.0.2.5")
|
|
assert attempt.allowed
|
|
assert not attempt.shared
|
|
limited = await limiter.acquire(username="u", address="192.0.2.5")
|
|
assert not limited.allowed
|
|
assert limited.retry_after >= 1
|
|
cache.down = False
|
|
attempt = await limiter.acquire(username="x", address="192.0.2.6")
|
|
assert attempt.shared
|
|
|
|
with caplog.at_level("INFO", logger="src.login_limit"):
|
|
asyncio.run(scenario())
|
|
messages = [record.getMessage() for record in caplog.records]
|
|
assert sum("uses process counters" in m for m in messages) == 1
|
|
assert sum("uses shared counters" in m for m in messages) == 1
|
|
|
|
|
|
def test_local_limiter_window_release_and_overflow() -> None:
|
|
local = LocalLoginLimiter(window=1, max_keys=2)
|
|
wait, keys = local.acquire({"a": 1})
|
|
assert (wait, keys) == (0, ("a",))
|
|
wait, _ = local.acquire({"a": 1})
|
|
assert wait == 1
|
|
local.release({"a": "decr"})
|
|
assert len(local) == 0 # дошедшая до 0 запись удалена
|
|
local.acquire({"b": 5, "c": 5})
|
|
# словарь полон: новый ключ не заводится, попытка разрешена
|
|
wait, keys = local.acquire({"d": 5})
|
|
assert (wait, keys) == (0, ())
|
|
time.sleep(1.05)
|
|
wait, keys = local.acquire({"d": 5})
|
|
assert keys == ("d",)
|
|
|
|
|
|
# --- адрес клиента -----------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("forwarded", "trusted", "expected"),
|
|
[
|
|
("198.51.100.1", True, "198.51.100.1"),
|
|
(" 2001:db8::1 ", True, "2001:db8::1"),
|
|
("198.51.100.1, 10.0.0.1", True, "10.9.8.7"),
|
|
("garbage", True, "10.9.8.7"),
|
|
(None, True, "10.9.8.7"),
|
|
("198.51.100.1", False, "10.9.8.7"),
|
|
],
|
|
)
|
|
def test_client_address(forwarded: str | None, trusted: bool, expected: str) -> None:
|
|
assert (
|
|
client_address(forwarded=forwarded, peer="10.9.8.7", trusted=trusted)
|
|
== expected
|
|
)
|
|
|
|
|
|
# --- порядок проверок входа --------------------------------------------------
|
|
|
|
|
|
class FakeStorage:
|
|
def __init__(self, password_hash: str | None) -> None:
|
|
self.user = User(uuid.uuid4(), "alice_1", "Alice", datetime.now(UTC))
|
|
self.password_hash = password_hash
|
|
self.reads = 0
|
|
self.down = False
|
|
self.rehashed: tuple[str, str] | None = None
|
|
|
|
async def get_credentials(self, username: str) -> Credentials | None:
|
|
self.reads += 1
|
|
if self.down:
|
|
raise Unavailable
|
|
if self.password_hash is None:
|
|
return None
|
|
return Credentials(user=self.user, password_hash=self.password_hash)
|
|
|
|
def _session(self, ttl: timedelta) -> Session:
|
|
now = datetime.now(UTC)
|
|
return Session(uuid.uuid4(), self.user.id, now + ttl, now)
|
|
|
|
async def create_session(self, *, user_id, token_hash, ttl) -> Session: # noqa: ANN001
|
|
return self._session(ttl)
|
|
|
|
async def create_session_with_rehash( # noqa: ANN201
|
|
self,
|
|
*,
|
|
user_id, # noqa: ANN001
|
|
token_hash, # noqa: ANN001
|
|
ttl, # noqa: ANN001
|
|
old_hash, # noqa: ANN001
|
|
new_hash, # noqa: ANN001
|
|
):
|
|
updated = self.password_hash == old_hash
|
|
if updated:
|
|
self.password_hash = new_hash
|
|
self.rehashed = (old_hash, new_hash)
|
|
return self._session(ttl), updated
|
|
|
|
|
|
def _service(
|
|
storage: FakeStorage, passwords: Passwords, cache: FakeCache
|
|
) -> SessionService:
|
|
return SessionService(storage, passwords, _limiter(cache, account=2), ttl=60)
|
|
|
|
|
|
def test_login_order_and_settle() -> None:
|
|
passwords = Passwords(FAST)
|
|
password = "correct horse battery"
|
|
old = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY).hash(password)
|
|
storage = FakeStorage(old)
|
|
cache = FakeCache()
|
|
service = _service(storage, passwords, cache)
|
|
|
|
async def login(pw: str) -> object:
|
|
return await service.login(
|
|
username="alice_1", password=pw, client_address="192.0.2.9"
|
|
)
|
|
|
|
async def scenario() -> None:
|
|
# неверная пара — резерв остаётся
|
|
for _ in range(2):
|
|
with pytest.raises(InvalidCredentials):
|
|
await login("wrong password!")
|
|
assert storage.password_hash == old
|
|
# предел: ни чтения БД, ни хэша, верный пароль — тоже 429
|
|
reads = storage.reads
|
|
with pytest.raises(LoginRateLimited) as caught:
|
|
await login(password)
|
|
assert caught.value.retry_after >= 1
|
|
assert storage.reads == reads
|
|
cache.data.clear()
|
|
# 503 БД — резерв возвращён
|
|
storage.down = True
|
|
with pytest.raises(Unavailable):
|
|
await login(password)
|
|
storage.down = False
|
|
assert cache.data == {}
|
|
# успех: пересчёт в одной транзакции с сессией, резерв возвращён
|
|
issued = await login(password)
|
|
assert issued.user == storage.user
|
|
assert storage.rehashed is not None
|
|
assert storage.password_hash.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
|
assert cache.data == {}
|
|
storage.rehashed = None
|
|
await login(password)
|
|
assert storage.rehashed is None
|
|
|
|
asyncio.run(scenario())
|
|
|
|
|
|
def test_busy_budget_skips_rehash_and_counts_as_aborted() -> None:
|
|
password = "correct horse battery"
|
|
old = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY).hash(password)
|
|
storage = FakeStorage(old)
|
|
cache = FakeCache()
|
|
passwords = Passwords(FAST)
|
|
service = _service(storage, passwords, cache)
|
|
calls = {"n": 0}
|
|
original = passwords.budget.run
|
|
|
|
async def second_busy(func, *args): # noqa: ANN001, ANN202
|
|
calls["n"] += 1
|
|
if calls["n"] == 2:
|
|
raise PasswordHashingBusy(waited_ms=5)
|
|
return await original(func, *args)
|
|
|
|
passwords.budget.run = second_busy # type: ignore[method-assign]
|
|
|
|
async def scenario() -> None:
|
|
# проверка прошла, пересчёт — бюджет занят: вход 201 без пересчёта
|
|
await service.login(username="alice_1", password=password, client_address="a")
|
|
assert storage.rehashed is None
|
|
assert storage.password_hash == old
|
|
|
|
async def always_busy(func, *args): # noqa: ANN001, ANN202
|
|
raise PasswordHashingBusy(waited_ms=0)
|
|
|
|
passwords.budget.run = always_busy # type: ignore[method-assign]
|
|
with pytest.raises(PasswordHashingBusy):
|
|
await service.login(
|
|
username="alice_1", password=password, client_address="a"
|
|
)
|
|
# 429 бюджета — не неудача: резерва нет
|
|
assert cache.data == {}
|
|
|
|
asyncio.run(scenario())
|
|
|
|
|
|
# --- предел тела -------------------------------------------------------------
|
|
|
|
|
|
async def _echo(scope, receive, send) -> None: # noqa: ANN001
|
|
body = b""
|
|
while True:
|
|
message = await receive()
|
|
if message["type"] == "http.disconnect":
|
|
break
|
|
body += message.get("body", b"")
|
|
if not message.get("more_body"):
|
|
break
|
|
await send({"type": "http.response.start", "status": 200, "headers": []})
|
|
await send({"type": "http.response.body", "body": str(len(body)).encode()})
|
|
|
|
|
|
class _State:
|
|
settings = type("S", (), {"instance_id": "test-instance"})()
|
|
|
|
|
|
async def _app(scope, receive, send) -> None: # noqa: ANN001
|
|
scope["app"] = type("App", (), {"state": _State()})()
|
|
scope.setdefault("state", {})["request_id"] = "rid-1"
|
|
await BodyLimitMiddleware(_echo, max_bytes=100)(scope, receive, send)
|
|
|
|
|
|
def _post(path: str, content: object) -> httpx.Response:
|
|
async def call() -> httpx.Response:
|
|
transport = httpx.ASGITransport(app=_app)
|
|
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
|
|
return await c.post(path, content=content)
|
|
|
|
return asyncio.run(call())
|
|
|
|
|
|
def test_body_limit() -> None:
|
|
assert _post("/api/v1/chats", b"x" * 100).text == "100"
|
|
declared = _post("/api/v1/chats", b"x" * 101)
|
|
assert declared.status_code == 400
|
|
body = json.loads(declared.text)["error"]
|
|
assert body == {
|
|
"code": "invalid_request",
|
|
"message": BODY_TOO_LARGE,
|
|
"request_id": "rid-1",
|
|
}
|
|
assert declared.headers["X-Instance-Id"] == "test-instance"
|
|
|
|
async def chunks(): # noqa: ANN202
|
|
for _ in range(5):
|
|
yield b"y" * 30
|
|
|
|
assert _post("/api/v1/auth/sessions", chunks()).status_code == 400
|
|
# загрузка вложения — свой предел сервиса
|
|
upload = "/api/v1/chats/0f0f/attachments"
|
|
assert _post(upload, b"z" * 1000).text == "1000"
|