forked from mtusi2026/mtusi2026lab7
feat: harden authentication (Argon2id by measurement, login limits, body limit)
Apply auth-hardening up to the bench_login label: Argon2id parameters from [auth] chosen by driver.py argon2-params (m=64 MiB, t=2, p=1), rehash on login, per-process KDF budget with 429, shared login failure limit in Valkey with a local fallback, X-Forwarded-For from HAProxy, 64 KiB body limit (400) in LB and middleware, bench login profile, tests, threat model and trust matrix rows. Hypotheses H1-H4 are committed here before the baseline label. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -43,7 +43,10 @@ from jsonschema import Draft202012Validator, FormatChecker
|
||||
|
||||
import images
|
||||
from api_client import API, Actor, Api, new_key
|
||||
from api_client import unique_username as unique_name
|
||||
from conftest import UPLOADS_CLIENT_TIMEOUT_S
|
||||
from contract import (
|
||||
BASIC_CHALLENGE,
|
||||
BEARER_CHALLENGE,
|
||||
assert_accepted,
|
||||
assert_content,
|
||||
@@ -1240,9 +1243,17 @@ HOLD_MAX_S = 10
|
||||
|
||||
|
||||
def assert_uploads_stand() -> None:
|
||||
"""Без этого окружения «узкого» API тесты мест ничего не доказывают."""
|
||||
assert UPLOADS_ENV == EXPECTED_UPLOADS_ENV, (
|
||||
f"uploads stand started with {UPLOADS_ENV}, "
|
||||
"""Без этого окружения «узкого» API тесты мест ничего не доказывают.
|
||||
|
||||
Сверяются только `UPLOADS__*`: с change auth-hardening у того же API ещё
|
||||
бюджет хэшей (`AUTH__*`, его сверяет `assert_uploads_auth_stand`)."""
|
||||
uploads_env = {
|
||||
key: value
|
||||
for key, value in UPLOADS_ENV.items()
|
||||
if key.startswith("UPLOADS__")
|
||||
}
|
||||
assert uploads_env == EXPECTED_UPLOADS_ENV, (
|
||||
f"uploads stand started with {uploads_env}, "
|
||||
f"expected {EXPECTED_UPLOADS_ENV}"
|
||||
)
|
||||
|
||||
@@ -6471,3 +6482,420 @@ def test_backlog_off(
|
||||
assert unfinished_jobs(stand) == BACKLOG_LIMIT + 2
|
||||
for attachment in accepted:
|
||||
api.wait_attachment(alice, attachment["id"], timeout=JOB_WAIT_S)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Защита входа (change auth-hardening, design, решение 10): клиент в роли LB
|
||||
# ставит X-Forwarded-For (по умолчанию 192.0.2.1, у каждого теста — свои
|
||||
# адреса из TEST-NET), «тесный» API — окно 10 с, пара 3, адрес 6
|
||||
# (FAULT_TIGHT_ENV), «узкий по загрузкам» — бюджет хэшей 1 место, 1 ждущий,
|
||||
# 0,5 с (FAULT_UPLOADS_ENV). Обычный API — пределы по умолчанию (10 / 200)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
TIGHT_ENV = dict(
|
||||
item.split("=", 1)
|
||||
for item in os.environ.get("FAULT_TIGHT_ENV", "").split()
|
||||
)
|
||||
EXPECTED_TIGHT_AUTH = {
|
||||
"AUTH__LOGIN_WINDOW_SECONDS": "10",
|
||||
"AUTH__LOGIN_MAX_FAILURES_PER_ACCOUNT": "3",
|
||||
"AUTH__LOGIN_MAX_FAILURES_PER_ADDRESS": "6",
|
||||
"AUTH__KDF_WAIT_TIMEOUT_SECONDS": "1",
|
||||
}
|
||||
EXPECTED_UPLOADS_AUTH = {
|
||||
"AUTH__KDF_CONCURRENCY": "1",
|
||||
"AUTH__KDF_MAX_WAITING": "1",
|
||||
"AUTH__KDF_WAIT_TIMEOUT_SECONDS": "0.5",
|
||||
}
|
||||
TIGHT_WINDOW_S = 10
|
||||
TIGHT_ACCOUNT_LIMIT = 3
|
||||
TIGHT_ADDRESS_LIMIT = 6
|
||||
DEFAULT_ACCOUNT_LIMIT = 10
|
||||
# одновременных клиентов против бюджета 1 место + 1 ждущий
|
||||
KDF_CLIENTS = 8
|
||||
# прежние параметры хэша (RFC 9106 low-memory) и текущие по умолчанию
|
||||
OLD_HASH_PARAMS = "$argon2id$v=19$m=65536,t=3,p=4"
|
||||
CURRENT_HASH_PARAMS = "$argon2id$v=19$m=65536,t=2,p=1"
|
||||
|
||||
|
||||
def assert_tight_auth_stand() -> None:
|
||||
got = {key: TIGHT_ENV.get(key) for key in EXPECTED_TIGHT_AUTH}
|
||||
assert got == EXPECTED_TIGHT_AUTH, f"tight stand started with {got}"
|
||||
|
||||
|
||||
def assert_uploads_auth_stand() -> None:
|
||||
got = {key: UPLOADS_ENV.get(key) for key in EXPECTED_UPLOADS_AUTH}
|
||||
assert got == EXPECTED_UPLOADS_AUTH, f"uploads stand started with {got}"
|
||||
|
||||
|
||||
def fail_login(
|
||||
api: Api,
|
||||
username: str,
|
||||
*,
|
||||
address: str | None,
|
||||
) -> httpx.Response:
|
||||
return api.login_response(
|
||||
username,
|
||||
f"wrong-{uuid.uuid4().hex}",
|
||||
forwarded_for=address,
|
||||
)
|
||||
|
||||
|
||||
def assert_login_limited(resp: httpx.Response, window: int) -> int:
|
||||
assert_error(resp, 429)
|
||||
retry_after = int(resp.headers["Retry-After"])
|
||||
assert 1 <= retry_after <= window, retry_after
|
||||
return retry_after
|
||||
|
||||
|
||||
def api_records(stand: Stand, role: str) -> list[dict[str, Any]]:
|
||||
return [
|
||||
json.loads(line)
|
||||
for line in stand("api-log", role).splitlines()
|
||||
if line.startswith("{")
|
||||
]
|
||||
|
||||
|
||||
def assert_records_clean(
|
||||
records: Sequence[dict[str, Any]],
|
||||
secrets: Sequence[str],
|
||||
) -> None:
|
||||
for record in records:
|
||||
text = json.dumps(record, ensure_ascii=False)
|
||||
for secret in secrets:
|
||||
assert secret not in text, f"{record.get('event')}: leaked value"
|
||||
|
||||
|
||||
def at_once(count: int, call: Callable[[int], httpx.Response]) -> list:
|
||||
"""`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)))
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Предел адреса")
|
||||
def test_login_address_limit(tight_api: Api, stand: Stand) -> None:
|
||||
assert_tight_auth_stand()
|
||||
address = "198.51.100.11"
|
||||
users = [unique_name() for _ in range(TIGHT_ADDRESS_LIMIT // 2)]
|
||||
# по 2 неудачи на username (меньше предела пары 3), пока не исчерпан
|
||||
# предел адреса 6
|
||||
for username in users:
|
||||
for _ in range(2):
|
||||
assert_unauthorized(
|
||||
fail_login(tight_api, username, address=address),
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
fresh = tight_api.register()
|
||||
limited = tight_api.login_response(
|
||||
fresh.username,
|
||||
fresh.password,
|
||||
forwarded_for=address,
|
||||
)
|
||||
assert_login_limited(limited, TIGHT_WINDOW_S)
|
||||
# с другого адреса — обычный ответ
|
||||
assert_unauthorized(
|
||||
fail_login(tight_api, unique_name(), address="198.51.100.12"),
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
assert_ok(
|
||||
tight_api.login_response(
|
||||
fresh.username,
|
||||
fresh.password,
|
||||
forwarded_for="198.51.100.12",
|
||||
),
|
||||
201,
|
||||
"Session",
|
||||
)
|
||||
# запись отказа — с остатком окна, без username и адреса
|
||||
records = [
|
||||
record
|
||||
for record in api_records(stand, "tight")
|
||||
if record.get("event") == "Login rate limited"
|
||||
]
|
||||
assert records, "no 'Login rate limited' record"
|
||||
assert all("retry_after_seconds" in record for record in records)
|
||||
assert_records_clean(records, [fresh.username, address])
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Окно истекло")
|
||||
def test_login_window_expires(tight_api: Api) -> None:
|
||||
"""И сценарий `service-configuration` «Подмена пределов входа
|
||||
окружением» (вне сверки покрытия): «тесный» API запущен с
|
||||
`AUTH__LOGIN_MAX_FAILURES_PER_ACCOUNT=3`, файлы те же — четвёртая
|
||||
неудача пары получает 429."""
|
||||
assert_tight_auth_stand()
|
||||
address = "198.51.100.21"
|
||||
actor = tight_api.register()
|
||||
for _ in range(TIGHT_ACCOUNT_LIMIT):
|
||||
assert_unauthorized(
|
||||
fail_login(tight_api, actor.username, address=address),
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
retry_after = assert_login_limited(
|
||||
fail_login(tight_api, actor.username, address=address),
|
||||
TIGHT_WINDOW_S,
|
||||
)
|
||||
time.sleep(retry_after + SLACK_S)
|
||||
assert_ok(
|
||||
tight_api.login_response(
|
||||
actor.username,
|
||||
actor.password,
|
||||
forwarded_for=address,
|
||||
),
|
||||
201,
|
||||
"Session",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Адреса балансировщика различаются")
|
||||
def test_login_addresses_differ(tight_api: Api) -> None:
|
||||
assert_tight_auth_stand()
|
||||
actor = tight_api.register()
|
||||
for _ in range(TIGHT_ACCOUNT_LIMIT):
|
||||
fail_login(tight_api, actor.username, address="198.51.100.31")
|
||||
assert_login_limited(
|
||||
fail_login(tight_api, actor.username, address="198.51.100.31"),
|
||||
TIGHT_WINDOW_S,
|
||||
)
|
||||
assert_unauthorized(
|
||||
fail_login(tight_api, actor.username, address="198.51.100.32"),
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Нет заголовка — адрес соединения")
|
||||
def test_login_without_forwarded_header(tight_api: Api, stand: Stand) -> None:
|
||||
assert_tight_auth_stand()
|
||||
actor = tight_api.register()
|
||||
for _ in range(TIGHT_ACCOUNT_LIMIT):
|
||||
assert_unauthorized(
|
||||
fail_login(tight_api, actor.username, address=None),
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
assert_login_limited(
|
||||
fail_login(tight_api, actor.username, address=None),
|
||||
TIGHT_WINDOW_S,
|
||||
)
|
||||
assert_unauthorized(
|
||||
fail_login(tight_api, actor.username, address="198.51.100.41"),
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
events = {record.get("event") for record in api_records(stand, "tight")}
|
||||
assert "Client address header is missing" in events
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Valkey остановлен")
|
||||
def test_login_limit_without_valkey(api: Api, stand: Stand) -> None:
|
||||
address = "198.51.100.51"
|
||||
actor = api.register()
|
||||
other = unique_name()
|
||||
with outage(stand, "stop", "valkey"):
|
||||
assert_ok(
|
||||
api.login_response(
|
||||
actor.username,
|
||||
actor.password,
|
||||
forwarded_for=address,
|
||||
),
|
||||
201,
|
||||
"Session",
|
||||
)
|
||||
for _ in range(DEFAULT_ACCOUNT_LIMIT):
|
||||
assert_unauthorized(
|
||||
fail_login(api, other, address=address),
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
assert_login_limited(fail_login(api, other, address=address), 300)
|
||||
events = [record.get("event") for record in api_records(stand, "default")]
|
||||
assert "Login limiter uses process counters" in events
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Ключи счётчиков")
|
||||
def test_login_counter_keys(api: Api, stand: Stand) -> None:
|
||||
address = "198.51.100.61"
|
||||
username = unique_name()
|
||||
# после отказа Valkey в прошлом тесте API пропускает кэш ещё до 5 с и
|
||||
# считает в процессе: неудачи — пока счётчик пары не появится в Valkey
|
||||
deadline = time.monotonic() + CACHE_RETRY_AFTER_S + 2
|
||||
lines: list[str] = []
|
||||
while not lines and time.monotonic() < deadline:
|
||||
fail_login(api, username, address=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
|
||||
|
||||
|
||||
def _login_at_once(
|
||||
base_url: str,
|
||||
actors: Sequence[Actor],
|
||||
) -> list[httpx.Response]:
|
||||
def login(index: int) -> httpx.Response:
|
||||
with Api(base_url, timeout=UPLOADS_CLIENT_TIMEOUT_S) as client:
|
||||
actor = actors[index]
|
||||
return client.login_response(
|
||||
actor.username,
|
||||
actor.password,
|
||||
forwarded_for=f"198.51.100.{100 + index}",
|
||||
)
|
||||
|
||||
return at_once(len(actors), login)
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Бюджет входа занят")
|
||||
def test_kdf_budget_login(uploads_api: Api, stand: Stand) -> None:
|
||||
assert_uploads_auth_stand()
|
||||
actors = [uploads_api.register() for _ in range(KDF_CLIENTS)]
|
||||
answers = _login_at_once(str(uploads_api.client.base_url), actors)
|
||||
statuses = [resp.status_code for resp in answers]
|
||||
assert set(statuses) <= {201, 429}, statuses
|
||||
assert 429 in statuses, statuses
|
||||
for resp in answers:
|
||||
if resp.status_code == 429:
|
||||
assert_error(resp, 429)
|
||||
assert resp.headers["Retry-After"] == "1"
|
||||
else:
|
||||
token = assert_ok(resp, 201, "Session")["token"]
|
||||
me = uploads_api.request(
|
||||
"GET",
|
||||
ME,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert_ok(me, 200, "User")
|
||||
busy = [
|
||||
record
|
||||
for record in api_records(stand, "uploads")
|
||||
if record.get("event") == "Password hashing is busy"
|
||||
]
|
||||
assert any(record.get("operation") == "login" for record in busy)
|
||||
assert_records_clean(
|
||||
busy,
|
||||
[actor.username for actor in actors],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Бюджет регистрации занят")
|
||||
def test_kdf_budget_register(uploads_api: Api, stand: Stand) -> None:
|
||||
assert_uploads_auth_stand()
|
||||
base_url = str(uploads_api.client.base_url)
|
||||
names = [unique_name() for _ in range(KDF_CLIENTS)]
|
||||
|
||||
def register(index: int) -> httpx.Response:
|
||||
with Api(base_url, timeout=UPLOADS_CLIENT_TIMEOUT_S) as client:
|
||||
return client.request(
|
||||
"POST",
|
||||
f"{API}/users",
|
||||
json={
|
||||
"username": names[index],
|
||||
"display_name": "Budget",
|
||||
"password": f"pw-{uuid.uuid4().hex}",
|
||||
},
|
||||
)
|
||||
|
||||
answers = at_once(KDF_CLIENTS, register)
|
||||
statuses = [resp.status_code for resp in answers]
|
||||
assert set(statuses) <= {201, 429}, statuses
|
||||
assert 429 in statuses, statuses
|
||||
for name, resp in zip(names, answers, strict=True):
|
||||
if resp.status_code == 429:
|
||||
assert_error(resp, 429)
|
||||
assert resp.headers["Retry-After"] == "1"
|
||||
# строки не осталось: тот же username регистрируется
|
||||
uploads_api.register(username=name)
|
||||
busy = [
|
||||
record
|
||||
for record in api_records(stand, "uploads")
|
||||
if record.get("event") == "Password hashing is busy"
|
||||
]
|
||||
assert any(record.get("operation") == "register" for record in busy)
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Лёгкий запрос при занятом бюджете")
|
||||
def test_light_request_with_busy_budget(uploads_api: Api) -> None:
|
||||
assert_uploads_auth_stand()
|
||||
base_url = str(uploads_api.client.base_url)
|
||||
reader = uploads_api.register()
|
||||
actors = [uploads_api.register() for _ in range(KDF_CLIENTS)]
|
||||
stop = threading.Event()
|
||||
|
||||
def flood(index: int) -> None:
|
||||
with Api(base_url, timeout=UPLOADS_CLIENT_TIMEOUT_S) as client:
|
||||
actor = actors[index]
|
||||
while not stop.is_set():
|
||||
client.login_response(
|
||||
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):
|
||||
resp, took = timed(
|
||||
lambda: uploads_api.request("GET", ME, actor=reader),
|
||||
)
|
||||
assert_ok(resp, 200, "User")
|
||||
# лёгкий запрос не ждёт бюджет хэшей
|
||||
assert took < 1, f"GET /users/me took {took:.2f}s"
|
||||
finally:
|
||||
stop.set()
|
||||
for future in futures:
|
||||
future.result()
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "Старый хэш пересчитан при входе")
|
||||
def test_old_hash_rehashed_on_login(api: Api, stand: Stand) -> None:
|
||||
actor = api.register()
|
||||
stand(
|
||||
"set-password-hash",
|
||||
actor.username,
|
||||
stdin=actor.password.encode(),
|
||||
)
|
||||
assert stand("password-params", actor.username) == OLD_HASH_PARAMS
|
||||
assert_ok(
|
||||
api.login_response(actor.username, actor.password),
|
||||
201,
|
||||
"Session",
|
||||
)
|
||||
assert stand("password-params", actor.username) == CURRENT_HASH_PARAMS
|
||||
assert_ok(
|
||||
api.login_response(actor.username, actor.password),
|
||||
201,
|
||||
"Session",
|
||||
)
|
||||
rehashed = [
|
||||
record
|
||||
for record in api_records(stand, "default")
|
||||
if record.get("event") == "Rehashed password"
|
||||
and record.get("user_id") == actor.id
|
||||
]
|
||||
assert len(rehashed) == 1, rehashed
|
||||
record = rehashed[0]
|
||||
assert (record["previous_time_cost"], record["time_cost"]) == (3, 2)
|
||||
assert (record["previous_parallelism"], record["parallelism"]) == (4, 1)
|
||||
assert "$argon2id$" not in json.dumps(record)
|
||||
assert_records_clean(rehashed, [actor.username, actor.password])
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "Неудачный вход не пересчитывает")
|
||||
def test_failed_login_keeps_old_hash(api: Api, stand: Stand) -> None:
|
||||
actor = api.register()
|
||||
stand(
|
||||
"set-password-hash",
|
||||
actor.username,
|
||||
stdin=actor.password.encode(),
|
||||
)
|
||||
assert_unauthorized(
|
||||
fail_login(api, actor.username, address="198.51.100.71"),
|
||||
BASIC_CHALLENGE,
|
||||
)
|
||||
assert stand("password-params", actor.username) == OLD_HASH_PARAMS
|
||||
|
||||
Reference in New Issue
Block a user