385 lines
15 KiB
Python
385 lines
15 KiB
Python
"""Лаба 7: TLS клиентов к PostgreSQL, Valkey и S3 (перенос storage-tls).
|
||
|
||
Без стенда. Настройки и проверка точки входа (`src/client_tls.py`), контекст
|
||
клиента и настоящие рукопожатия со своим TLS-сервером на loopback в потоке:
|
||
сертификаты `postgres`, `valkey`, `s3` выпускает `infra/pki/pki.sh` во
|
||
временный каталог (без OpenSSL ≥ 3 — пропуск с причиной). Проводка клиентов
|
||
приложения: `Db` (asyncpg), `create_cache` (redis-py, `TlsConnection`),
|
||
`create_object_store` (aiobotocore) — по CA стенда и имени; чужой CA и
|
||
адрес вне SAN — та же недоступность (503 у PostgreSQL и S3, обход у кэша).
|
||
Положительный путь протоколов хранилищ — `make storage-tls-check` на стенде.
|
||
"""
|
||
|
||
import asyncio
|
||
import logging
|
||
import os
|
||
import socket
|
||
import ssl
|
||
import subprocess
|
||
import threading
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
from src.cache import TlsConnection, create_cache
|
||
from src.client_tls import (
|
||
API_STORAGES,
|
||
MIGRATION_STORAGES,
|
||
RELAY_STORAGES,
|
||
WORKER_STORAGES,
|
||
check_or_exit,
|
||
client_context,
|
||
client_tls_problems,
|
||
)
|
||
from src.config import Cache, ClientTls, Database, ObjectStorage, Settings
|
||
from src.db import Db
|
||
from src.errors import ObjectStorageUnavailable, Unavailable
|
||
from src.s3 import create_object_store
|
||
|
||
pytestmark = pytest.mark.unit
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
PKI = ROOT / "infra" / "pki" / "pki.sh"
|
||
# файлы входа в OpenBao: обязательны всем процессам с переноса openbao-secrets
|
||
BAO_FILES = ("BAO_CERT_FILE", "BAO_KEY_FILE", "BAO_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, пары postgres, valkey, s3, api) и CA другого
|
||
оператора (его ключ — во временном каталоге теста)."""
|
||
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, "PKI_OPERATOR_DIR": str(base / "other")}, "init")
|
||
return {"stand": base / "stand", "foreign": base / "other" / "ca.crt"}
|
||
|
||
|
||
def _settings(env: dict[str, str]) -> Settings:
|
||
return Settings.from_env(env)
|
||
|
||
|
||
# --- настройки и проверка точки входа ---------------------------------------
|
||
|
||
|
||
def test_client_tls_settings_and_defaults() -> None:
|
||
settings = Settings.from_env({})
|
||
assert settings.client_tls == ClientTls(ca_file="")
|
||
assert ClientTls.from_env({"CLIENT_TLS_CA_FILE": " /ca.crt "}).ca_file == "/ca.crt"
|
||
# умолчания — имена и https: без окружения нечему уйти открытым текстом
|
||
assert settings.database.host == "localhost"
|
||
assert settings.cache.host == "localhost"
|
||
assert settings.s3.endpoint == "https://localhost:8334"
|
||
|
||
|
||
def test_storages_by_process() -> None:
|
||
# с переноса messaging-telemetry-mtls у worker и relay ещё брокер
|
||
# (student-tests/unit/test_broker_tls.py), с переноса telemetry-mtls у всех
|
||
# троих — приём Collector (test_telemetry_tls.py), с переноса openbao-secrets у
|
||
# всех — OpenBao (test_secrets_store.py)
|
||
assert API_STORAGES == ("database", "cache", "s3", "telemetry", "secret_store")
|
||
assert WORKER_STORAGES == (
|
||
"database",
|
||
"s3",
|
||
"broker",
|
||
"telemetry",
|
||
"secret_store",
|
||
)
|
||
assert RELAY_STORAGES == ("database", "broker", "telemetry", "secret_store")
|
||
assert MIGRATION_STORAGES == ("database", "secret_store")
|
||
|
||
|
||
def test_problems_without_ca_and_with_ip_addresses(tmp_path: Path) -> None:
|
||
assert client_tls_problems(_settings({}), API_STORAGES) == [
|
||
"CLIENT_TLS_CA_FILE",
|
||
*BAO_FILES,
|
||
]
|
||
missing = str(tmp_path / "missing.crt")
|
||
env = {
|
||
"CLIENT_TLS_CA_FILE": missing,
|
||
"DB_HOST": "127.0.0.1",
|
||
"CACHE_HOST": "::1",
|
||
"S3_ENDPOINT": "https://10.0.0.5:8333",
|
||
}
|
||
assert client_tls_problems(_settings(env), API_STORAGES) == [
|
||
"CLIENT_TLS_CA_FILE",
|
||
"DB_HOST",
|
||
"CACHE_HOST",
|
||
"S3_ENDPOINT",
|
||
*BAO_FILES,
|
||
]
|
||
# процесс проверяет только свои хранилища (у relay с переноса
|
||
# messaging-telemetry-mtls — ещё файлы брокера, поэтому здесь migrate)
|
||
assert client_tls_problems(_settings(env), MIGRATION_STORAGES) == [
|
||
"CLIENT_TLS_CA_FILE",
|
||
"DB_HOST",
|
||
*BAO_FILES,
|
||
]
|
||
plain = {"S3_ENDPOINT": "http://s3:8333"}
|
||
assert "S3_ENDPOINT" in client_tls_problems(_settings(plain), WORKER_STORAGES)
|
||
|
||
|
||
def test_problems_on_real_files(pki: dict, tmp_path: Path) -> None:
|
||
stand = pki["stand"]
|
||
good = {
|
||
"CLIENT_TLS_CA_FILE": str(stand / "ca.crt"),
|
||
"DB_HOST": "postgres",
|
||
"CACHE_HOST": "valkey",
|
||
"S3_ENDPOINT": "https://s3:8333",
|
||
"BAO_CERT_FILE": str(stand / "api-client.crt"),
|
||
"BAO_KEY_FILE": str(stand / "api-client.key"),
|
||
"BAO_CRL_FILE": str(stand / "crl.pem"),
|
||
}
|
||
assert client_tls_problems(_settings(good), API_STORAGES) == []
|
||
# файл читается, но сертификата CA в нём нет: leaf, CRL, не PEM
|
||
broken = tmp_path / "broken.crt"
|
||
broken.write_text("not a certificate\n", encoding="ascii")
|
||
for path in (stand / "postgres.crt", stand / "crl.pem", broken):
|
||
env = {**good, "CLIENT_TLS_CA_FILE": str(path)}
|
||
assert client_tls_problems(_settings(env), API_STORAGES) == [
|
||
"CLIENT_TLS_CA_FILE"
|
||
], path.name
|
||
|
||
|
||
def test_check_or_exit_names_only(
|
||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||
) -> None:
|
||
secret_path = str(tmp_path / "secret-dir" / "ca.crt")
|
||
env = {"CLIENT_TLS_CA_FILE": secret_path, "DB_HOST": "192.0.2.1"}
|
||
with pytest.raises(SystemExit) as exit_info:
|
||
check_or_exit(_settings(env), MIGRATION_STORAGES)
|
||
assert exit_info.value.code == 2
|
||
err = capsys.readouterr().err
|
||
assert err.strip() == (
|
||
"configuration error: invalid client TLS settings: CLIENT_TLS_CA_FILE, "
|
||
"DB_HOST, BAO_CERT_FILE, BAO_KEY_FILE, BAO_CRL_FILE"
|
||
)
|
||
assert "secret-dir" not in err
|
||
assert "192.0.2.1" not in err
|
||
|
||
|
||
def test_client_context_flags(pki: dict) -> None:
|
||
context = client_context(str(pki["stand"] / "ca.crt"))
|
||
assert context.minimum_version == ssl.TLSVersion.TLSv1_3
|
||
assert context.check_hostname is True
|
||
assert context.verify_mode == ssl.CERT_REQUIRED
|
||
assert context.verify_flags & ssl.VERIFY_X509_STRICT
|
||
# только CA стенда: системные корни не загружены
|
||
assert context.cert_store_stats()["x509_ca"] == 1
|
||
# без пути — ни одного доверенного CA (fail-closed), а не системные
|
||
assert client_context("").cert_store_stats()["x509_ca"] == 0
|
||
|
||
|
||
# --- свой TLS-сервер на loopback ------------------------------------------------
|
||
|
||
|
||
class _Server:
|
||
"""TLS-сервер в потоке: `pg` — сначала SSLRequest PostgreSQL и ответ «S»;
|
||
`reply(sock)` — что ответить после рукопожатия. `handshakes` — число
|
||
успешных рукопожатий."""
|
||
|
||
def __init__(self, stand: Path, name: str, *, pg: bool = False, reply=None):
|
||
self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||
self.context.load_cert_chain(stand / f"{name}.crt", stand / f"{name}.key")
|
||
self.pg = pg
|
||
self.reply = reply
|
||
self.handshakes = 0
|
||
self.listener = socket.create_server(("127.0.0.1", 0))
|
||
self.port = self.listener.getsockname()[1]
|
||
self.thread = threading.Thread(target=self._serve, daemon=True)
|
||
|
||
def _serve(self) -> None:
|
||
while True:
|
||
try:
|
||
raw, _ = self.listener.accept()
|
||
except OSError:
|
||
return
|
||
threading.Thread(target=self._one, args=(raw,), daemon=True).start()
|
||
|
||
def _one(self, raw: socket.socket) -> None:
|
||
raw.settimeout(5)
|
||
try:
|
||
if self.pg:
|
||
raw.recv(8)
|
||
raw.sendall(b"S")
|
||
with self.context.wrap_socket(raw, server_side=True) as sock:
|
||
self.handshakes += 1
|
||
if self.reply is not None:
|
||
self.reply(sock)
|
||
except (OSError, ssl.SSLError):
|
||
pass
|
||
finally:
|
||
raw.close()
|
||
|
||
def __enter__(self) -> "_Server":
|
||
self.thread.start()
|
||
return self
|
||
|
||
def __exit__(self, *_: object) -> None:
|
||
self.listener.close()
|
||
|
||
|
||
def _connect(port: int, ca: Path, name: str) -> str:
|
||
try:
|
||
with (
|
||
socket.create_connection(("127.0.0.1", port), timeout=5) as raw,
|
||
client_context(str(ca)).wrap_socket(raw, server_hostname=name) as sock,
|
||
):
|
||
return str(sock.version())
|
||
except ssl.SSLCertVerificationError as error:
|
||
return "name" if "mismatch" in str(error) else "certificate"
|
||
|
||
|
||
@pytest.mark.parametrize("identity", ["postgres", "valkey", "s3"])
|
||
def test_handshakes(pki: dict, identity: str) -> None:
|
||
stand = pki["stand"]
|
||
with _Server(stand, identity) as server:
|
||
assert _connect(server.port, stand / "ca.crt", "localhost") == "TLSv1.3"
|
||
assert _connect(server.port, stand / "ca.crt", identity) == "TLSv1.3"
|
||
assert _connect(server.port, pki["foreign"], "localhost") == "certificate"
|
||
assert _connect(server.port, stand / "ca.crt", "127.0.0.1") == "name"
|
||
# сертификат другой identity того же CA под этим именем не проходит
|
||
assert _connect(server.port, stand / "ca.crt", "api") == "name"
|
||
|
||
|
||
def test_client_refuses_tls_below_1_3(pki: dict) -> None:
|
||
stand = pki["stand"]
|
||
with _Server(stand, "postgres") as server:
|
||
server.context.maximum_version = ssl.TLSVersion.TLSv1_2
|
||
with pytest.raises(ssl.SSLError):
|
||
_connect(server.port, stand / "ca.crt", "localhost")
|
||
|
||
|
||
# --- проводка клиентов приложения -------------------------------------------
|
||
|
||
|
||
def test_db_tls_failure_is_unavailable(pki: dict) -> None:
|
||
stand = pki["stand"]
|
||
|
||
async def scenario(db: Db) -> None:
|
||
try:
|
||
with pytest.raises(Unavailable):
|
||
async with db.read():
|
||
pass
|
||
with pytest.raises(Unavailable):
|
||
await db.ping()
|
||
finally:
|
||
await db.dispose()
|
||
|
||
with _Server(stand, "postgres", pg=True) as server:
|
||
base = Database(host="localhost", port=server.port, connect_timeout=2)
|
||
asyncio.run(scenario(Db(base, ca_file=str(pki["foreign"]))))
|
||
# чужой CA: рукопожатие не прошло
|
||
assert server.handshakes == 0
|
||
ip = Database(host="127.0.0.1", port=server.port, connect_timeout=2)
|
||
asyncio.run(scenario(Db(ip, ca_file=str(stand / "ca.crt"))))
|
||
# имя вне SAN: клиент отверг сертификат до конца рукопожатия
|
||
assert server.handshakes == 0
|
||
asyncio.run(scenario(Db(base, ca_file=str(stand / "ca.crt"))))
|
||
# CA стенда и имя: рукопожатие прошло (дальше протокол PostgreSQL
|
||
# сервер пробы не знает и закрывает соединение — тоже недоступность)
|
||
assert server.handshakes > 0
|
||
|
||
|
||
def _resp_reply(sock: ssl.SSLSocket) -> None:
|
||
"""RESP: на GET — `value`, на прочее (CLIENT SETINFO и т. п.) — +OK."""
|
||
buffer = b""
|
||
while True:
|
||
chunk = sock.recv(4096)
|
||
if not chunk:
|
||
return
|
||
buffer += chunk
|
||
while buffer.startswith(b"*"):
|
||
lines = buffer.split(b"\r\n")
|
||
count = int(lines[0][1:])
|
||
if len(lines) < 1 + 2 * count + 1:
|
||
break
|
||
parts = lines[2 : 2 + 2 * count : 2]
|
||
consumed = sum(len(line) + 2 for line in lines[: 1 + 2 * count])
|
||
buffer = buffer[consumed:]
|
||
if parts[0].upper() == b"GET":
|
||
sock.sendall(b"$5\r\nvalue\r\n")
|
||
else:
|
||
sock.sendall(b"+OK\r\n")
|
||
|
||
|
||
def test_cache_over_tls_and_bypass(pki: dict, caplog: pytest.LogCaptureFixture) -> None:
|
||
stand = pki["stand"]
|
||
|
||
async def get(cache) -> str | None:
|
||
try:
|
||
return await cache.get("chat")
|
||
finally:
|
||
await cache.close()
|
||
|
||
with _Server(stand, "valkey", reply=_resp_reply) as server:
|
||
settings = Cache(host="localhost", port=server.port, timeout=2)
|
||
cache = create_cache(settings, namespace="t", ca_file=str(stand / "ca.crt"))
|
||
assert cache._client.connection_pool.connection_class is TlsConnection
|
||
assert asyncio.run(get(cache)) == "value"
|
||
with caplog.at_level(logging.WARNING, logger="src.cache"):
|
||
foreign = create_cache(settings, namespace="t", ca_file=str(pki["foreign"]))
|
||
assert asyncio.run(get(foreign)) is None
|
||
ip = Cache(host="127.0.0.1", port=server.port, timeout=2)
|
||
by_ip = create_cache(ip, namespace="t", ca_file=str(stand / "ca.crt"))
|
||
assert asyncio.run(get(by_ip)) is None
|
||
warnings = [r.getMessage() for r in caplog.records]
|
||
assert sum("cache unavailable" in line for line in warnings) == 2
|
||
|
||
|
||
def _http_404(sock: ssl.SSLSocket) -> None:
|
||
data = b""
|
||
while b"\r\n\r\n" not in data:
|
||
chunk = sock.recv(4096)
|
||
if not chunk:
|
||
return
|
||
data += chunk
|
||
sock.sendall(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n")
|
||
|
||
|
||
def test_object_store_over_https(pki: dict) -> None:
|
||
stand = pki["stand"]
|
||
|
||
async def head(store, key: str = "missing"):
|
||
try:
|
||
return await store.head(key)
|
||
finally:
|
||
await store.close()
|
||
|
||
with _Server(stand, "s3", reply=_http_404) as server:
|
||
settings = ObjectStorage(
|
||
endpoint=f"https://localhost:{server.port}", connect_timeout=2, timeout=3
|
||
)
|
||
good = create_object_store(
|
||
settings, namespace="t", ca_file=str(stand / "ca.crt")
|
||
)
|
||
# подписанный HEAD по TLS дошёл до сервера: 404 — «объекта нет»
|
||
assert asyncio.run(head(good)) is None
|
||
foreign = create_object_store(
|
||
settings, namespace="t", ca_file=str(pki["foreign"])
|
||
)
|
||
with pytest.raises(ObjectStorageUnavailable):
|
||
asyncio.run(head(foreign))
|
||
ip = ObjectStorage(endpoint=f"https://127.0.0.1:{server.port}", timeout=3)
|
||
by_ip = create_object_store(ip, namespace="t", ca_file=str(stand / "ca.crt"))
|
||
with pytest.raises(ObjectStorageUnavailable):
|
||
asyncio.run(head(by_ip))
|
||
|
||
|
||
def test_object_store_without_ca_refuses() -> None:
|
||
store = create_object_store(ObjectStorage(), namespace="t", ca_file="")
|
||
with pytest.raises(ValueError, match="CLIENT_TLS_CA_FILE"):
|
||
asyncio.run(store.start())
|