feat: import lab 7 security implementation

This commit is contained in:
2026-12-02 23:44:32 +03:00
parent 20afc2c790
commit ee28cd7dbd
259 changed files with 84919 additions and 35 deletions
+113
View File
@@ -0,0 +1,113 @@
"""X-Request-Id и X-Instance-Id: поведение слоя, общее для любых его реализаций.
Эти тесты фиксируют то, что видит клиент, и не зависят от того, как
написан middleware (в лабе 1 его переписали на чистое ASGI, трек «5»).
Ответ 401 формирует AuthenticationMiddleware, а не роутер: id из
входящего заголовка должен дойти и до него. С лабы 3 у каждого ответа
API есть ещё непустой X-Instance-Id — на успехе, ошибке, health, 404
неизвестного пути и 405 (500 по HTTP не вызвать: заголовок ему ставит
`handlers.error_response`).
С лабы 7 X-Instance-Id — случайный alias процесса (16 hex-символов): ни
hostname, ни ID контейнера, ни IP контракт раскрывать не разрешает
(`contracts/README.md`).
"""
import re
import httpx
import pytest
from helpers import ME, USERS, assert_error, instance_id
GENERATED_ID = re.compile(r"[0-9a-f]{32}")
# лаба 7: alias процесса — secrets.token_hex(8) (src/early_stop.py)
INSTANCE_ALIAS = re.compile(r"[0-9a-f]{16}")
@pytest.mark.parametrize(
("path", "status", "code"),
[
("/health/live", 200, None),
(f"{USERS}/me", 401, "unauthorized"),
("/no-such-path", 404, "not_found"),
],
ids=["ok", "unauthorized", "unknown-path"],
)
def test_safe_incoming_request_id_is_echoed(
client: httpx.Client,
path: str,
status: int,
code: str | None,
) -> None:
response = client.get(path, headers={"X-Request-Id": "trace-42.a_b"})
assert response.status_code == status
assert response.headers["X-Request-Id"] == "trace-42.a_b"
if code is not None:
# тот же id и в теле ошибки: assert_error сверяет его с заголовком
assert_error(response, status, code)
@pytest.mark.parametrize(
"incoming",
["bad id", "x" * 65, "<script>"],
ids=["space", "too-long", "markup"],
)
def test_unsafe_incoming_request_id_is_replaced(
client: httpx.Client,
incoming: str,
) -> None:
response = client.get("/health/live", headers={"X-Request-Id": incoming})
assert response.status_code == 200
assert GENERATED_ID.fullmatch(response.headers["X-Request-Id"])
def test_generated_request_ids_are_unique(client: httpx.Client) -> None:
ids = {client.get("/health/live").headers["X-Request-Id"] for _ in range(20)}
assert len(ids) == 20
assert all(GENERATED_ID.fullmatch(request_id) for request_id in ids)
@pytest.mark.parametrize(
("method", "path", "status"),
[
("GET", "/health/live", 200),
("GET", "/health/ready", 200),
("POST", USERS, 400),
("GET", ME, 401),
("GET", "/no-such-path", 404),
# вне /api/v1: под ним без токена раньше 405 отвечает 401
("DELETE", "/health/live", 405),
],
ids=["live", "ready", "bad-request", "unauthorized", "unknown-path", "method"],
)
def test_instance_id_on_every_response(
client: httpx.Client,
method: str,
path: str,
status: int,
) -> None:
response = client.request(method, path, json={} if method == "POST" else None)
assert response.status_code == status, response.text
assert instance_id(response)
def test_instance_id_is_random_alias(client: httpx.Client) -> None:
"""Лаба 7: X-Instance-Id — alias процесса, а не hostname (в compose это
начало ID контейнера, 12 hex-символов) и не IP: на успехе, ошибке и
health."""
seen = set()
for method, path in (
("GET", "/health/live"),
("GET", "/health/ready"),
("GET", ME),
("GET", "/no-such-path"),
("POST", USERS),
):
response = client.request(method, path, json={} if method == "POST" else None)
value = instance_id(response)
assert INSTANCE_ALIAS.fullmatch(value), (
f"{method} {path}: X-Instance-Id {value!r} is not a 16-hex alias"
)
seen.add(value)
assert seen