Files
mtusi2026lab7/student-tests/unit/test_tls.py
T

570 lines
21 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: TLS сервера API, allowlist identity, alias процесса, слушатель health.
Без стенда. Рукопожатия — настоящие: uvicorn с `src.tls` на loopback в
потоке, сертификаты выпускает `infra/pki/pki.sh` во временный каталог (без
OpenSSL ≥ 3 эти тесты пропускаются с причиной). Клиент — `ssl` stdlib, как
у HAProxy: проверка сервера по CA стенда и имени `api`.
"""
import asyncio
import os
import re
import signal
import socket
import ssl
import subprocess
import threading
import time
from pathlib import Path
import pytest
import uvicorn
from src import early_stop
from src import health_listener as listener_module
from src.config import ConfigError, Settings, Tls
from src.health_listener import HealthListener
from src.tls import (
allowlist_protocol,
client_identities,
context_factory,
is_allowed,
server_context,
tls_problems,
)
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[2]
PKI = ROOT / "infra" / "pki" / "pki.sh"
ALIAS = re.compile(r"[0-9a-f]{16}")
REQUEST = b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n"
# исходы «HTTP-ответа нет»
NO_HTTP = ("tls_error", "closed")
# --- настройки и alias -------------------------------------------------------
def test_instance_id_defaults_to_random_alias() -> None:
first = Settings.from_env({}).instance_id
second = Settings.from_env({}).instance_id
assert ALIAS.fullmatch(first)
assert first != second
def test_explicit_instance_id_and_bad_one() -> None:
assert Settings.from_env({"APP_INSTANCE_ID": "api-a"}).instance_id == "api-a"
with pytest.raises(ConfigError, match="APP_INSTANCE_ID"):
Settings.from_env({"APP_INSTANCE_ID": "api a"})
def test_health_port_must_differ_from_app_port() -> None:
assert Settings.from_env({}).health_port == 8081
assert Settings.from_env({"APP_HEALTH_PORT": "0"}).health_port == 0
with pytest.raises(ConfigError, match="APP_HEALTH_PORT"):
Settings.from_env({"APP_PORT": "8081"})
def test_tls_settings_parse() -> None:
tls = Settings.from_env({}).tls
assert tls.client_auth is True
assert tls.allowed_clients == ("haproxy",)
tls = Tls.from_env(
{"TLS_CLIENT_AUTH": "false", "TLS_ALLOWED_CLIENTS": "haproxy, mtls-probe"}
)
assert tls.client_auth is False
assert tls.allowed_clients == ("haproxy", "mtls-probe")
with pytest.raises(ConfigError, match="TLS_ALLOWED_CLIENTS"):
Tls.from_env({"TLS_ALLOWED_CLIENTS": "haproxy,Bad Name"})
with pytest.raises(ConfigError, match="TLS_CLIENT_AUTH"):
Tls.from_env({"TLS_CLIENT_AUTH": "yes"})
def test_early_stop_puts_one_alias_into_environment(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("APP_INSTANCE_ID", raising=False)
handlers = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT)}
try:
early_stop.install()
alias = os.environ["APP_INSTANCE_ID"]
early_stop.install()
assert os.environ["APP_INSTANCE_ID"] == alias
finally:
early_stop.disarm()
for signum, handler in handlers.items():
signal.signal(signum, handler)
assert ALIAS.fullmatch(alias)
assert alias in early_stop._line(signal.SIGTERM).decode()
assert Settings.from_env(os.environ).instance_id == alias
def test_explicit_instance_id_survives_early_stop(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("APP_INSTANCE_ID", "api-a")
handlers = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT)}
try:
early_stop.install()
finally:
early_stop.disarm()
for signum, handler in handlers.items():
signal.signal(signum, handler)
assert os.environ["APP_INSTANCE_ID"] == "api-a"
# --- allowlist и проверка настроек ------------------------------------------
def test_client_identities_are_dns_san_only() -> None:
peercert = {
"subject": ((("commonName", "api"),),),
"subjectAltName": (("DNS", "haproxy"), ("IP Address", "10.0.0.1")),
}
assert client_identities(peercert) == ("haproxy",)
assert client_identities(None) == ()
assert is_allowed(("haproxy",), ("haproxy",))
assert not is_allowed(("mtls-probe",), ("haproxy",))
assert not is_allowed((), ("haproxy",))
def test_tls_problems_without_files() -> None:
assert tls_problems(Settings.from_env({})) == [
"TLS_CERT_FILE",
"TLS_KEY_FILE",
"TLS_CA_FILE",
"TLS_CRL_FILE",
]
# --- настоящие рукопожатия ---------------------------------------------------
def _pki(env: dict[str, str], *args: str) -> None:
done = subprocess.run(
["sh", str(PKI), *args], env=env, capture_output=True, text=True, check=False
)
if done.returncode != 0:
pytest.skip(f"infra/pki/pki.sh {args[0]} failed (OpenSSL 3+?): {done.stderr}")
@pytest.fixture(scope="module")
def pki(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Path]:
"""CA стенда и файлы стенда, разовая mtls-probe, haproxy другого CA и
копия CRL до отзыва (её берёт тест отзыва)."""
base = tmp_path_factory.mktemp("pki")
env = {
**os.environ,
"PKI_OPERATOR_DIR": str(base / "operator"),
"PKI_STAND_DIR": str(base / "stand"),
}
_pki(env, "stand")
_pki(env, "issue", "mtls-probe", "--profile", "client", "--san", "mtls-probe",
"--days", "1", "--out", str(base / "probe"), "--bundle") # fmt: skip
(base / "crl-before.pem").write_bytes((base / "stand" / "crl.pem").read_bytes())
other = {**env, "PKI_OPERATOR_DIR": str(base / "other")}
_pki(other, "init")
_pki(other, "issue", "haproxy", "--profile", "client", "--san", "haproxy",
"--days", "1", "--out", str(base / "foreign"), "--bundle") # fmt: skip
return {"base": base, "stand": base / "stand", "env": env} # type: ignore[dict-item]
def _revoke_haproxy(pki: dict) -> Path:
"""Отозвать haproxy (действующие пары identity) и вернуть новый CRL."""
_pki(pki["env"], "revoke", "haproxy")
return pki["stand"] / "crl.pem"
async def _app(scope, receive, send) -> None: # noqa: ANN001
if scope["type"] != "http":
return
await send({"type": "http.response.start", "status": 200, "headers": []})
await send({"type": "http.response.body", "body": b"ok"})
class _Server:
def __init__(self, tls: Tls, app=_app) -> None: # noqa: ANN001
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
self.port = sock.getsockname()[1]
sock.close()
config = uvicorn.Config(
app,
host="127.0.0.1",
port=self.port,
ssl_context_factory=context_factory(tls),
http=allowlist_protocol(tls),
log_config=None,
lifespan="off",
)
self.server = uvicorn.Server(config)
self.thread = threading.Thread(target=self.server.run, daemon=True)
def __enter__(self) -> "_Server":
self.thread.start()
deadline = time.monotonic() + 10
while not self.server.started and time.monotonic() < deadline:
time.sleep(0.05)
assert self.server.started
return self
def __exit__(self, *_: object) -> None:
self.server.should_exit = True
self.thread.join(10)
def _connect(port: int, ca: Path, pair: Path | None) -> str:
"""Исход для клиента: `http 200`, `closed` или `tls_error`."""
context = ssl.create_default_context(cafile=str(ca))
if pair is not None:
context.load_cert_chain(str(pair))
raw = socket.create_connection(("127.0.0.1", port), timeout=5)
try:
try:
sock = context.wrap_socket(raw, server_hostname="api")
except (ssl.SSLError, OSError):
return "tls_error"
try:
sock.sendall(REQUEST)
data = sock.recv(4096)
except (ssl.SSLError, OSError):
return "tls_error"
if data.startswith(b"HTTP/1.1 "):
return "http " + data.split()[1].decode()
return "closed"
finally:
raw.close()
def _tls(stand: Path, crl: Path | None = None) -> Tls:
return Tls(
cert_file=str(stand / "api.crt"),
key_file=str(stand / "api.key"),
ca_file=str(stand / "ca.crt"),
crl_file=str(crl or stand / "crl.pem"),
client_auth=True,
allowed_clients=("haproxy",),
)
def test_mtls_handshakes(pki: dict, caplog: pytest.LogCaptureFixture) -> None:
"""Без сертификата, другой CA, серверный сертификат — отказ рукопожатия
(в TLS 1.3 клиент узнаёт о нём алертом или закрытием уже после своей
половины), строки «tls client rejected» о них нет; identity того же CA
вне allowlist — закрыто без ответа и строка; haproxy — 200."""
stand, base = pki["stand"], pki["base"]
ca = stand / "ca.crt"
with _Server(_tls(stand)) as server, caplog.at_level("WARNING"):
assert _connect(server.port, ca, None) in NO_HTTP
assert _connect(server.port, ca, base / "foreign" / "haproxy.pem") in NO_HTTP
assert _connect(server.port, ca, stand / "ingress.pem") in NO_HTTP
time.sleep(0.2)
assert "tls client rejected" not in caplog.text
assert _connect(server.port, ca, base / "probe" / "mtls-probe.pem") in NO_HTTP
time.sleep(0.2)
assert "tls client rejected identity=mtls-probe" in caplog.text
assert _connect(server.port, ca, stand / "haproxy.pem") == "http 200"
# без TLS: HTTP-ответа нет
with _Server(_tls(stand)) as server:
raw = socket.create_connection(("127.0.0.1", server.port), timeout=5)
try:
raw.sendall(REQUEST)
try:
data = raw.recv(4096)
except OSError:
data = b""
finally:
raw.close()
assert not data.startswith(b"HTTP/1.1 200")
def test_revoked_client_is_rejected(pki: dict) -> None:
stand, base = pki["stand"], pki["base"]
crl = _revoke_haproxy(pki)
with _Server(_tls(stand, crl)) as server:
assert _connect(server.port, stand / "ca.crt", stand / "haproxy.pem") in NO_HTTP
# тот же сервер со старым CRL принимает ту же пару: отказ дал именно CRL
with _Server(_tls(stand, base / "crl-before.pem")) as server:
assert _connect(server.port, stand / "ca.crt", stand / "haproxy.pem") == (
"http 200"
)
def test_tls_problems_on_real_files(pki: dict) -> None:
stand = pki["stand"]
files = {
"TLS_CERT_FILE": str(stand / "api.crt"),
"TLS_KEY_FILE": str(stand / "api.key"),
"TLS_CA_FILE": str(stand / "ca.crt"),
"TLS_CRL_FILE": str(stand / "crl.pem"),
}
assert tls_problems(Settings.from_env({**files, "APP_HOST": "0.0.0.0"})) == []
# без проверки клиента — только loopback
no_auth = {**files, "TLS_CLIENT_AUTH": "false"}
assert tls_problems(Settings.from_env({**no_auth, "APP_HOST": "127.0.0.1"})) == []
assert tls_problems(Settings.from_env({**no_auth, "APP_HOST": "0.0.0.0"})) == [
"TLS_CLIENT_AUTH"
]
# ключ не от сертификата — отказ сборки контекста
broken = {**files, "TLS_KEY_FILE": str(stand / "haproxy.key")}
assert "TLS_KEY_FILE" in tls_problems(Settings.from_env(broken))
# --- билеты сессии и обрыв тела (перенос https-tooling) ----------------------
def _bytes_after_handshake(
server: ssl.SSLContext, client: ssl.SSLContext, server_hostname: str
) -> int:
"""Рукопожатие в памяти до конца с обеих сторон; сколько байт сервер
отдал клиенту сверх прочитанного в рукопожатии (билеты TLS 1.3)."""
s_in, s_out, c_in, c_out = (ssl.MemoryBIO() for _ in range(4))
server_conn = server.wrap_bio(s_in, s_out, server_side=True)
client_conn = client.wrap_bio(c_in, c_out, server_hostname=server_hostname)
done = {"client": False, "server": False}
for _ in range(10):
for name, conn in (("client", client_conn), ("server", server_conn)):
if not done[name]:
try:
conn.do_handshake()
done[name] = True
except ssl.SSLWantReadError:
pass
s_in.write(c_out.read())
c_in.write(s_out.read())
if all(done.values()):
break
assert all(done.values()), done
return c_in.pending
@pytest.mark.parametrize("client_auth", [True, False])
def test_no_messages_after_handshake(pki: dict, client_auth: bool) -> None:
"""Билеты сессии TLS 1.3 после рукопожатия — непрочитанные байты у
клиента, который только пишет тело; его обрыв тогда — RST, и процесс API
его не замечал (докстринг `src/tls.py`)."""
stand, base = pki["stand"], pki["base"]
client = ssl.create_default_context(cafile=str(stand / "ca.crt"))
if client_auth:
tls = _tls(stand, base / "crl-before.pem")
client.load_cert_chain(str(stand / "haproxy.pem"))
name = "api"
else:
tls = Tls(
cert_file=str(stand / "ingress.crt"),
key_file=str(stand / "ingress.key"),
client_auth=False,
)
name = "localhost"
assert _bytes_after_handshake(server_context(tls), client, name) == 0
# тело обрываемой загрузки и срок, за который сервер обязан заметить обрыв
ABORTED_BODY = b"\x89PNG\r\n\x1a\n" + bytes(1024 * 1024)
ABORT_NOTICED_S = 1.0
ABORT_ROUNDS = 3
def _aborted_upload(port: int, stand: Path) -> None:
"""Клиент в роли LB: заголовки, 1 MiB тела частью chunked, закрытие
сокета без чтения ответа (как httpx на исключении итератора тела)."""
context = ssl.create_default_context(cafile=str(stand / "ca.crt"))
context.load_cert_chain(str(stand / "haproxy.pem"))
with (
socket.create_connection(("127.0.0.1", port), timeout=5) as raw,
context.wrap_socket(raw, server_hostname="api") as conn,
):
conn.sendall(
b"POST /upload HTTP/1.1\r\nHost: api\r\nTransfer-Encoding: chunked\r\n\r\n"
)
conn.sendall(f"{len(ABORTED_BODY):x}\r\n".encode() + ABORTED_BODY + b"\r\n")
def test_aborted_body_noticed(pki: dict) -> None:
"""Обрыв тела по mTLS доходит до приложения как `http.disconnect` сразу,
а не по сроку тела."""
stand, base = pki["stand"], pki["base"]
outcomes: list[str] = []
async def body_app(scope, receive, send) -> None: # noqa: ANN001
if scope["type"] != "http":
return
outcome = "complete"
try:
async with asyncio.timeout(ABORT_NOTICED_S * 5):
while True:
message = await receive()
if message["type"] == "http.disconnect":
outcome = "disconnect"
break
if not message.get("more_body"):
break
except TimeoutError:
outcome = "timeout"
outcomes.append(outcome)
try:
await send({"type": "http.response.start", "status": 200, "headers": []})
await send({"type": "http.response.body", "body": b""})
except OSError:
pass
with _Server(_tls(stand, base / "crl-before.pem"), app=body_app) as server:
for attempt in range(ABORT_ROUNDS):
_aborted_upload(server.port, stand)
deadline = time.monotonic() + ABORT_NOTICED_S
while len(outcomes) <= attempt and time.monotonic() < deadline:
time.sleep(0.02)
assert outcomes[attempt:] == ["disconnect"], (attempt, outcomes)
# --- перевыпуск leaf по списку identity (перенос https-tooling) -------------
def _serial(path: Path) -> str:
done = subprocess.run(
["openssl", "x509", "-in", str(path), "-noout", "-serial"],
capture_output=True,
text=True,
check=True,
)
return done.stdout.strip()
def test_stand_reissues_leaf_that_differs_from_list(tmp_path: Path) -> None:
"""`pki.sh stand` перевыпускает leaf, чьи DNS SAN или назначение разошлись
со строкой списка; остальные и повтор без правки — без перевыпуска."""
old = tmp_path / "old.conf"
old.write_text(
"haproxy client haproxy bundle\napi server api split\n"
"ingress server localhost bundle\n"
)
new = tmp_path / "new.conf"
new.write_text(
"haproxy client haproxy bundle\napi server api split\n"
"ingress server ingress,localhost bundle\n"
)
swapped = tmp_path / "swapped.conf"
swapped.write_text(
"haproxy client haproxy bundle\napi client api split\n"
"ingress server ingress,localhost bundle\n"
)
env = {
**os.environ,
"PKI_OPERATOR_DIR": str(tmp_path / "operator"),
"PKI_STAND_DIR": str(tmp_path / "stand"),
}
stand = tmp_path / "stand"
def run(identities: Path) -> str:
done = subprocess.run(
["sh", str(PKI), "stand"],
env={**env, "PKI_IDENTITIES": str(identities)},
capture_output=True,
text=True,
check=False,
)
if done.returncode != 0:
pytest.skip(f"infra/pki/pki.sh stand failed (OpenSSL 3+?): {done.stderr}")
assert "PRIVATE KEY" not in done.stdout + done.stderr
return done.stdout
def reissued(identities: Path) -> list[str]:
out = run(identities).splitlines()
return [line for line in out if line.startswith("reissue ")]
run(old)
serials = {name: _serial(stand / f"{name}.crt") for name in ("haproxy", "api")}
assert reissued(new) == ["reissue ingress: SAN differ from the list"]
assert {name: _serial(stand / f"{name}.crt") for name in serials} == serials
assert reissued(new) == []
assert reissued(swapped) == ["reissue api: purpose differs from the list"]
# --- слушатель health ---------------------------------------------------------
async def _ask(port: int, line: str) -> bytes:
reader, writer = await asyncio.open_connection("127.0.0.1", port)
writer.write(f"{line}\r\nHost: x\r\n\r\n".encode())
await writer.drain()
data = await reader.read()
writer.close()
return data
def _listen(ready, *requests: str) -> list[bytes]: # noqa: ANN001
async def scenario() -> list[bytes]:
listener = HealthListener(ready=ready, instance_id="0123456789abcdef", port=0)
await listener.start()
try:
return [await _ask(listener.port, line) for line in requests]
finally:
await listener.close()
return asyncio.run(scenario())
def test_health_listener_answers_only_live_and_ready() -> None:
calls: list[int] = []
async def ready() -> bool:
calls.append(1)
return True
live, ready_ok, me, register, head = _listen(
ready,
"GET /health/live HTTP/1.1",
"GET /health/ready HTTP/1.1",
"GET /api/v1/users/me HTTP/1.1",
"POST /api/v1/users HTTP/1.1",
"HEAD /health/live HTTP/1.1",
)
assert live.startswith(b"HTTP/1.1 200 ")
assert ready_ok.startswith(b"HTTP/1.1 200 ")
assert b"X-Instance-Id: 0123456789abcdef" in live
assert b"Connection: close" in live
for answer in (me, register, head):
assert answer.startswith(b"HTTP/1.1 404 ")
assert b'"code": "not_found"' in answer
assert len(calls) == 1
def test_health_listener_not_ready_and_slow_ready(
monkeypatch: pytest.MonkeyPatch,
) -> None:
async def not_ready() -> bool:
return False
(answer,) = _listen(not_ready, "GET /health/ready HTTP/1.1")
assert answer.startswith(b"HTTP/1.1 503 ")
assert b'"code": "unavailable"' in answer
# проверка готовности дольше своего срока — 503, а не обрыв
monkeypatch.setattr(listener_module, "HEALTH_LISTENER_READY_TIMEOUT", 0.2)
async def frozen() -> bool:
await asyncio.sleep(5)
return True
started = time.monotonic()
(answer,) = _listen(frozen, "GET /health/ready HTTP/1.1")
assert answer.startswith(b"HTTP/1.1 503 ")
assert time.monotonic() - started < 2
def test_health_listener_timeouts_are_chained() -> None:
from src.constants import (
DB_CLOSE_TIMEOUT,
HEALTH_LISTENER_READY_TIMEOUT,
READINESS_TIMEOUT,
)
from src.healthcheck import TIMEOUT
assert HEALTH_LISTENER_READY_TIMEOUT > READINESS_TIMEOUT + DB_CLOSE_TIMEOUT
assert TIMEOUT > HEALTH_LISTENER_READY_TIMEOUT
dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8")
match = re.search(r"HEALTHCHECK .*--timeout=(\d+)s", dockerfile)
assert match
assert int(match.group(1)) > TIMEOUT