"""Лаба 7, защита входа на стенде отказов (выполняет только `make failure-checks`). Клиент набора — в роли LB (пара `haproxy`): ставит `X-Forwarded-For`, как HAProxy (по умолчанию 192.0.2.1, у тестов — свои адреса TEST-NET-2). «Тесный» API — окно 10 с, пара 3, адрес 6 (`FAULT_TIGHT_ENV`); «узкий по загрузкам» — бюджет хэшей 1 место, 1 ждущий, 0,5 с (`FAULT_UPLOADS_ENV`); обычный API — пределы по умолчанию (10 / 200 за 300 с). Что проверяется: предел адреса и независимость адресов, окно истекло, нет заголовка — адрес соединения, подмена пределов окружением (тесный API запущен с `LOGIN_MAX_FAILURES_PER_ACCOUNT=3` без правки файлов); Valkey остановлен — счётчики процесса; ключи Valkey без username и адреса; бюджет хэшей — 429 у входа и регистрации, лёгкий запрос при занятом бюджете; пересчёт старого хэша при входе и его отсутствие при неудаче; записи журнала без username, пароля и адреса. """ import os import threading import time import uuid from collections.abc import Callable, Iterator from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from typing import Any import httpx import pytest from conftest import FAULT_TIGHT_BASE_URL, FAULT_UPLOADS_BASE_URL from helpers import ( BASIC_CHALLENGE, ME, USERS, assert_error, assert_unauthorized, headers, http_client, login_response, register, unique_username, ) pytestmark = pytest.mark.fault type Stand = Callable[..., str] TIGHT_WINDOW = 10 TIGHT_ACCOUNT = 3 TIGHT_ADDRESS = 6 DEFAULT_ACCOUNT = 10 DEFAULT_WINDOW = 300 CACHE_RETRY_AFTER = 5.0 SLACK = 0.5 # одновременных клиентов против бюджета 1 место + 1 ждущий KDF_CLIENTS = 8 EXPECTED_TIGHT = { "LOGIN_WINDOW_SECONDS": "10", "LOGIN_MAX_FAILURES_PER_ACCOUNT": "3", "LOGIN_MAX_FAILURES_PER_ADDRESS": "6", } EXPECTED_UPLOADS = { "KDF_CONCURRENCY": "1", "KDF_MAX_WAITING": "1", "KDF_WAIT_TIMEOUT": "0.5", } # прежние параметры (RFC 9106 low memory) — префикс строки хэша OLD_PARAMS = "$argon2id$v=19$m=65536,t=3,p=4" def _env(name: str) -> dict[str, str]: raw = os.environ.get(name, "") return dict(item.split("=", 1) for item in raw.split(",") if item) def assert_stand(name: str, expected: dict[str, str]) -> None: """Без этих значений у стенда тесты ничего не доказывают.""" got = {key: _env(name).get(key) for key in expected} assert got == expected, f"{name}: stand started with {got}" def fail(client: httpx.Client, username: str, address: str | None) -> httpx.Response: return login_response( client, username, f"wrong-{uuid.uuid4().hex}", forwarded_for=address ) def assert_limited(response: httpx.Response, window: int) -> int: assert_error(response, 429, "rate_limited") retry_after = int(response.headers["Retry-After"]) assert 1 <= retry_after <= window, retry_after return retry_after def assert_clean_log(log: str, secrets: list[str]) -> None: for secret in secrets: assert secret not in log, "username, password or address leaked into the log" @contextmanager def stopped(stand: Stand, service: str) -> Iterator[None]: stand("stop", service) try: yield finally: stand("start", service) def at_once(count: int, call: Callable[[int], httpx.Response]) -> list[httpx.Response]: """`count` вызовов за барьером, у каждого своё соединение.""" barrier = threading.Barrier(count) def run(index: int) -> httpx.Response: barrier.wait(timeout=30) return call(index) with ThreadPoolExecutor(count) as pool: return list(pool.map(run, range(count))) # --- «тесный» API: окно и пределы ---------------------------------------------- def test_login_address_limit(tight_client: httpx.Client, stand: Stand) -> None: assert_stand("FAULT_TIGHT_ENV", EXPECTED_TIGHT) address = "198.51.100.11" # по 2 неудачи на username (меньше предела пары 3), пока не исчерпан # предел адреса 6 for _ in range(TIGHT_ADDRESS // 2): username = unique_username("addr") for _ in range(2): assert_unauthorized(fail(tight_client, username, address), BASIC_CHALLENGE) fresh = register(tight_client, "addr") limited = login_response( tight_client, fresh["username"], fresh["password"], forwarded_for=address ) assert_limited(limited, TIGHT_WINDOW) # с другого адреса — обычные 401 и 201 other = "198.51.100.12" assert_unauthorized( fail(tight_client, unique_username("addr"), other), BASIC_CHALLENGE ) ok = login_response( tight_client, fresh["username"], fresh["password"], forwarded_for=other ) assert ok.status_code == 201, ok.text log = stand("api-log", "tight") assert "login rate limited retry_after=" in log assert_clean_log(log, [fresh["username"], fresh["password"], address]) def test_login_window_expires(tight_client: httpx.Client) -> None: """И подмена пределов окружением: тесный API запущен с `LOGIN_MAX_FAILURES_PER_ACCOUNT=3` — четвёртая неудача пары получает 429.""" assert_stand("FAULT_TIGHT_ENV", EXPECTED_TIGHT) address = "198.51.100.21" actor = register(tight_client, "window") for _ in range(TIGHT_ACCOUNT): assert_unauthorized( fail(tight_client, actor["username"], address), BASIC_CHALLENGE ) retry_after = assert_limited( fail(tight_client, actor["username"], address), TIGHT_WINDOW ) print(f"limited: Retry-After {retry_after}s") time.sleep(retry_after + SLACK) ok = login_response( tight_client, actor["username"], actor["password"], forwarded_for=address ) assert ok.status_code == 201, ok.text def test_login_addresses_differ(tight_client: httpx.Client) -> None: assert_stand("FAULT_TIGHT_ENV", EXPECTED_TIGHT) actor = register(tight_client, "differ") for _ in range(TIGHT_ACCOUNT): fail(tight_client, actor["username"], "198.51.100.31") assert_limited(fail(tight_client, actor["username"], "198.51.100.31"), TIGHT_WINDOW) assert_unauthorized( fail(tight_client, actor["username"], "198.51.100.32"), BASIC_CHALLENGE ) def test_login_without_forwarded_header(stand: Stand) -> None: assert_stand("FAULT_TIGHT_ENV", EXPECTED_TIGHT) with http_client(FAULT_TIGHT_BASE_URL, forwarded_for=None) as bare: actor = register(bare, "bare") for _ in range(TIGHT_ACCOUNT): assert_unauthorized(fail(bare, actor["username"], None), BASIC_CHALLENGE) assert_limited(fail(bare, actor["username"], None), TIGHT_WINDOW) # тот же username с адресом A — другая пара assert_unauthorized( fail(bare, actor["username"], "198.51.100.41"), BASIC_CHALLENGE ) assert "client address header is missing" in stand("api-log", "tight") # --- обычный API: Valkey и ключи ------------------------------------------------ def test_login_limit_without_valkey(client: httpx.Client, stand: Stand) -> None: address = "198.51.100.51" actor = register(client, "novalkey") other = unique_username("novalkey") with stopped(stand, "valkey"): ok = login_response( client, actor["username"], actor["password"], forwarded_for=address ) assert ok.status_code == 201, ok.text for _ in range(DEFAULT_ACCOUNT): assert_unauthorized(fail(client, other, address), BASIC_CHALLENGE) assert_limited(fail(client, other, address), DEFAULT_WINDOW) assert "login limiter uses process counters" in stand("api-log", "default") def counter_keys(stand: Stand) -> dict[str, str]: """Ключ счётчика входа → значение (hook `login-keys`).""" return { key: value for key, value, _ in (line.split() for line in stand("login-keys").splitlines()) } def test_login_counter_keys(client: httpx.Client, stand: Stand) -> None: address = "198.51.100.61" username = unique_username("keys") # после отказа Valkey в прошлом тесте API ещё до 5 с считает в процессе: # неудачи — пока счётчик не появится в Valkey deadline = time.monotonic() + CACHE_RETRY_AFTER + 2 lines: list[str] = [] while not lines and time.monotonic() < deadline: fail(client, username, address) lines = stand("login-keys").splitlines() time.sleep(0.5) assert lines, "no login counters in Valkey" for line in lines: assert username not in line assert address not in line # --- «узкий по загрузкам» API: бюджет хэшей --------------------------------------- def _login_all(actors: list[dict[str, Any]]) -> list[httpx.Response]: def login(index: int) -> httpx.Response: with http_client(FAULT_UPLOADS_BASE_URL, timeout=20) as own: actor = actors[index] return login_response( own, actor["username"], actor["password"], forwarded_for=f"198.51.100.{100 + index}", ) return at_once(len(actors), login) def test_kdf_budget_login(uploads_client: httpx.Client, stand: Stand) -> None: """И возврат резерва: после всплеска в Valkey только ключи неудачи (пара и адрес со значением 1), а не ключи на каждую попытку.""" assert_stand("FAULT_UPLOADS_ENV", EXPECTED_UPLOADS) actors = [register(uploads_client, "kdf") for _ in range(KDF_CLIENTS)] before = counter_keys(stand) stranger = unique_username("kdf") deadline = time.monotonic() + CACHE_RETRY_AFTER + 2 failed: dict[str, str] = {} while len(failed) < 2 and time.monotonic() < deadline: assert_unauthorized( fail(uploads_client, stranger, "198.51.100.99"), BASIC_CHALLENGE ) failed = {k: v for k, v in counter_keys(stand).items() if k not in before} assert len(failed) == 2, f"no login counters in Valkey: {failed}" answers = _login_all(actors) statuses = [response.status_code for response in answers] print(f"kdf budget: login statuses {sorted(statuses)}") assert set(statuses) <= {201, 429}, statuses assert 429 in statuses, statuses for response in answers: if response.status_code == 429: assert_error(response, 429, "rate_limited") assert response.headers["Retry-After"] == "1" else: token = response.json()["token"] me = uploads_client.get(ME, headers={"Authorization": f"Bearer {token}"}) assert me.status_code == 200 log = stand("api-log", "uploads") assert "password hashing is busy operation=login" in log assert_clean_log(log, [a["username"] for a in actors]) new = {k: v for k, v in counter_keys(stand).items() if k not in before} assert new == failed, f"login counters after the burst: {new}, before: {failed}" def test_kdf_budget_register(uploads_client: httpx.Client, stand: Stand) -> None: assert_stand("FAULT_UPLOADS_ENV", EXPECTED_UPLOADS) names = [unique_username("kdfreg") for _ in range(KDF_CLIENTS)] passwords = [f"pw-{uuid.uuid4().hex}" for _ in names] def create(index: int) -> httpx.Response: with http_client(FAULT_UPLOADS_BASE_URL, timeout=20) as own: return own.post( USERS, json={ "username": names[index], "display_name": "Budget", "password": passwords[index], }, ) answers = at_once(KDF_CLIENTS, create) statuses = [response.status_code for response in answers] print(f"kdf budget: register statuses {sorted(statuses)}") assert set(statuses) <= {201, 429}, statuses assert 429 in statuses, statuses for index, response in enumerate(answers): if response.status_code == 429: assert response.headers["Retry-After"] == "1" # строки не осталось: тот же username регистрируется again = uploads_client.post( USERS, json={ "username": names[index], "display_name": "Budget", "password": passwords[index], }, ) assert again.status_code == 201, again.text assert "password hashing is busy operation=register" in stand("api-log", "uploads") def test_light_request_with_busy_budget(uploads_client: httpx.Client) -> None: assert_stand("FAULT_UPLOADS_ENV", EXPECTED_UPLOADS) reader = register(uploads_client, "light") actors = [register(uploads_client, "light") for _ in range(KDF_CLIENTS)] stop = threading.Event() def flood(index: int) -> None: with http_client(FAULT_UPLOADS_BASE_URL, timeout=20) as own: actor = actors[index] while not stop.is_set(): login_response( own, actor["username"], actor["password"], forwarded_for=f"198.51.100.{150 + index}", ) with ThreadPoolExecutor(KDF_CLIENTS) as pool: futures = [pool.submit(flood, index) for index in range(KDF_CLIENTS)] try: time.sleep(0.5) for _ in range(5): started = time.monotonic() response = uploads_client.get(ME, headers=headers(reader)) took = time.monotonic() - started assert response.status_code == 200 # лёгкий запрос бюджет хэшей не ждёт assert took < 1, f"GET /users/me took {took:.2f}s" finally: stop.set() for future in futures: future.result() # --- пересчёт старого хэша ---------------------------------------------------------- def test_old_hash_rehashed_on_login(client: httpx.Client, stand: Stand) -> None: actor = register(client, "rehash") stand("set-password-hash", actor["username"], data=actor["password"].encode()) assert stand("password-params", actor["username"]) == OLD_PARAMS first = login_response(client, actor["username"], actor["password"]) assert first.status_code == 201, first.text current = stand("password-params", actor["username"]) assert current != OLD_PARAMS assert current.startswith("$argon2id$v=19$m=") second = login_response(client, actor["username"], actor["password"]) assert second.status_code == 201, second.text assert stand("password-params", actor["username"]) == current log = stand("api-log", "default") lines = [ line for line in log.splitlines() if "password rehashed" in line and actor["id"] in line ] assert len(lines) == 1, lines assert "from=m=65536,t=3,p=4" in lines[0] assert "$argon2id$" not in lines[0] assert_clean_log(log, [actor["username"], actor["password"]]) def test_failed_login_keeps_old_hash(client: httpx.Client, stand: Stand) -> None: actor = register(client, "rehash") stand("set-password-hash", actor["username"], data=actor["password"].encode()) assert_unauthorized( fail(client, actor["username"], "198.51.100.71"), BASIC_CHALLENGE ) assert stand("password-params", actor["username"]) == OLD_PARAMS