forked from mtusi2026/mtusi2026lab7
wip: apply pki-ingress-mtls groups 1-4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
"""TLS процесса API (change `pki-ingress-mtls`): контекст сервера и проверка
|
||||
`[api_tls]` — `context.py` (без логгера); протокол с allowlist identity —
|
||||
`protocol.py`, его импортирует только uvicorn по строке
|
||||
`PROTOCOL_IMPORT_PATH`."""
|
||||
|
||||
from src.infra.tls.context import (
|
||||
api_tls_problems,
|
||||
build_server_context,
|
||||
client_identities,
|
||||
is_allowed_client,
|
||||
ssl_context_factory,
|
||||
)
|
||||
|
||||
PROTOCOL_IMPORT_PATH = "src.infra.tls.protocol:AllowlistHttpToolsProtocol"
|
||||
|
||||
__all__ = [
|
||||
"PROTOCOL_IMPORT_PATH",
|
||||
"api_tls_problems",
|
||||
"build_server_context",
|
||||
"client_identities",
|
||||
"is_allowed_client",
|
||||
"ssl_context_factory",
|
||||
]
|
||||
@@ -0,0 +1,111 @@
|
||||
"""TLS процесса API: контекст сервера, allowlist identity клиента и проверка
|
||||
настроек `[api_tls]` (change `pki-ingress-mtls`, design, решения 4, 5, 10;
|
||||
правило `.claude/rules/tls.md`).
|
||||
|
||||
- С проверкой клиента (docker, mTLS LB → реплика): TLS 1.3, сертификат
|
||||
клиента обязателен, цепочка — по CA стенда, отзыв — по CRL
|
||||
(`VERIFY_CRL_CHECK_LEAF`: без CRL или с просроченным CRL рукопожатие не
|
||||
проходит), `VERIFY_X509_STRICT`. Назначение `clientAuth` проверяет сам
|
||||
OpenSSL (purpose `sslclient` на стороне сервера): серверный сертификат
|
||||
клиентом быть не может даже при ошибке в allowlist.
|
||||
- Без проверки клиента (консоль): TLS 1.2 и новее, только сертификат
|
||||
сервера.
|
||||
|
||||
Identity клиента — DNS-имена SAN; CN не смотрится. Решение по allowlist
|
||||
принимает протокол соединения (`protocol.py`) после рукопожатия.
|
||||
"""
|
||||
|
||||
import ssl
|
||||
from collections.abc import Callable, Iterable
|
||||
from typing import Any
|
||||
|
||||
from src.config.settings import ApiTls
|
||||
from src.schemas.enums import RunModeEnum
|
||||
|
||||
ALPN_PROTOCOLS = ["http/1.1"]
|
||||
|
||||
|
||||
def build_server_context(tls: ApiTls) -> ssl.SSLContext:
|
||||
"""`SSLContext` сервера по `[api_tls]`; ошибки файлов — `OSError` и
|
||||
`ssl.SSLError`."""
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(certfile=tls.cert_file, keyfile=tls.key_file)
|
||||
context.set_alpn_protocols(ALPN_PROTOCOLS)
|
||||
if not tls.client_auth:
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
return context
|
||||
# обе стороны внутренней связи — наши: только TLS 1.3
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
context.verify_mode = ssl.CERT_REQUIRED
|
||||
context.load_verify_locations(cafile=tls.client_ca_file)
|
||||
# PEM с CRL попадает в то же хранилище X509
|
||||
context.load_verify_locations(cafile=tls.crl_file)
|
||||
context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT
|
||||
return context
|
||||
|
||||
|
||||
def ssl_context_factory(
|
||||
_config: Any,
|
||||
_default_factory: Callable[[], ssl.SSLContext],
|
||||
) -> ssl.SSLContext:
|
||||
"""Хук `uvicorn.run(ssl_context_factory=…)`: модульная функция — её
|
||||
pickle переживает reload консоли; настройки читает процесс сервера."""
|
||||
from src.config import settings
|
||||
|
||||
return build_server_context(settings.api_tls)
|
||||
|
||||
|
||||
def client_identities(peercert: dict[str, Any] | None) -> tuple[str, ...]:
|
||||
"""DNS-имена SAN сертификата клиента (`getpeercert()`)."""
|
||||
if not peercert:
|
||||
return ()
|
||||
return tuple(
|
||||
value
|
||||
for kind, value in peercert.get("subjectAltName", ())
|
||||
if kind == "DNS"
|
||||
)
|
||||
|
||||
|
||||
def is_allowed_client(
|
||||
identities: Iterable[str],
|
||||
allowed: Iterable[str],
|
||||
) -> bool:
|
||||
"""Хотя бы одно DNS-имя SAN клиента — в allowlist."""
|
||||
return bool(set(identities) & set(allowed))
|
||||
|
||||
|
||||
def _readable(path: str) -> bool:
|
||||
if not path:
|
||||
return False
|
||||
try:
|
||||
with open(path, "rb"):
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def api_tls_problems(tls: ApiTls, run_mode: RunModeEnum) -> list[str]:
|
||||
"""Имена неверных полей `[api_tls]` для старта API (без значений).
|
||||
|
||||
Docker: четыре файла читаются, проверка клиента включена, allowlist не
|
||||
пуст. Консоль: сертификат и ключ (с проверкой клиента — ещё CA и CRL).
|
||||
Затем контекст собирается: битый PEM или ключ не от сертификата — поле
|
||||
`api_tls`.
|
||||
"""
|
||||
files = ["cert_file", "key_file"]
|
||||
problems: list[str] = []
|
||||
if run_mode == RunModeEnum.DOCKER or tls.client_auth:
|
||||
files += ["client_ca_file", "crl_file"]
|
||||
problems += [name for name in files if not _readable(getattr(tls, name))]
|
||||
if run_mode == RunModeEnum.DOCKER:
|
||||
if not tls.client_auth:
|
||||
problems.append("client_auth")
|
||||
if not [name for name in tls.allowed_clients if name.strip()]:
|
||||
problems.append("allowed_clients")
|
||||
if problems:
|
||||
return problems
|
||||
try:
|
||||
build_server_context(tls)
|
||||
except (OSError, ssl.SSLError):
|
||||
return ["api_tls"]
|
||||
return []
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Протокол HTTP процесса API с проверкой identity клиента (change
|
||||
`pki-ingress-mtls`, design, решение 5).
|
||||
|
||||
Наследник `HttpToolsProtocol` (его выбирает `auto` uvicorn при
|
||||
установленном httptools). asyncio и uvloop вызывают `connection_made` после
|
||||
рукопожатия TLS, а `data_received` — позже: здесь HTTP-запрос ещё не
|
||||
читался. Родитель регистрирует соединение в учёте uvicorn, затем, если
|
||||
DNS-имён SAN клиента нет в `[api_tls] allowed_clients`, — `warning`
|
||||
«Rejected TLS client» (identity и причина, без содержимого сертификата) и
|
||||
`transport.abort()`; `connection_lost` придёт штатно и снимет учёт.
|
||||
Сертификат без подписи CA стенда, отозванный или без сертификата сюда не
|
||||
доходит: отказ на рукопожатии. Опирается на внутренности uvicorn (версия
|
||||
закреплена `uv.lock`), смену ловит быстрый тест настоящего рукопожатия.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
from uvicorn.protocols.http.httptools_impl import HttpToolsProtocol
|
||||
|
||||
from src.config import settings
|
||||
from src.infra.logger import AbstractLogger, get_logger
|
||||
from src.infra.tls.context import client_identities, is_allowed_client
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="api_tls")
|
||||
|
||||
|
||||
class AllowlistHttpToolsProtocol(HttpToolsProtocol):
|
||||
"""HTTP/1.1 только для клиента из allowlist."""
|
||||
|
||||
def connection_made( # type: ignore[override]
|
||||
self,
|
||||
transport: asyncio.Transport,
|
||||
) -> None:
|
||||
super().connection_made(transport)
|
||||
tls = settings.api_tls
|
||||
if not tls.client_auth:
|
||||
return
|
||||
identities = client_identities(transport.get_extra_info("peercert"))
|
||||
if is_allowed_client(identities, tls.allowed_clients):
|
||||
return
|
||||
logger.warning(
|
||||
"Rejected TLS client",
|
||||
client_identity=list(identities),
|
||||
reason="identity_not_allowed" if identities else "no_dns_san",
|
||||
)
|
||||
transport.abort()
|
||||
Reference in New Issue
Block a user