Files
mtusi2026lab7/student-tests/test_login_protection.py
T

128 lines
6.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Лаба 7: предел неудачных входов через публичную точку входа.
Предел пары «username + адрес» (по умолчанию 10 за 300 с), верный пароль и
битый Basic во время блокировки, неизвестный username считается так же,
другой пользователь с того же адреса, предел общий для реплик, успех
сбрасывает счёт пары, подмена `X-Forwarded-For` не обходит предел, тела
отказов без credentials. Предел адреса, окно, отказ Valkey, бюджет хэшей и
пересчёт старого хэша — на стенде отказов (`test_login_faults.py`): здесь
адрес клиента один на все тесты и прогоны набора.
Неудачных входов за прогон набора — около 61: 58 у этого модуля (по 10 у
пары в трёх тестах, 10 у неизвестного username, 18 у сброса успехом) и
остальные у `test_rubric.py::test_wrong_password_is_401`. Два прогона подряд
в одном окне (300 с) — счётчик адреса 122 при пределе 200 (замер на стенде
переноса, 27 ноября 2026): 429 вне тестов предела нет; `make test` неудачных
входов не делает. Каждый тест — свои username.
"""
import base64
import httpx
from helpers import (
BASIC_CHALLENGE,
assert_error,
assert_replicas,
assert_unauthorized,
basic_raw,
instance_id,
login_response,
register,
unique_password,
unique_username,
)
# пределы по умолчанию (src/config.py, Auth)
LOGIN_WINDOW = 300
ACCOUNT_LIMIT = 10
def _fail(client: httpx.Client, username: str, **kwargs: str) -> httpx.Response:
return login_response(client, username, unique_password(), **kwargs)
def _assert_limited(response: httpx.Response) -> dict:
error = assert_error(response, 429, "rate_limited")
retry_after = int(response.headers["Retry-After"])
assert 1 <= retry_after <= LOGIN_WINDOW, response.headers["Retry-After"]
return error
def _assert_no_credentials(
response: httpx.Response, username: str, password: str
) -> None:
encoded = base64.b64encode(f"{username}:{password}".encode()).decode("ascii")
seen = [response.text, *(f"{k}: {v}" for k, v in response.headers.items())]
for secret in (username, password, encoded):
for item in seen:
assert secret not in item, f"credentials leaked into {item[:80]!r}"
def test_account_limit(client: httpx.Client) -> None:
"""Предел пары; верный пароль и битый Basic во время блокировки; другой
пользователь с того же адреса; неизвестный username — тот же счёт и
отказ; тела 401 и 429 без credentials."""
alice = register(client, "limit")
bob = register(client, "limit")
password = unique_password()
for _ in range(ACCOUNT_LIMIT):
response = login_response(client, alice["username"], password)
assert_unauthorized(response, BASIC_CHALLENGE)
_assert_no_credentials(response, alice["username"], password)
limited = login_response(client, alice["username"], password)
error = _assert_limited(limited)
_assert_no_credentials(limited, alice["username"], password)
# верный пароль во время блокировки — тоже 429, сессии нет
correct = login_response(client, alice["username"], alice["password"])
_assert_limited(correct)
assert "token" not in correct.text
# битый Basic — 401 разбора раньше предела
broken = client.post("/api/v1/auth/sessions", headers=basic_raw(b"!!!"))
assert_unauthorized(broken, BASIC_CHALLENGE)
# другой пользователь с того же адреса входит
assert login_response(client, bob["username"], bob["password"]).status_code == 201
unknown = unique_username("ghost")
for _ in range(ACCOUNT_LIMIT):
assert_unauthorized(_fail(client, unknown), BASIC_CHALLENGE)
unknown_error = _assert_limited(_fail(client, unknown))
assert (unknown_error["code"], unknown_error["message"]) == (
error["code"],
error["message"],
)
def test_limit_shared_by_replicas(client: httpx.Client, replicas: int) -> None:
alice = register(client, "shared")
seen = []
for _ in range(ACCOUNT_LIMIT):
response = _fail(client, alice["username"])
assert_unauthorized(response, BASIC_CHALLENGE)
seen.append(instance_id(response))
# неудачи пары обслуживали разные реплики, а предел — общий
assert_replicas(seen, replicas)
for _ in range(2):
_assert_limited(_fail(client, alice["username"]))
def test_success_resets_account(client: httpx.Client) -> None:
alice = register(client, "reset")
for _ in range(ACCOUNT_LIMIT - 1):
assert_unauthorized(_fail(client, alice["username"]), BASIC_CHALLENGE)
ok = login_response(client, alice["username"], alice["password"])
assert ok.status_code == 201, ok.text
for _ in range(ACCOUNT_LIMIT - 1):
assert_unauthorized(_fail(client, alice["username"]), BASIC_CHALLENGE)
def test_forwarded_header_spoofing(client: httpx.Client) -> None:
"""Через LB значение клиента перезаписывается; без LB (`make run`)
реплика заголовок не учитывает — в обоих случаях счёт один."""
alice = register(client, "spoof")
for index in range(ACCOUNT_LIMIT):
response = _fail(client, alice["username"], forwarded_for=f"203.0.113.{index}")
assert_unauthorized(response, BASIC_CHALLENGE)
_assert_limited(_fail(client, alice["username"], forwarded_for="203.0.113.99"))