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:
2026-11-18 10:42:25 +03:00
co-authored by Claude Opus 5.5
parent 3f4771c9d9
commit fa5ba51d6a
10 changed files with 163 additions and 30 deletions
+46
View File
@@ -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,
}
# адрес клиента