forked from mtusi2026/mtusi2026lab7
fix: delete login counters that drop to zero
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>
This commit is contained in:
@@ -238,6 +238,34 @@ async def test_settle_returns_reserve_and_success_resets(
|
||||
]
|
||||
|
||||
|
||||
@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)
|
||||
@@ -296,6 +324,24 @@ async def test_local_counters_bounded(records: _Records) -> None:
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
# адрес клиента
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user