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:
@@ -37,6 +37,21 @@ CA_FILE = os.environ.get("CA_FILE", str(STAND_CA_FILE))
|
||||
TLS_CLIENT_CERT = os.environ.get("TLS_CLIENT_CERT", "")
|
||||
TLS_CLIENT_KEY = os.environ.get("TLS_CLIENT_KEY", "")
|
||||
TLS_SERVER_NAME = os.environ.get("TLS_SERVER_NAME", "")
|
||||
# клиент в роли LB передаёт адрес клиента, как HAProxy (change
|
||||
# auth-hardening, design, решение 10): постоянный адрес из TEST-NET-1, тест
|
||||
# может задать свой (`forwarded_for=`) или убрать заголовок (`None`)
|
||||
FORWARDED_FOR = "X-Forwarded-For"
|
||||
LB_CLIENT_ADDRESS = "192.0.2.1"
|
||||
|
||||
|
||||
class _LbAddress:
|
||||
"""Маркер `Api.request`: адрес клиента в роли LB по умолчанию."""
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "LB_ADDRESS"
|
||||
|
||||
|
||||
LB_ADDRESS = _LbAddress()
|
||||
|
||||
|
||||
class TlsSettingsError(ValueError):
|
||||
@@ -201,10 +216,22 @@ class Api:
|
||||
*,
|
||||
actor: Actor | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
forwarded_for: str | None | _LbAddress = LB_ADDRESS,
|
||||
**kwargs: Any,
|
||||
) -> httpx.Response:
|
||||
merged = actor.headers() if actor is not None else {}
|
||||
merged.update(headers or {})
|
||||
# в роли LB (стенд отказов) — X-Forwarded-For, как у HAProxy; через
|
||||
# настоящий LB заголовок клиента перезаписывается
|
||||
if TLS_CLIENT_CERT and forwarded_for is not None:
|
||||
merged.setdefault(
|
||||
FORWARDED_FOR,
|
||||
LB_CLIENT_ADDRESS
|
||||
if isinstance(forwarded_for, _LbAddress)
|
||||
else forwarded_for,
|
||||
)
|
||||
elif isinstance(forwarded_for, str):
|
||||
merged[FORWARDED_FOR] = forwarded_for
|
||||
return self.client.request(
|
||||
method,
|
||||
path,
|
||||
@@ -234,11 +261,39 @@ class Api:
|
||||
user = assert_ok(resp, 201, "User")
|
||||
return self.login(user, password)
|
||||
|
||||
def login_response(self, username: str, password: str) -> httpx.Response:
|
||||
def login_response(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
*,
|
||||
forwarded_for: str | None | _LbAddress = LB_ADDRESS,
|
||||
) -> httpx.Response:
|
||||
return self.request(
|
||||
"POST",
|
||||
SESSIONS,
|
||||
headers=basic_auth(username, password),
|
||||
forwarded_for=forwarded_for,
|
||||
)
|
||||
|
||||
def login_raw(
|
||||
self,
|
||||
authorization: str | None,
|
||||
*,
|
||||
headers: dict[str, str] | None = None,
|
||||
forwarded_for: str | None | _LbAddress = LB_ADDRESS,
|
||||
**kwargs: Any,
|
||||
) -> httpx.Response:
|
||||
"""Вход с произвольным `Authorization` (битый Basic) и заголовками;
|
||||
`kwargs` — тело (`content=`) и прочее httpx."""
|
||||
merged = dict(headers or {})
|
||||
if authorization is not None:
|
||||
merged["Authorization"] = authorization
|
||||
return self.request(
|
||||
"POST",
|
||||
SESSIONS,
|
||||
headers=merged,
|
||||
forwarded_for=forwarded_for,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def login(self, user: dict[str, Any], password: str) -> Actor:
|
||||
|
||||
@@ -142,10 +142,15 @@ def assert_accepted(resp: httpx.Response) -> dict[str, Any]:
|
||||
return attachment
|
||||
|
||||
|
||||
def assert_error(resp: httpx.Response, status: int) -> dict[str, Any]:
|
||||
def assert_error(
|
||||
resp: httpx.Response,
|
||||
status: int,
|
||||
*,
|
||||
instance_id: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Ошибка в формате контракта; `code` соответствует статусу."""
|
||||
assert resp.status_code == status, describe(resp, f"expected {status}")
|
||||
body = json_body(resp)
|
||||
body = json_body(resp, instance_id=instance_id)
|
||||
check_body(body, "Error")
|
||||
error = body["error"]
|
||||
assert error["code"] == ERROR_CODES[status], describe(
|
||||
@@ -314,11 +319,16 @@ def assert_replicas(values: Iterable[str], expected: int) -> set[str]:
|
||||
return seen
|
||||
|
||||
|
||||
def json_body(resp: httpx.Response) -> Any:
|
||||
"""JSON-тело в UTF-8, непустые `X-Request-Id` и `X-Instance-Id`."""
|
||||
def json_body(resp: httpx.Response, *, instance_id: bool = True) -> Any:
|
||||
"""JSON-тело в UTF-8, непустые `X-Request-Id` и `X-Instance-Id`.
|
||||
|
||||
`instance_id=False` — ответ мог построить сам LB (предел тела, change
|
||||
auth-hardening): у его ответов `X-Instance-Id` нет, контракт допускает.
|
||||
"""
|
||||
request_id = resp.headers.get("X-Request-Id", "")
|
||||
assert request_id.strip(), describe(resp, "no X-Request-Id")
|
||||
assert_instance_id(resp)
|
||||
if instance_id:
|
||||
assert_instance_id(resp)
|
||||
media_type, _, params = resp.headers.get("Content-Type", "").partition(
|
||||
";",
|
||||
)
|
||||
|
||||
@@ -57,6 +57,17 @@
|
||||
сообщение уже подтвердил
|
||||
stop|start|kill|pause|unpause relay
|
||||
relay стенда; start — docker start контейнера
|
||||
login-keys ключи счётчиков предела входа базы стенда в
|
||||
Valkey: `<ключ> <значение> <ttl>` (change
|
||||
auth-hardening)
|
||||
set-password-hash <username>
|
||||
хэш прежних параметров Argon2id (t=3, 64 MiB,
|
||||
p=4) пользователю; пароль — stdin, хэш считает
|
||||
Python образа API
|
||||
password-params <username> префикс строки хэша до соли
|
||||
(`$argon2id$v=19$m=…,t=…,p=…`)
|
||||
api-log default|tight|uploads
|
||||
журнал API стенда этой роли
|
||||
freeze worker docker kill -s STOP: контейнер остаётся running
|
||||
(не paused), поэтому его можно убить посреди
|
||||
COMMIT
|
||||
@@ -701,6 +712,31 @@ client = botocore.session.get_session().create_client(
|
||||
body = sys.stdin.buffer.read()
|
||||
client.put_object(Bucket=s3.bucket, Key=sys.argv[1], Body=body)
|
||||
"""
|
||||
# хэш пароля прежних параметров (RFC 9106 low-memory: t=3, 64 MiB, p=4) —
|
||||
# argon2-cffi образа API; пароль — stdin, хэш — stdout (change
|
||||
# auth-hardening, design, решение 10)
|
||||
OLD_PASSWORD_HASH_PY = """\
|
||||
import sys
|
||||
from argon2 import PasswordHasher, profiles
|
||||
password = sys.stdin.read()
|
||||
print(PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY).hash(password))
|
||||
"""
|
||||
SET_PASSWORD_HASH_SQL = """\
|
||||
UPDATE users SET password_hash = :'title' WHERE username = :'mode'
|
||||
RETURNING 'updated';
|
||||
"""
|
||||
# параметры строки хэша — префикс до соли: $argon2id$v=19$m=…,t=…,p=…
|
||||
PASSWORD_PARAMS_SQL = """\
|
||||
SELECT array_to_string((string_to_array(password_hash, '$'))[1:4], '$')
|
||||
FROM users WHERE username = :'mode';
|
||||
"""
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
# журнал API стенда по роли (имена задаёт run_failures.py)
|
||||
API_LOG_SUFFIXES = {
|
||||
"default": "-api",
|
||||
"tight": "-api-tight",
|
||||
"uploads": "-api-uploads",
|
||||
}
|
||||
# SHA-256 объекта тем же способом; нет объекта — пустой вывод
|
||||
OBJECT_SHA256_PY = """\
|
||||
import hashlib
|
||||
@@ -1682,6 +1718,59 @@ def api_container(project: str) -> str:
|
||||
return f"{project}-api"
|
||||
|
||||
|
||||
def login_keys(project: str) -> str:
|
||||
"""Ключи и значения счётчиков предела входа базы стенда в Valkey:
|
||||
`<ключ> <значение> <ttl>` построчно (тест ищет в них username и
|
||||
адрес — их там быть не должно)."""
|
||||
_, database = storage_names()
|
||||
keys = valkey(
|
||||
project,
|
||||
"--scan",
|
||||
"--pattern",
|
||||
f"{database}:login:*",
|
||||
).split()
|
||||
lines = []
|
||||
for key in keys:
|
||||
value = valkey(project, "get", key)
|
||||
ttl = valkey(project, "ttl", key)
|
||||
lines.append(f"{key} {value} {ttl}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def set_password_hash(project: str, username: str) -> str:
|
||||
"""Записать пользователю хэш прежних параметров: пароль — stdin hook,
|
||||
хэш считает Python образа API, в argv пароля нет."""
|
||||
if not USERNAME_RE.fullmatch(username):
|
||||
raise HookError(f"not a username: {username!r}")
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
"-i",
|
||||
api_container(project),
|
||||
"python",
|
||||
"-c",
|
||||
OLD_PASSWORD_HASH_PY,
|
||||
],
|
||||
input=sys.stdin.buffer.read(),
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
sys.stderr.write(result.stderr.decode(errors="replace"))
|
||||
raise SystemExit(result.returncode)
|
||||
password_hash = result.stdout.decode().strip()
|
||||
updated = psql(
|
||||
project,
|
||||
SET_PASSWORD_HASH_SQL,
|
||||
title=password_hash,
|
||||
mode=username,
|
||||
)
|
||||
if updated != "updated":
|
||||
raise HookError(f"no user {username!r}")
|
||||
return ""
|
||||
|
||||
|
||||
def start_api(project: str) -> str:
|
||||
"""Тот же контейнер API; готов — `healthy` по healthcheck образа."""
|
||||
name = api_container(project)
|
||||
@@ -1899,6 +1988,18 @@ def run(project: str, action: str, args: list[str]) -> str:
|
||||
return reconcile(project, args[0], args[1:])
|
||||
if action == "run-cleaner" and len(args) == 1:
|
||||
return run_cleaner(project, args[0])
|
||||
if action == "login-keys" and not args:
|
||||
return login_keys(project)
|
||||
if action == "api-log" and len(args) == 1:
|
||||
if args[0] not in API_LOG_SUFFIXES:
|
||||
raise HookError(f"api-log: one of {sorted(API_LOG_SUFFIXES)}")
|
||||
return docker("logs", f"{project}{API_LOG_SUFFIXES[args[0]]}")
|
||||
if action == "set-password-hash" and len(args) == 1:
|
||||
return set_password_hash(project, args[0])
|
||||
if action == "password-params" and len(args) == 1:
|
||||
if not USERNAME_RE.fullmatch(args[0]):
|
||||
raise HookError(f"not a username: {args[0]!r}")
|
||||
return psql(project, PASSWORD_PARAMS_SQL, mode=args[0])
|
||||
raise HookError(f"unknown action or arguments: {action} {args}")
|
||||
|
||||
|
||||
|
||||
@@ -122,6 +122,12 @@ UPLOADS_ENV = {
|
||||
"UPLOADS__MAX_WAITING": "1",
|
||||
"UPLOADS__WAIT_TIMEOUT_SECONDS": "1",
|
||||
"UPLOADS__BODY_TIMEOUT_SECONDS": "3",
|
||||
# малый бюджет хэшей пароля (change auth-hardening, design, решение 10):
|
||||
# одно место, один ждущий, ожидание 0,5 с — «Бюджет входа занят»,
|
||||
# «Бюджет регистрации занят», «Лёгкий запрос при занятом бюджете»
|
||||
"AUTH__KDF_CONCURRENCY": "1",
|
||||
"AUTH__KDF_MAX_WAITING": "1",
|
||||
"AUTH__KDF_WAIT_TIMEOUT_SECONDS": "0.5",
|
||||
}
|
||||
# API «с коротким сроком S3» (change fix-upload-put-flake, design, решение
|
||||
# 3): срок вызова S3 1 с, и простой дольше срока в test_upload_after_idle_s3
|
||||
@@ -589,6 +595,7 @@ def run_stand(
|
||||
"FAULT_HOOK": str(FAULT_HOOK),
|
||||
"FAULT_PROJECT": project,
|
||||
"FAULT_LIMITS_ENV": env_pairs(LIMITS_ENV),
|
||||
"FAULT_TIGHT_ENV": env_pairs(TIGHT_ENV),
|
||||
"FAULT_UPLOADS_ENV": env_pairs(UPLOADS_ENV),
|
||||
"FAULT_S3_ENV": env_pairs(S3_ENV),
|
||||
"FAULT_BACKLOG_ENV": env_pairs(BACKLOG_ENV),
|
||||
|
||||
@@ -33,6 +33,9 @@ CAPABILITIES = (
|
||||
"message-broker",
|
||||
# с change track1-queue-overload
|
||||
"queue-overload",
|
||||
# с лабы 7 (change auth-hardening, design, решение 10): до archive файла
|
||||
# спека нет — сценарии пусты, маркеры — «unknown scenario»
|
||||
"login-protection",
|
||||
)
|
||||
SCENARIO_RE = re.compile(r"^#### Scenario: (.+?)\s*$", re.MULTILINE)
|
||||
|
||||
@@ -157,6 +160,13 @@ EXCLUDED: dict[Scenario, Exclusion] = {
|
||||
"разные хэши одинаковых паролей, пароля нет в pg_dump базы — "
|
||||
"evidence/auth/passwords-and-tokens.md",
|
||||
),
|
||||
("users", "Замер на стенде"): Exclusion(
|
||||
reason="замер времени и памяти хэша в образе API под лимитами "
|
||||
"реплики, а не поведение по HTTP (change auth-hardening, решение 1)",
|
||||
check="driver.py argon2-params: методика, сетка, правило выбора и "
|
||||
"строка «Выбрано» (её сверяет test_settings.py с умолчаниями) — "
|
||||
"evidence/auth/argon2-params.md",
|
||||
),
|
||||
("message-broker", "Сервис брокера запущен"): Exclusion(
|
||||
reason="образ, volume и порты контейнера видны только в Docker",
|
||||
check="driver.py --port <LB> broker-check: образ с тегом и digest, "
|
||||
@@ -234,8 +244,12 @@ COLLECTED = pytest.StashKey[Collected]()
|
||||
|
||||
|
||||
def spec_scenarios(capability: str, specs_dir: Path = SPECS_DIR) -> list[str]:
|
||||
text = (specs_dir / capability / "spec.md").read_text(encoding="utf-8")
|
||||
return SCENARIO_RE.findall(text)
|
||||
"""Сценарии основного спека; новой capability до archive change спека
|
||||
ещё нет — пустой список, а не падение сверки."""
|
||||
path = specs_dir / capability / "spec.md"
|
||||
if not path.is_file():
|
||||
return []
|
||||
return SCENARIO_RE.findall(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def all_scenarios(
|
||||
|
||||
@@ -481,3 +481,109 @@ def test_attachment_ids_in_upper_case(
|
||||
assert_content(api.attachment_content(alice, upper), data, "image/png")
|
||||
message = api.send_message(alice, chat["id"], "x", attachment_ids=[upper])
|
||||
assert message["attachment_ids"] == [attachment["id"]]
|
||||
|
||||
|
||||
# предел размера тела запроса (change auth-hardening, design, решение 8):
|
||||
# 64 KiB вне загрузки вложения, отказ — 400 invalid_request
|
||||
BODY_MAX_BYTES = 65536
|
||||
|
||||
|
||||
def _chunks(total: int, size: int = 8192):
|
||||
"""Тело частями без Content-Length (httpx шлёт chunked)."""
|
||||
sent = 0
|
||||
while sent < total:
|
||||
part = min(size, total - sent)
|
||||
sent += part
|
||||
yield b" " * part
|
||||
|
||||
|
||||
@pytest.mark.spec("api-conventions", "Объявленное тело больше предела")
|
||||
def test_declared_body_over_limit(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
body = b'{"text": "x"' + b" " * (BODY_MAX_BYTES + 1 - 13) + b"}"
|
||||
assert len(body) == BODY_MAX_BYTES + 1
|
||||
headers = {"Content-Type": "application/json"}
|
||||
with_auth = api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
content=body,
|
||||
headers=headers,
|
||||
)
|
||||
without_auth = api.post_message(
|
||||
None,
|
||||
chat["id"],
|
||||
content=body,
|
||||
headers=headers,
|
||||
)
|
||||
# через LB отказывает LB: X-Instance-Id у его ответа нет
|
||||
for resp in (with_auth, without_auth):
|
||||
error = assert_error(resp, 400, instance_id=False)
|
||||
assert error["message"] == "Request body is too large"
|
||||
assert api.all_messages(alice, chat["id"]) == []
|
||||
|
||||
|
||||
@pytest.mark.spec("api-conventions", "Тело частями больше предела")
|
||||
def test_chunked_body_over_limit(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
resp = api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
content=_chunks(BODY_MAX_BYTES + 8192),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
# Content-Length нет — LB тело не меряет, отказывает реплика
|
||||
error = assert_error(resp, 400)
|
||||
assert error["message"] == "Request body is too large"
|
||||
assert_instance_id(resp)
|
||||
assert api.all_messages(alice, chat["id"]) == []
|
||||
|
||||
|
||||
@pytest.mark.spec("api-conventions", "Наибольшее валидное тело принимается")
|
||||
def test_largest_valid_body_accepted(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
attachment_ids = [
|
||||
api.upload(alice, chat["id"], images.sample_png())["id"]
|
||||
for _ in range(10)
|
||||
]
|
||||
# 4000 символов вне BMP, каждый — экранированная суррогатная пара
|
||||
text = "\\ud83d\\ude00" * 4000
|
||||
body = (
|
||||
'{"text": "'
|
||||
+ text
|
||||
+ '", "attachment_ids": '
|
||||
+ json.dumps(attachment_ids)
|
||||
+ "}"
|
||||
).encode("ascii")
|
||||
assert 48000 < len(body) < BODY_MAX_BYTES
|
||||
resp = api.post_message(
|
||||
alice,
|
||||
chat["id"],
|
||||
content=body,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
message = assert_ok(resp, 201, "Message")
|
||||
assert message["text"] == "\U0001f600" * 4000
|
||||
assert message["attachment_ids"] == attachment_ids
|
||||
|
||||
|
||||
@pytest.mark.spec(
|
||||
"api-conventions",
|
||||
"Загрузка вложения не ограничена пределом JSON",
|
||||
)
|
||||
def test_upload_not_limited_by_json_limit(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
data = images.png_noise(seed=7)
|
||||
assert len(data) > BODY_MAX_BYTES
|
||||
api.upload(alice, chat["id"], data)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Спек `login-protection` через публичную точку входа (change
|
||||
`auth-hardening`, design, решения 3, 6, 10): предел пары, общий для реплик,
|
||||
неизвестный username, сброс успехом, подмена `X-Forwarded-For`, тела отказов.
|
||||
|
||||
Предел адреса, окно, отказ Valkey и бюджет хэшей — на стенде отказов
|
||||
(`test_failures.py`): адрес клиента набора здесь один на все тесты и прогоны.
|
||||
Неудачных входов за прогон набора — 63: 58 у этого модуля (по 10 у пары в
|
||||
трёх тестах, 10 у неизвестного username, 18 у сброса успехом) и 5 у прочих
|
||||
модулей (неверный пароль, неизвестный пользователь). Счётчик адреса после двух
|
||||
прогонов подряд в одном окне (300 с) — 125 при пределе 200 (замер на стенде,
|
||||
2026-11-17), 429 вне тестов предела нет; параллельный `make test` неудачных
|
||||
входов не делает. Каждый тест — свои username.
|
||||
"""
|
||||
|
||||
import base64
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api_client import Actor, Api, unique_password, unique_username
|
||||
from conftest import EXPECT_REPLICAS
|
||||
from contract import (
|
||||
BASIC_CHALLENGE,
|
||||
assert_error,
|
||||
assert_instance_id,
|
||||
assert_ok,
|
||||
assert_replicas,
|
||||
assert_unauthorized,
|
||||
)
|
||||
|
||||
# пределы по умолчанию (спек `service-configuration`, «Параметры пароля и
|
||||
# входа»): окно 300 с, пара — 10
|
||||
LOGIN_WINDOW_S = 300
|
||||
ACCOUNT_LIMIT = 10
|
||||
|
||||
|
||||
def _fail(api: Api, username: str, **kwargs: object) -> httpx.Response:
|
||||
return api.login_response(username, unique_password(), **kwargs)
|
||||
|
||||
|
||||
def _assert_limited(resp: httpx.Response) -> dict:
|
||||
error = assert_error(resp, 429)
|
||||
retry_after = int(resp.headers["Retry-After"])
|
||||
assert 1 <= retry_after <= LOGIN_WINDOW_S, resp.headers["Retry-After"]
|
||||
return error
|
||||
|
||||
|
||||
def _assert_no_credentials(
|
||||
resp: httpx.Response,
|
||||
username: str,
|
||||
password: str,
|
||||
) -> None:
|
||||
authorization = base64.b64encode(
|
||||
f"{username}:{password}".encode(),
|
||||
).decode("ascii")
|
||||
seen = [resp.text, *(f"{k}: {v}" for k, v in resp.headers.items())]
|
||||
for secret in (username, password, authorization):
|
||||
for item in seen:
|
||||
assert secret not in item, f"credentials leaked into {item[:80]!r}"
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Предел пары")
|
||||
@pytest.mark.spec("login-protection", "Верный пароль во время блокировки")
|
||||
@pytest.mark.spec("login-protection", "Неизвестный username считается так же")
|
||||
@pytest.mark.spec("login-protection", "Другой пользователь с того же адреса")
|
||||
@pytest.mark.spec("login-protection", "Битый Basic во время блокировки")
|
||||
@pytest.mark.spec("login-protection", "Тела отказов")
|
||||
def test_account_limit(api: Api, alice: Actor, bob: Actor) -> None:
|
||||
password = unique_password()
|
||||
for _ in range(ACCOUNT_LIMIT):
|
||||
resp = api.login_response(alice.username, password)
|
||||
assert_unauthorized(resp, BASIC_CHALLENGE)
|
||||
_assert_no_credentials(resp, alice.username, password)
|
||||
limited = api.login_response(alice.username, password)
|
||||
error = _assert_limited(limited)
|
||||
_assert_no_credentials(limited, alice.username, password)
|
||||
|
||||
# верный пароль во время блокировки — тоже 429, сессии нет
|
||||
correct = api.login_response(alice.username, alice.password)
|
||||
_assert_limited(correct)
|
||||
assert "token" not in correct.text
|
||||
|
||||
# битый Basic — 401 разбора раньше предела
|
||||
broken = api.login_raw("Basic !!!")
|
||||
assert_unauthorized(broken, BASIC_CHALLENGE)
|
||||
|
||||
# другой пользователь с того же адреса входит
|
||||
assert_ok(api.login_response(bob.username, bob.password), 201, "Session")
|
||||
|
||||
# неизвестный username: тот же счёт и тот же отказ
|
||||
unknown = unique_username()
|
||||
for _ in range(ACCOUNT_LIMIT):
|
||||
assert_unauthorized(_fail(api, unknown), BASIC_CHALLENGE)
|
||||
unknown_limited = _fail(api, unknown)
|
||||
unknown_error = _assert_limited(unknown_limited)
|
||||
assert unknown_error["code"] == error["code"]
|
||||
assert unknown_error["message"] == error["message"]
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Предел общий для реплик")
|
||||
def test_limit_shared_by_replicas(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
replicas: int, # noqa: ARG001
|
||||
) -> None:
|
||||
instances = []
|
||||
for _ in range(ACCOUNT_LIMIT):
|
||||
resp = _fail(api, alice.username)
|
||||
assert_unauthorized(resp, BASIC_CHALLENGE)
|
||||
instances.append(assert_instance_id(resp))
|
||||
# неудачи пары обслуживали разные реплики
|
||||
assert_replicas(instances, EXPECT_REPLICAS)
|
||||
for _ in range(2):
|
||||
_assert_limited(_fail(api, alice.username))
|
||||
|
||||
|
||||
@pytest.mark.spec("login-protection", "Успешный вход сбрасывает счёт пары")
|
||||
def test_success_resets_account(api: Api, alice: Actor) -> None:
|
||||
for _ in range(ACCOUNT_LIMIT - 1):
|
||||
assert_unauthorized(_fail(api, alice.username), BASIC_CHALLENGE)
|
||||
assert_ok(
|
||||
api.login_response(alice.username, alice.password),
|
||||
201,
|
||||
"Session",
|
||||
)
|
||||
for _ in range(ACCOUNT_LIMIT - 1):
|
||||
assert_unauthorized(_fail(api, alice.username), BASIC_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.spec(
|
||||
"login-protection",
|
||||
"Подмена X-Forwarded-For не обходит предел",
|
||||
)
|
||||
def test_forwarded_header_spoofing(api: Api, alice: Actor) -> None:
|
||||
"""Через LB значение клиента перезаписывается; без LB (консоль) реплика
|
||||
заголовок не учитывает — в обоих случаях счёт один."""
|
||||
for index in range(ACCOUNT_LIMIT):
|
||||
resp = _fail(api, alice.username, forwarded_for=f"203.0.113.{index}")
|
||||
assert_unauthorized(resp, BASIC_CHALLENGE)
|
||||
_assert_limited(_fail(api, alice.username, forwarded_for="203.0.113.99"))
|
||||
@@ -21,6 +21,7 @@ from api_client import (
|
||||
from contract import (
|
||||
BASIC_CHALLENGE,
|
||||
BEARER_CHALLENGE,
|
||||
assert_error,
|
||||
assert_ok,
|
||||
assert_unauthorized,
|
||||
)
|
||||
@@ -117,6 +118,28 @@ def test_broken_basic(api: Api, alice: Actor) -> None:
|
||||
assert_unauthorized(resp, BASIC_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "Большое тело входа")
|
||||
def test_login_large_body(api: Api, alice: Actor) -> None:
|
||||
"""Предел размера тела (change auth-hardening, решение 8): верный Basic с
|
||||
телом больше 64 KiB — 400 до проверки credentials; через LB отказывает
|
||||
LB (без X-Instance-Id)."""
|
||||
headers = {
|
||||
"Authorization": basic_header(
|
||||
f"{alice.username}:{alice.password}".encode(),
|
||||
)["Authorization"],
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
resp = api.request(
|
||||
"POST",
|
||||
SESSIONS,
|
||||
headers=headers,
|
||||
content=b" " * 65537,
|
||||
)
|
||||
error = assert_error(resp, 400, instance_id=False)
|
||||
assert error["message"] == "Request body is too large"
|
||||
assert "token" not in resp.text
|
||||
|
||||
|
||||
@pytest.mark.spec("sessions", "Повторный выход")
|
||||
def test_logout_twice(api: Api, alice: Actor) -> None:
|
||||
assert api.logout(alice).status_code == 204
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Проверки транспорта лабы 7 (спек `student-tests`, «Проверки входа и
|
||||
транспорта лабы 7»; сценарий «Недоверенный TLS» — вне сверки покрытия, в
|
||||
докстринге): публичная точка входа отвергается проверкой сертификата при
|
||||
чужом CA (системное хранилище вместо CA стенда) и при имени хоста не из SAN
|
||||
(`127.0.0.1` вместо `localhost`) — именно ошибкой проверки, а не отказом
|
||||
соединения.
|
||||
"""
|
||||
|
||||
import ssl
|
||||
import urllib.parse
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from api_client import tls_context
|
||||
from conftest import BASE_URL
|
||||
|
||||
HEALTH = "/health/live"
|
||||
|
||||
|
||||
def _verify_error(url: str, context: ssl.SSLContext) -> str:
|
||||
with pytest.raises(httpx.ConnectError) as caught:
|
||||
httpx.get(url, verify=context, timeout=5)
|
||||
cause = caught.value.__context__ or caught.value.__cause__
|
||||
text = f"{caught.value} {cause!r}"
|
||||
assert "CERTIFICATE_VERIFY_FAILED" in text, text
|
||||
return text
|
||||
|
||||
|
||||
def test_untrusted_tls() -> None:
|
||||
"""Сценарий «Недоверенный TLS» (`student-tests`)."""
|
||||
parts = urllib.parse.urlsplit(BASE_URL)
|
||||
if parts.hostname != "localhost":
|
||||
pytest.skip(f"BASE_URL host {parts.hostname!r} is not localhost")
|
||||
# системное хранилище: CA стенда в нём нет
|
||||
unknown_issuer = _verify_error(
|
||||
BASE_URL + HEALTH,
|
||||
ssl.create_default_context(),
|
||||
)
|
||||
assert "unable to get local issuer" in unknown_issuer.lower() or (
|
||||
"self-signed" in unknown_issuer.lower()
|
||||
), unknown_issuer
|
||||
# CA стенда, но имя не из SAN
|
||||
by_ip = parts._replace(netloc=f"127.0.0.1:{parts.port}").geturl()
|
||||
mismatch = _verify_error(by_ip + HEALTH, tls_context())
|
||||
assert "mismatch" in mismatch.lower(), mismatch
|
||||
# с CA стенда и localhost — работает: отказ выше не от недоступности
|
||||
assert (
|
||||
httpx.get(BASE_URL + HEALTH, verify=tls_context()).status_code == 200
|
||||
)
|
||||
Reference in New Issue
Block a user