forked from mtusi2026/mtusi2026lab7
A reserve returned after a KDF budget rejection or 503 left a zero key in Valkey until the end of the window, so a flood with new usernames created keys past the address limit and could evict real counters. SETTLE_SCRIPT and LocalLoginLimiter now delete a counter at zero. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
390 lines
14 KiB
Python
390 lines
14 KiB
Python
"""Предел неудачных входов (design change `auth-hardening`, решения 3, 4, 6;
|
|
спек `login-protection`): `Cache.run_script` на подменённом клиенте,
|
|
`ValkeyLoginLimiter` поверх фейка `Cache` (те же сценарии Lua — их
|
|
семантика в фейке), счётчики процесса и адрес клиента."""
|
|
|
|
import asyncio
|
|
import time
|
|
|
|
import pytest
|
|
from redis.exceptions import NoScriptError, RedisError
|
|
|
|
from fakes import FakeCache, FakeDatabase
|
|
from src.api import dependencies
|
|
from src.infra import login_limit
|
|
from src.infra.cache import Cache
|
|
from src.infra.cache import client as cache_client
|
|
from src.infra.login_limit import (
|
|
LocalLoginLimiter,
|
|
ValkeyLoginLimiter,
|
|
address_part,
|
|
login_keys,
|
|
)
|
|
from src.schemas.enums import LoginOutcome
|
|
|
|
pytestmark = pytest.mark.anyio
|
|
|
|
USER = "alice_secret_name"
|
|
ADDRESS = "198.51.100.23"
|
|
|
|
|
|
class _Records:
|
|
def __init__(self) -> None:
|
|
self.records: list[tuple[str, str, dict]] = []
|
|
|
|
def warning(self, event: str, **fields: object) -> None:
|
|
self.records.append(("warning", event, fields))
|
|
|
|
def info(self, event: str, **fields: object) -> None:
|
|
self.records.append(("info", event, fields))
|
|
|
|
def events(self) -> list[str]:
|
|
return [event for _, event, _ in self.records]
|
|
|
|
|
|
@pytest.fixture
|
|
def records(monkeypatch: pytest.MonkeyPatch) -> _Records:
|
|
recorder = _Records()
|
|
monkeypatch.setattr(login_limit, "logger", recorder)
|
|
monkeypatch.setattr(cache_client, "logger", recorder)
|
|
return recorder
|
|
|
|
|
|
def _limiter(
|
|
cache: FakeCache,
|
|
*,
|
|
window: int = 60,
|
|
account: int = 3,
|
|
address: int = 5,
|
|
max_keys: int = 100,
|
|
) -> ValkeyLoginLimiter:
|
|
return ValkeyLoginLimiter(
|
|
cache=cache, # type: ignore[arg-type]
|
|
window_seconds=window,
|
|
max_failures_per_account=account,
|
|
max_failures_per_address=address,
|
|
local=LocalLoginLimiter(window_seconds=window, max_keys=max_keys),
|
|
)
|
|
|
|
|
|
async def _fail(limiter: ValkeyLoginLimiter, user: str, address: str) -> bool:
|
|
attempt = await limiter.acquire(username=user, address=address)
|
|
if attempt.allowed:
|
|
await limiter.settle(attempt=attempt, outcome=LoginOutcome.FAILED)
|
|
return attempt.allowed
|
|
|
|
|
|
# Cache.run_script на подменённом клиенте redis-py
|
|
|
|
|
|
class _Redis:
|
|
def __init__(self) -> None:
|
|
self.calls: list[str] = []
|
|
self.loaded = False
|
|
self.error: Exception | None = None
|
|
self.delay = 0.0
|
|
|
|
async def evalsha(self, digest: str, count: int, *rest: object) -> int:
|
|
self.calls.append("evalsha")
|
|
if self.delay:
|
|
await asyncio.sleep(self.delay)
|
|
if self.error is not None:
|
|
raise self.error
|
|
if not self.loaded:
|
|
raise NoScriptError("NOSCRIPT")
|
|
return 7
|
|
|
|
async def eval(self, script: str, count: int, *rest: object) -> int:
|
|
self.calls.append("eval")
|
|
self.loaded = True
|
|
return 7
|
|
|
|
|
|
def _cache(client: _Redis) -> Cache:
|
|
return Cache(
|
|
client, # type: ignore[arg-type]
|
|
namespace="db",
|
|
timeout_seconds=0.05,
|
|
retry_after_seconds=60,
|
|
)
|
|
|
|
|
|
async def test_run_script_evalsha_then_eval(records: _Records) -> None:
|
|
client = _Redis()
|
|
cache = _cache(client)
|
|
assert await cache.run_script("return 7", keys=["k"], args=[1]) == 7
|
|
assert await cache.run_script("return 7", keys=["k"], args=[1]) == 7
|
|
# NOSCRIPT — EVAL без SCRIPT LOAD, дальше — EVALSHA
|
|
assert client.calls == ["evalsha", "eval", "evalsha"]
|
|
assert records.records == []
|
|
|
|
|
|
@pytest.mark.parametrize("failure", ["timeout", "redis_error"])
|
|
async def test_run_script_failure_and_skip_window(
|
|
records: _Records,
|
|
failure: str,
|
|
) -> None:
|
|
client = _Redis()
|
|
if failure == "timeout":
|
|
client.delay = 1
|
|
else:
|
|
client.error = RedisError("down")
|
|
cache = _cache(client)
|
|
assert await cache.run_script("return 7", keys=["k"], args=[]) is None
|
|
calls = len(client.calls)
|
|
# окно пропуска: без обращения к клиенту
|
|
assert await cache.run_script("return 7", keys=["k"], args=[]) is None
|
|
assert len(client.calls) == calls
|
|
assert records.events() == ["Cache is unavailable"]
|
|
|
|
|
|
# ключи
|
|
|
|
|
|
def test_keys_without_username_and_address() -> None:
|
|
account, address = login_keys(
|
|
namespace="db",
|
|
username=USER,
|
|
address=ADDRESS,
|
|
)
|
|
assert account.startswith("db:login:ua:")
|
|
assert address.startswith("db:login:a:")
|
|
for key in (account, address):
|
|
assert USER not in key
|
|
assert ADDRESS not in key
|
|
assert len(key.rsplit(":", 1)[1]) == 32
|
|
|
|
|
|
def test_ipv6_folded_to_64() -> None:
|
|
assert address_part("2001:db8:1:2:aaaa::1") == "2001:db8:1:2::/64"
|
|
assert address_part("2001:db8:1:2:bbbb::9") == "2001:db8:1:2::/64"
|
|
assert address_part("::ffff:192.0.2.1") == "192.0.2.1"
|
|
assert address_part(ADDRESS) == ADDRESS
|
|
same = login_keys(namespace="db", username=USER, address="2001:db8::1")
|
|
other = login_keys(namespace="db", username=USER, address="2001:db8::2")
|
|
assert same == other
|
|
|
|
|
|
# ValkeyLoginLimiter поверх фейка Cache
|
|
|
|
|
|
@pytest.fixture
|
|
def cache() -> FakeCache:
|
|
return FakeCache(FakeDatabase(), namespace="db")
|
|
|
|
|
|
async def test_account_limit_and_retry_after(cache: FakeCache) -> None:
|
|
limiter = _limiter(cache, window=60, account=3)
|
|
assert [await _fail(limiter, USER, ADDRESS) for _ in range(3)] == [
|
|
True,
|
|
True,
|
|
True,
|
|
]
|
|
blocked = await limiter.acquire(username=USER, address=ADDRESS)
|
|
assert not blocked.allowed
|
|
assert 1 <= blocked.retry_after_seconds <= 60
|
|
# другой пользователь с того же адреса — свой счёт пары
|
|
other = await limiter.acquire(username="bob_user", address=ADDRESS)
|
|
assert other.allowed
|
|
# тот же пользователь с другого адреса — тоже
|
|
elsewhere = await limiter.acquire(username=USER, address="192.0.2.99")
|
|
assert elsewhere.allowed
|
|
|
|
|
|
async def test_address_limit(cache: FakeCache) -> None:
|
|
limiter = _limiter(cache, account=3, address=5)
|
|
for index in range(5):
|
|
assert await _fail(limiter, f"user_{index}", ADDRESS)
|
|
assert not (
|
|
await limiter.acquire(username="fresh_user", address=ADDRESS)
|
|
).allowed
|
|
assert (
|
|
await limiter.acquire(username="fresh_user", address="192.0.2.7")
|
|
).allowed
|
|
|
|
|
|
async def test_reserve_blocks_concurrent_attempts(cache: FakeCache) -> None:
|
|
limiter = _limiter(cache, account=3, address=100)
|
|
attempts = await asyncio.gather(
|
|
*[limiter.acquire(username=USER, address=ADDRESS) for _ in range(10)],
|
|
)
|
|
# резерв занят до проверки пароля: сверх предела не проходят
|
|
assert sum(attempt.allowed for attempt in attempts) == 3
|
|
|
|
|
|
async def test_settle_returns_reserve_and_success_resets(
|
|
cache: FakeCache,
|
|
) -> None:
|
|
limiter = _limiter(cache, account=3, address=100)
|
|
for _ in range(2):
|
|
assert await _fail(limiter, USER, ADDRESS)
|
|
# прерванная попытка (503, 429 бюджета) резерв возвращает
|
|
aborted = await limiter.acquire(username=USER, address=ADDRESS)
|
|
await limiter.settle(attempt=aborted, outcome=LoginOutcome.ABORTED)
|
|
assert await _fail(limiter, USER, ADDRESS)
|
|
assert not (await limiter.acquire(username=USER, address=ADDRESS)).allowed
|
|
# ещё раз: окно не сбрасывается неудачей
|
|
cache.values.clear()
|
|
cache.expires.clear()
|
|
for _ in range(2):
|
|
assert await _fail(limiter, USER, ADDRESS)
|
|
success = await limiter.acquire(username=USER, address=ADDRESS)
|
|
await limiter.settle(attempt=success, outcome=LoginOutcome.SUCCEEDED)
|
|
# успех начинает счёт пары заново: снова три неудачи
|
|
assert [await _fail(limiter, USER, ADDRESS) for _ in range(3)] == [
|
|
True,
|
|
True,
|
|
True,
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"outcome",
|
|
[LoginOutcome.ABORTED, LoginOutcome.SUCCEEDED],
|
|
)
|
|
async def test_returned_reserve_leaves_no_key(
|
|
cache: FakeCache,
|
|
outcome: LoginOutcome,
|
|
) -> None:
|
|
"""Задача 13.8: счётчик, дошедший до 0, удаляется — попытка без неудачи
|
|
(503, 429 бюджета, отмена, успех) ключей не оставляет, и поток с новыми
|
|
username не заводит ключи мимо предела адреса."""
|
|
limiter = _limiter(cache, account=3, address=100)
|
|
for index in range(5):
|
|
attempt = await limiter.acquire(
|
|
username=f"fresh_{index}",
|
|
address=ADDRESS,
|
|
)
|
|
assert attempt.allowed
|
|
await limiter.settle(attempt=attempt, outcome=outcome)
|
|
assert cache.values == {}
|
|
assert cache.expires == {}
|
|
# неудача остаётся счётом, возврат резерва поверх неё — нет
|
|
assert await _fail(limiter, USER, ADDRESS)
|
|
aborted = await limiter.acquire(username=USER, address=ADDRESS)
|
|
await limiter.settle(attempt=aborted, outcome=LoginOutcome.ABORTED)
|
|
assert sorted(cache.values.values()) == ["1", "1"]
|
|
|
|
|
|
async def test_window_expiry(cache: FakeCache) -> None:
|
|
limiter = _limiter(cache, window=1, account=1)
|
|
assert await _fail(limiter, USER, ADDRESS)
|
|
assert not (await limiter.acquire(username=USER, address=ADDRESS)).allowed
|
|
await asyncio.sleep(1.05)
|
|
assert (await limiter.acquire(username=USER, address=ADDRESS)).allowed
|
|
|
|
|
|
async def test_zero_limit_touches_no_key(cache: FakeCache) -> None:
|
|
limiter = _limiter(cache, account=0, address=0)
|
|
for _ in range(20):
|
|
assert await _fail(limiter, USER, ADDRESS)
|
|
assert cache.values == {}
|
|
|
|
|
|
async def test_process_counters_on_cache_failure_and_back(
|
|
cache: FakeCache,
|
|
records: _Records,
|
|
) -> None:
|
|
limiter = _limiter(cache, account=2, address=100)
|
|
cache.failing = True
|
|
assert await _fail(limiter, USER, ADDRESS)
|
|
assert await _fail(limiter, USER, ADDRESS)
|
|
blocked = await limiter.acquire(username=USER, address=ADDRESS)
|
|
assert not blocked.allowed
|
|
assert not blocked.shared
|
|
assert 1 <= blocked.retry_after_seconds <= 60
|
|
# запись перехода — одна на отказ
|
|
assert records.events().count("Login limiter uses process counters") == 1
|
|
cache.failing = False
|
|
back = await limiter.acquire(username=USER, address=ADDRESS)
|
|
# локальный счёт в Valkey не переносится: окно перехода мягче
|
|
assert back.allowed
|
|
assert back.shared
|
|
assert records.events()[-1] == "Login limiter uses shared counters"
|
|
for _, _, fields in records.records:
|
|
assert USER not in str(fields)
|
|
assert ADDRESS not in str(fields)
|
|
|
|
|
|
async def test_local_counters_bounded(records: _Records) -> None:
|
|
local = LocalLoginLimiter(window_seconds=60, max_keys=4)
|
|
for index in range(4):
|
|
wait, counted = local.acquire({f"k{index}": 1})
|
|
assert (wait, counted) == (0, (f"k{index}",))
|
|
# полон: новый ключ не заводится, попытка разрешена с warning
|
|
wait, counted = local.acquire({"new": 1})
|
|
assert (wait, counted) == (0, ())
|
|
assert len(local) == 4
|
|
assert records.events() == ["Login limiter process counters are full"]
|
|
# истёкшие окна выбрасываются первыми
|
|
for window in local._windows.values():
|
|
window.expires_at = time.monotonic() - 1
|
|
wait, counted = local.acquire({"new": 1})
|
|
assert counted == ("new",)
|
|
assert len(local) == 1
|
|
|
|
|
|
def test_local_counter_at_zero_removed() -> None:
|
|
"""Задача 13.8: запись процесса, дошедшая до 0, удаляется, как ключ в
|
|
Valkey; неудача остаётся."""
|
|
local = LocalLoginLimiter(window_seconds=60, max_keys=10)
|
|
_, counted = local.acquire({"pair": 3, "addr": 5})
|
|
local.release(dict.fromkeys(counted, "decr"))
|
|
assert len(local) == 0
|
|
_, counted = local.acquire({"pair": 3, "addr": 5})
|
|
assert len(local) == 2
|
|
_, again = local.acquire({"pair": 3, "addr": 5})
|
|
local.release(dict.fromkeys(again, "decr"))
|
|
# первый резерв не возвращён (неудача): обе записи со счётом 1
|
|
assert {key: window.count for key, window in local._windows.items()} == {
|
|
"pair": 1,
|
|
"addr": 1,
|
|
}
|
|
|
|
|
|
# адрес клиента
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("forwarded", "expected", "warned"),
|
|
[
|
|
("203.0.113.5", "203.0.113.5", False),
|
|
(" 2001:db8::5 ", "2001:db8::5", False),
|
|
("garbage", "10.0.0.2", True),
|
|
("203.0.113.5, 203.0.113.6", "10.0.0.2", True),
|
|
(None, "10.0.0.2", True),
|
|
],
|
|
)
|
|
def test_client_address_from_balancer(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
forwarded: str | None,
|
|
expected: str,
|
|
warned: bool,
|
|
) -> None:
|
|
recorder = _Records()
|
|
monkeypatch.setattr(dependencies, "logger", recorder)
|
|
assert (
|
|
dependencies.client_address(
|
|
forwarded=forwarded,
|
|
peer="10.0.0.2",
|
|
trust_forwarded=True,
|
|
)
|
|
== expected
|
|
)
|
|
assert (
|
|
recorder.events() == ["Client address header is missing"]
|
|
) is warned
|
|
for _, _, fields in recorder.records:
|
|
assert "10.0.0.2" not in str(fields)
|
|
|
|
|
|
def test_console_ignores_forwarded_header() -> None:
|
|
assert (
|
|
dependencies.client_address(
|
|
forwarded="203.0.113.5",
|
|
peer="127.0.0.1",
|
|
trust_forwarded=False,
|
|
)
|
|
== "127.0.0.1"
|
|
)
|