fix: address auth-hardening verify findings

Drop the body-limit rule from HAProxy (user decision 2026-11-18): the
replica middleware answers 400 with X-Instance-Id, tests require the
header again. Widen the failure_checks selection in the trust matrix,
name 13fdd18 in the evidence header, document Valkey LRU eviction of
login counters and the allowlist as trusted X-Forwarded-For senders,
check waited_ms of KDF budget rejections in the queue scenario.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 10:31:57 +03:00
co-authored by Claude Opus 5.5
parent 4d117f0297
commit 3f4771c9d9
22 changed files with 372 additions and 127 deletions
+38 -1
View File
@@ -279,6 +279,21 @@ async def test_two_slow_steps_fit_single_deadline(
assert elapsed < BLOCK_SECONDS + MARGIN
class _SessionRecords:
"""Записи логгера `session_service`: событие и поля."""
def __init__(self) -> None:
self.records: list[tuple[str, dict[str, object]]] = []
def bind(self, **_: object) -> "_SessionRecords":
return self
def _record(self, event_name: str, **fields: object) -> None:
self.records.append((event_name, fields))
debug = info = warning = error = _record
async def test_hash_queue_gets_deadline(
client: httpx.AsyncClient,
monkeypatch: pytest.MonkeyPatch,
@@ -289,10 +304,18 @@ async def test_hash_queue_gets_deadline(
а не ждут очередь без срока; 503 — только от пула (один на «тесном»
API), не от очереди хэшей. Предел неудачных входов выключен: 200
одновременных попыток одной пары он остановил бы резервом раньше
бюджета (это его сценарий, не этот)."""
бюджета (это его сценарий, не этот).
Время в очереди 429 (verify S4) — `waited_ms` записи «Password hashing
is busy» на каждый 429: не больше `kdf_wait_timeout_seconds` с запасом.
Полное время ответа 429 включает ещё блок чтения хэша, а он на «тесном»
API ждёт единственное соединение пула до `pool_timeout_seconds`, — по
нему отдельно ограничено только общим сроком T."""
limiter = dependencies.login_limiter
monkeypatch.setattr(limiter, "max_failures_per_account", 0)
monkeypatch.setattr(limiter, "max_failures_per_address", 0)
wait_timeout = dependencies.settings.auth.kdf_wait_timeout_seconds
assert wait_timeout < BLOCK_SECONDS
headers, _ = await _register_login(client)
username = (await client.get("/users/me", headers=headers)).json()[
"username"
@@ -310,12 +333,26 @@ async def test_hash_queue_gets_deadline(
response.headers.get("Retry-After"),
)
records = _SessionRecords()
monkeypatch.setattr(session_module, "logger", records)
results = await asyncio.gather(*(login() for _ in range(200)))
statuses = {status for status, _, _ in results}
assert 429 in statuses
assert statuses <= {201, 429, 503}
assert {after for status, _, after in results if status == 429} == {"1"}
assert max(elapsed for _, elapsed, _ in results) < BLOCK_SECONDS + MARGIN
waits = [
fields["waited_ms"]
for event_name, fields in records.records
if event_name == "Password hashing is busy"
]
rejected = sum(1 for status, _, _ in results if status == 429)
assert len(waits) == rejected
assert max(waits) <= (wait_timeout + MARGIN) * 1000
# «очередь полна» — 0 мс; отказ по сроку (если был: очередь могла
# разойтись раньше срока) ждал не меньше срока
timed_out = [wait for wait in waits if wait > 0]
assert all(wait >= wait_timeout * 1000 * 0.9 for wait in timed_out)
class _PoolRecords(logging.Handler):