forked from mtusi2026/mtusi2026lab7
feat: accept OTLP only through an mTLS gateway with an identity allowlist
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+23
-7
@@ -539,12 +539,28 @@ class Telemetry(BaseModel):
|
||||
не применяют. Доля выбора трасс и набор границ — design change
|
||||
`track1-telemetry-cost`, решения 3–4: значения по умолчанию сохраняют
|
||||
прежнее поведение, другие задаёт профиль цены телеметрии стенда `bench/`.
|
||||
|
||||
С change `telemetry-mtls` (design, решения 7–8) отправка — только по mTLS
|
||||
через TLS-шлюз Collector: адрес — только `https`, `cert_file` / `key_file`
|
||||
— пара identity процесса (у API — клиентский leaf `api-client`, у worker и
|
||||
relay — их leaf), `crl_file` — CRL стенда; CA — `[client_tls] ca_file`. На
|
||||
стенде пути — `secrets` и `environment` compose, в `config.toml` их нет;
|
||||
консоль телеметрию не включает. Проверяют файлы точки входа API, worker и
|
||||
relay при старте, только при включённой телеметрии (`client_tls_problems`,
|
||||
код 2), а не валидатор. `OTEL_EXPORTER_OTLP_CERTIFICATE` и
|
||||
`OTEL_EXPORTER_OTLP_CLIENT_*` настройками не являются.
|
||||
"""
|
||||
|
||||
# выключена — ни провайдеров SDK, ни отправки, ни полей трассы в журнале
|
||||
enabled: bool = False
|
||||
# адрес OTLP/HTTP Collector: схема, хост и порт, без пути и query
|
||||
otlp_endpoint: str = "http://127.0.0.1:4318"
|
||||
# адрес OTLP/HTTP Collector: только https, хост и порт, без пути и query;
|
||||
# по умолчанию — приём Collector (его TLS-шлюз) в сети стенда
|
||||
otlp_endpoint: str = "https://otel-collector:4318"
|
||||
# пути к сертификату и закрытому ключу identity процесса и к CRL стенда
|
||||
# для mTLS с Collector; пусто при включённой телеметрии — код 2 при старте
|
||||
cert_file: str = ""
|
||||
key_file: str = ""
|
||||
crl_file: str = ""
|
||||
# deployment.environment.name ресурса
|
||||
environment: str = Field(default="lab", pattern=r"^[a-z0-9._-]{1,32}$")
|
||||
# доля корней трасс, выбранных в голове по trace_id (0…1; 1 — все,
|
||||
@@ -587,15 +603,16 @@ class Telemetry(BaseModel):
|
||||
@field_validator("otlp_endpoint")
|
||||
@classmethod
|
||||
def endpoint_without_path(cls, value: str) -> str:
|
||||
"""Схема `http` или `https`, хост и порт; путь сигнала добавляет
|
||||
код (`/v1/traces` и др.)."""
|
||||
"""Схема только `https` (change `telemetry-mtls`: открытого текста к
|
||||
Collector нет), хост и порт; путь сигнала добавляет код
|
||||
(`/v1/traces` и др.)."""
|
||||
parsed = urlsplit(value)
|
||||
try:
|
||||
port = parsed.port
|
||||
except ValueError:
|
||||
port = None
|
||||
if (
|
||||
parsed.scheme not in {"http", "https"}
|
||||
parsed.scheme != "https"
|
||||
or not parsed.hostname
|
||||
or port is None
|
||||
or parsed.path not in {"", "/"}
|
||||
@@ -605,8 +622,7 @@ class Telemetry(BaseModel):
|
||||
or parsed.password is not None
|
||||
):
|
||||
raise ValueError(
|
||||
"must be http(s)://host:port without path, query or "
|
||||
"credentials",
|
||||
"must be https://host:port without path, query or credentials",
|
||||
)
|
||||
return f"{parsed.scheme}://{parsed.netloc}"
|
||||
|
||||
|
||||
@@ -101,10 +101,12 @@ def start(
|
||||
service_name: str,
|
||||
instance_id: str,
|
||||
config: TelemetrySettings,
|
||||
ca_file: str = "",
|
||||
exporters: Exporters | None = None,
|
||||
) -> bool:
|
||||
"""Провайдеры трасс, метрик и логов процесса. Выключено — ничего, и SDK
|
||||
не загружается.
|
||||
не загружается. `ca_file` — CA стенда (`[client_tls]`) для mTLS
|
||||
экспортёров OTLP (change `telemetry-mtls`).
|
||||
|
||||
Вызывающий до этого удаляет `OTEL_*` (`remove_otel_environment`) и
|
||||
пишет `warning`; хуки журнала ставит `src.infra.telemetry.logs`."""
|
||||
@@ -125,6 +127,7 @@ def start(
|
||||
},
|
||||
config=config,
|
||||
exporters=exporters,
|
||||
ca_file=ca_file,
|
||||
)
|
||||
meter = providers.meter_provider.get_meter(
|
||||
TELEMETRY_SCOPE,
|
||||
|
||||
+110
-8
@@ -19,13 +19,30 @@ span и журнала и экспортёры OTLP span и журнала сч
|
||||
решению выборки (`otel.sdk.span.started`, track1-telemetry-cost). SDK 1.45 включает их только
|
||||
переменной окружения в конструкторе, поэтому код ставит её на время их сборки
|
||||
(`_internal_metrics`) — внешние `OTEL_*` к этому моменту уже удалены.
|
||||
|
||||
Транспорт (change `telemetry-mtls`, design, решение 8): отправка — только по
|
||||
mTLS через TLS-шлюз Collector. Контекст TLS (`export_context`: CA стенда из
|
||||
`[client_tls]`, имя, TLS 1.3, пара identity процесса и CRL из `[telemetry]`)
|
||||
строится один раз в `build` общим построителем клиента mTLS. Сессия каждого
|
||||
экспортёра (`export_session`) получает на `https://` адаптер `requests` с этим
|
||||
контекстом (`_ContextAdapter`), который не берёт `verify` и `cert` запроса:
|
||||
иначе `verify=True` экспортёра добавил бы в контекст корни certifi, а пути
|
||||
`cert` urllib3 читал бы на каждое новое соединение (`make pki_stand` заменяет
|
||||
`crl.pem`, и bind mount `secrets` работающего контейнера отдаёт `ENOENT`).
|
||||
Экспортёры создаются без `certificate_file` и `client_*`. Адаптер опирается на
|
||||
методы `HTTPAdapter` requests 2.34 (`init_poolmanager`, `cert_verify`,
|
||||
`build_connection_pool_key_attributes`): версия закреплена `uv.lock`, возврат
|
||||
certifi и чтение файлов на соединение ловит `service-tests/unit/
|
||||
test_telemetry_tls.py`.
|
||||
"""
|
||||
|
||||
import os
|
||||
import ssl
|
||||
from collections.abc import Iterator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
# транспорт экспортёров OTLP/HTTP (зависимость opentelemetry-exporter-otlp-
|
||||
# proto-http): своя сессия без окружения
|
||||
@@ -71,8 +88,10 @@ from opentelemetry.sdk.trace.sampling import (
|
||||
TraceIdRatioBased,
|
||||
)
|
||||
from opentelemetry.trace import Tracer
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
from src.config.settings import Telemetry as TelemetrySettings
|
||||
from src.infra.tls.client import build_mtls_client_context
|
||||
from src.schemas.enums import MetricBucketsEnum
|
||||
from src.utils.constants import (
|
||||
HTTP_DURATION_BUCKETS,
|
||||
@@ -162,15 +181,34 @@ def _internal_metrics() -> Iterator[None]:
|
||||
os.environ[TELEMETRY_SDK_INTERNAL_METRICS_ENV] = previous
|
||||
|
||||
|
||||
def export_context(
|
||||
config: TelemetrySettings,
|
||||
*,
|
||||
ca_file: str,
|
||||
) -> ssl.SSLContext:
|
||||
"""Контекст TLS отправки (решение 8): только CA стенда, имя Collector,
|
||||
TLS 1.3, пара identity процесса и CRL с проверкой отзыва сертификата
|
||||
шлюза. Файлы читаются здесь, один раз при старте процесса; их проверила
|
||||
точка входа (`client_tls_problems`)."""
|
||||
return build_mtls_client_context(
|
||||
ca_file,
|
||||
cert_file=config.cert_file,
|
||||
key_file=config.key_file,
|
||||
crl_file=config.crl_file,
|
||||
)
|
||||
|
||||
|
||||
def build(
|
||||
*,
|
||||
resource: Mapping[str, Any],
|
||||
config: TelemetrySettings,
|
||||
exporters: Any | None,
|
||||
ca_file: str,
|
||||
) -> Providers:
|
||||
"""Провайдеры трасс, метрик и логов. `exporters` — получатели вместо OTLP
|
||||
(`core.Exporters`, быстрые тесты; `spans` или `logs` `None` — экспортёр
|
||||
OTLP из `[telemetry]`) или `None` — всё OTLP.
|
||||
OTLP из `[telemetry]`) или `None` — всё OTLP. Контекст TLS экспортёров
|
||||
OTLP строится один раз (`export_context`), только если они есть.
|
||||
|
||||
Порядок (design change `slo-alerts`, решение 8): сначала `MeterProvider`,
|
||||
затем процессоры span и журнала и экспортёры OTLP span и журнала с его
|
||||
@@ -180,11 +218,17 @@ def build(
|
||||
attributes = Resource(dict(resource))
|
||||
timeout_ms = config.export_timeout_seconds * 1000
|
||||
delay_ms = config.schedule_delay_seconds * 1000
|
||||
needs_otlp = (
|
||||
exporters is None
|
||||
or getattr(exporters, "spans", None) is None
|
||||
or getattr(exporters, "logs", None) is None
|
||||
)
|
||||
context = export_context(config, ca_file=ca_file) if needs_otlp else None
|
||||
|
||||
reader = (
|
||||
exporters.metrics
|
||||
if exporters is not None
|
||||
else otlp_metric_reader(config)
|
||||
else otlp_metric_reader(config, context=context)
|
||||
)
|
||||
meter_provider = MeterProvider(
|
||||
metric_readers=[reader],
|
||||
@@ -215,12 +259,14 @@ def build(
|
||||
span_exporter = otlp_span_exporter(
|
||||
config,
|
||||
meter_provider=meter_provider,
|
||||
context=context,
|
||||
)
|
||||
log_exporter = getattr(exporters, "logs", None)
|
||||
if log_exporter is None:
|
||||
log_exporter = otlp_log_exporter(
|
||||
config,
|
||||
meter_provider=meter_provider,
|
||||
context=context,
|
||||
)
|
||||
span_processor = BatchSpanProcessor(
|
||||
span_exporter,
|
||||
@@ -276,21 +322,75 @@ def build(
|
||||
)
|
||||
|
||||
|
||||
def export_session() -> requests.Session:
|
||||
class _ContextAdapter(HTTPAdapter):
|
||||
"""Адаптер `https://` сессии экспортёра: пул urllib3 с готовым контекстом
|
||||
TLS процесса; `verify` и `cert` запроса не действуют (решение 8).
|
||||
|
||||
- `init_poolmanager` — контекст в параметрах пула;
|
||||
- `build_connection_pool_key_attributes` — ключ пула: адрес и этот
|
||||
контекст, без `ca_certs` / `cert_file` / `key_file` (иначе urllib3
|
||||
загрузил бы в контекст certifi и читал бы файлы на соединение);
|
||||
- `cert_verify` — ничего: проверку задаёт контекст (CA стенда, имя,
|
||||
CRL), выключить её запросом нельзя."""
|
||||
|
||||
def __init__(self, context: ssl.SSLContext) -> None:
|
||||
self._context = context
|
||||
super().__init__()
|
||||
|
||||
def init_poolmanager(
|
||||
self,
|
||||
connections: int,
|
||||
maxsize: int,
|
||||
block: bool = False, # noqa: FBT001, FBT002
|
||||
**pool_kwargs: Any,
|
||||
) -> None:
|
||||
pool_kwargs["ssl_context"] = self._context
|
||||
super().init_poolmanager(connections, maxsize, block, **pool_kwargs)
|
||||
|
||||
def build_connection_pool_key_attributes(
|
||||
self,
|
||||
request: requests.PreparedRequest,
|
||||
verify: Any, # noqa: ARG002
|
||||
cert: Any = None, # noqa: ARG002
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
parsed = urlsplit(str(request.url))
|
||||
host_params = {
|
||||
"scheme": parsed.scheme.lower(),
|
||||
"host": parsed.hostname,
|
||||
"port": parsed.port,
|
||||
}
|
||||
return host_params, {"ssl_context": self._context}
|
||||
|
||||
def cert_verify(
|
||||
self,
|
||||
conn: Any, # noqa: ARG002
|
||||
url: str, # noqa: ARG002
|
||||
verify: Any, # noqa: ARG002
|
||||
cert: Any, # noqa: ARG002
|
||||
) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def export_session(context: ssl.SSLContext) -> requests.Session:
|
||||
"""Сессия отправки без окружения: `HTTP(S)_PROXY`, `NO_PROXY`, `.netrc`
|
||||
и `REQUESTS_CA_BUNDLE` на неё не действуют — данные идут только по адресу
|
||||
`[telemetry]` (verify S5 change `otel-telemetry`, как с `OTEL_*`)."""
|
||||
`[telemetry]` (verify S5 change `otel-telemetry`, как с `OTEL_*`). На
|
||||
`https://` — адаптер с контекстом TLS процесса (change `telemetry-mtls`)."""
|
||||
session = requests.Session()
|
||||
session.trust_env = False
|
||||
session.mount("https://", _ContextAdapter(context))
|
||||
return session
|
||||
|
||||
|
||||
# OTLP/HTTP protobuf только из `[telemetry]`: адрес, срок, без заголовков и
|
||||
# сжатия, своя сессия без прокси окружения
|
||||
# сжатия, своя сессия без прокси окружения, mTLS контекстом процесса (без
|
||||
# аргументов сертификатов экспортёра)
|
||||
|
||||
|
||||
def otlp_metric_reader(
|
||||
config: TelemetrySettings,
|
||||
*,
|
||||
context: ssl.SSLContext,
|
||||
) -> PeriodicExportingMetricReader:
|
||||
"""Читатель метрик с экспортёром OTLP; строится до `MeterProvider` и
|
||||
внутренних метрик SDK не получает."""
|
||||
@@ -302,7 +402,7 @@ def otlp_metric_reader(
|
||||
timeout=timeout,
|
||||
compression=Compression.NoCompression,
|
||||
preferred_temporality=_CUMULATIVE,
|
||||
session=export_session(),
|
||||
session=export_session(context),
|
||||
),
|
||||
export_interval_millis=config.metric_export_interval_seconds * 1000,
|
||||
export_timeout_millis=timeout * 1000,
|
||||
@@ -313,6 +413,7 @@ def otlp_span_exporter(
|
||||
config: TelemetrySettings,
|
||||
*,
|
||||
meter_provider: MeterProvider | None,
|
||||
context: ssl.SSLContext,
|
||||
) -> OTLPSpanExporter:
|
||||
"""Экспортёр span; с `meter_provider` внутри `_internal_metrics` —
|
||||
счёт отправленного и неудачных отправок (`otel.sdk.exporter.span.*`)."""
|
||||
@@ -321,7 +422,7 @@ def otlp_span_exporter(
|
||||
headers={},
|
||||
timeout=config.export_timeout_seconds,
|
||||
compression=Compression.NoCompression,
|
||||
session=export_session(),
|
||||
session=export_session(context),
|
||||
meter_provider=meter_provider,
|
||||
)
|
||||
|
||||
@@ -330,6 +431,7 @@ def otlp_log_exporter(
|
||||
config: TelemetrySettings,
|
||||
*,
|
||||
meter_provider: MeterProvider | None,
|
||||
context: ssl.SSLContext,
|
||||
) -> OTLPLogExporter:
|
||||
"""Экспортёр записей журнала; счёт — `otel.sdk.exporter.log.*`."""
|
||||
return OTLPLogExporter(
|
||||
@@ -337,6 +439,6 @@ def otlp_log_exporter(
|
||||
headers={},
|
||||
timeout=config.export_timeout_seconds,
|
||||
compression=Compression.NoCompression,
|
||||
session=export_session(),
|
||||
session=export_session(context),
|
||||
meter_provider=meter_provider,
|
||||
)
|
||||
|
||||
@@ -54,6 +54,8 @@ def start_process_telemetry(
|
||||
service_name=service_name,
|
||||
instance_id=settings.app.instance_id,
|
||||
config=config,
|
||||
# CA стенда для mTLS с шлюзом Collector (change telemetry-mtls)
|
||||
ca_file=settings.client_tls.ca_file,
|
||||
exporters=exporters,
|
||||
)
|
||||
meter = core.meter()
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
`[api_tls]` — `context.py`; протокол с allowlist identity — `protocol.py`,
|
||||
его импортирует только uvicorn по строке `PROTOCOL_IMPORT_PATH`.
|
||||
- Клиенты хранилищ (change `storage-tls`): контекст клиента и проверка
|
||||
`[client_tls]` при старте процесса — `client.py`; там же контекст клиента
|
||||
брокера с парой identity и CRL (change `messaging-telemetry-mtls`).
|
||||
`[client_tls]` при старте процесса — `client.py`; там же общий контекст
|
||||
клиента стороны mTLS с парой identity и CRL — брокер (change
|
||||
`messaging-telemetry-mtls`) и приём OTLP Collector (change `telemetry-mtls`).
|
||||
"""
|
||||
|
||||
from src.infra.tls.client import (
|
||||
@@ -16,6 +17,7 @@ from src.infra.tls.client import (
|
||||
WORKER_STORAGES,
|
||||
build_broker_context,
|
||||
build_client_context,
|
||||
build_mtls_client_context,
|
||||
client_tls_problems,
|
||||
)
|
||||
from src.infra.tls.context import (
|
||||
@@ -38,6 +40,7 @@ __all__ = [
|
||||
"api_tls_problems",
|
||||
"build_broker_context",
|
||||
"build_client_context",
|
||||
"build_mtls_client_context",
|
||||
"build_server_context",
|
||||
"client_identities",
|
||||
"client_tls_problems",
|
||||
|
||||
+55
-30
@@ -19,26 +19,39 @@ redis-py): доверие — только CA стенда из `[client_tls] ca
|
||||
`rabbitmq` клиент проверяет; без CRL или с просроченным CRL рукопожатие не
|
||||
проходит (fail-closed), CRL читается при старте процесса.
|
||||
|
||||
Приём OTLP Collector (change `telemetry-mtls`, design, решения 7–8) — тоже
|
||||
сторона mTLS: тот же построитель `build_mtls_client_context` (брокер — на нём
|
||||
же), пара identity процесса из `[telemetry]` и CRL стенда; контекст строит
|
||||
`src/infra/telemetry/sdk.py` один раз при старте.
|
||||
|
||||
`client_tls_problems` — проверка при старте точки входа, до первого
|
||||
подключения: CA задан и загружается, адрес каждого хранилища и брокера процесса
|
||||
— DNS-имя (сертификаты несут только DNS SAN, IP-адрес не пройдёт проверку
|
||||
имени); у процесса с брокером — ещё сертификат, ключ (одна пара) и CRL.
|
||||
имени); у процесса с брокером — ещё сертификат, ключ (одна пара) и CRL; у
|
||||
процесса с включённой телеметрией — то же для `[telemetry]` и хост
|
||||
`otlp_endpoint`. Модуль импортирует только `ssl` и настройки: ни `requests`,
|
||||
ни SDK (спек `observability`, «Модули SDK без телеметрии не загружаются»).
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import ssl
|
||||
from collections.abc import Iterable
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from src.config.settings import Broker, Settings
|
||||
from src.config.settings import Settings
|
||||
|
||||
# хранилища и брокер по процессам: имена секций настроек с полем host
|
||||
API_STORAGES = ("database", "cache", "s3")
|
||||
WORKER_STORAGES = ("database", "s3", "broker")
|
||||
# хранилища, брокер и Collector по процессам: имена секций настроек. У
|
||||
# хранилищ и брокера адрес — поле host, у телеметрии — хост otlp_endpoint, и
|
||||
# она проверяется только включённой (change telemetry-mtls)
|
||||
API_STORAGES = ("database", "cache", "s3", "telemetry")
|
||||
WORKER_STORAGES = ("database", "s3", "broker", "telemetry")
|
||||
CLEANER_STORAGES = ("database", "s3")
|
||||
RELAY_STORAGES = ("database", "broker")
|
||||
RELAY_STORAGES = ("database", "broker", "telemetry")
|
||||
MIGRATION_STORAGES = ("database",)
|
||||
# секция, у которой проверяются ещё файлы identity процесса и CRL
|
||||
# секции, у которых проверяются ещё файлы identity процесса и CRL
|
||||
BROKER_SECTION = "broker"
|
||||
TELEMETRY_SECTION = "telemetry"
|
||||
IDENTITY_SECTIONS = (BROKER_SECTION, TELEMETRY_SECTION)
|
||||
|
||||
|
||||
def build_client_context(ca_file: str) -> ssl.SSLContext:
|
||||
@@ -59,16 +72,16 @@ def build_client_context(ca_file: str) -> ssl.SSLContext:
|
||||
return context
|
||||
|
||||
|
||||
def build_broker_context(
|
||||
def build_mtls_client_context(
|
||||
ca_file: str,
|
||||
*,
|
||||
cert_file: str,
|
||||
key_file: str,
|
||||
crl_file: str,
|
||||
) -> ssl.SSLContext:
|
||||
"""`SSLContext` клиента брокера: построитель клиента (CA стенда, имя,
|
||||
TLS 1.3), пара identity процесса и CRL стенда с проверкой отзыва
|
||||
сертификата брокера.
|
||||
"""`SSLContext` клиента стороны mTLS (брокер, приём OTLP Collector):
|
||||
построитель клиента (CA стенда, имя, TLS 1.3), пара identity процесса и
|
||||
CRL стенда с проверкой отзыва сертификата сервера.
|
||||
|
||||
Без `crl_file` флаг проверки всё равно стоит: CRL нет — рукопожатие не
|
||||
проходит (fail-closed), а не пропускает проверку отзыва. Ошибки файлов —
|
||||
@@ -81,6 +94,10 @@ def build_broker_context(
|
||||
return context
|
||||
|
||||
|
||||
# клиент брокера — тот же построитель (change messaging-telemetry-mtls)
|
||||
build_broker_context = build_mtls_client_context
|
||||
|
||||
|
||||
def _readable(path: str) -> bool:
|
||||
try:
|
||||
with open(path, "rb") as file:
|
||||
@@ -100,29 +117,28 @@ def _pem_counts(path: str) -> dict[str, int]:
|
||||
return context.cert_store_stats()
|
||||
|
||||
|
||||
def _broker_problems(broker: Broker) -> list[str]:
|
||||
"""Файлы identity и CRL процесса с брокером: заданы, читаются, сертификат
|
||||
— сертификат, ключ — от него, CRL — CRL. Имена полей без путей."""
|
||||
def _identity_problems(section: str, fields: object) -> list[str]:
|
||||
"""Файлы identity и CRL процесса (секция брокера или телеметрии): заданы,
|
||||
читаются, сертификат — сертификат, ключ — от него, CRL — CRL. Имена
|
||||
полей без путей."""
|
||||
cert_file: str = getattr(fields, "cert_file", "")
|
||||
key_file: str = getattr(fields, "key_file", "")
|
||||
crl_file: str = getattr(fields, "crl_file", "")
|
||||
problems: list[str] = []
|
||||
cert_ok = (
|
||||
bool(broker.cert_file) and _pem_counts(broker.cert_file)["x509"] > 0
|
||||
)
|
||||
cert_ok = bool(cert_file) and _pem_counts(cert_file)["x509"] > 0
|
||||
if not cert_ok:
|
||||
problems.append("broker.cert_file")
|
||||
if not broker.key_file or not _readable(broker.key_file):
|
||||
problems.append("broker.key_file")
|
||||
problems.append(f"{section}.cert_file")
|
||||
if not key_file or not _readable(key_file):
|
||||
problems.append(f"{section}.key_file")
|
||||
elif cert_ok:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
try:
|
||||
context.load_cert_chain(
|
||||
certfile=broker.cert_file,
|
||||
keyfile=broker.key_file,
|
||||
)
|
||||
context.load_cert_chain(certfile=cert_file, keyfile=key_file)
|
||||
except (OSError, ssl.SSLError, ValueError):
|
||||
# не ключ или ключ другого сертификата
|
||||
problems.append("broker.key_file")
|
||||
if not broker.crl_file or _pem_counts(broker.crl_file)["crl"] == 0:
|
||||
problems.append("broker.crl_file")
|
||||
problems.append(f"{section}.key_file")
|
||||
if not crl_file or _pem_counts(crl_file)["crl"] == 0:
|
||||
problems.append(f"{section}.crl_file")
|
||||
return problems
|
||||
|
||||
|
||||
@@ -144,7 +160,10 @@ def client_tls_problems(
|
||||
CA (только CRL, только leaf: контекст загрузится, но доверять в нём
|
||||
нечему — verify S1); `<секция>.host` — IP-адрес вместо имени
|
||||
хранилища или брокера, к которому ходит процесс; у процесса с брокером
|
||||
— `broker.cert_file`, `broker.key_file`, `broker.crl_file`."""
|
||||
— `broker.cert_file`, `broker.key_file`, `broker.crl_file`; у процесса с
|
||||
включённой телеметрией — `telemetry.otlp_endpoint` (хост — IP-адрес),
|
||||
`telemetry.cert_file`, `telemetry.key_file`, `telemetry.crl_file`. С
|
||||
выключенной телеметрией её поля не проверяются и файлы не читаются."""
|
||||
problems: list[str] = []
|
||||
ca_file = settings.client_tls.ca_file
|
||||
if not ca_file:
|
||||
@@ -161,8 +180,14 @@ def client_tls_problems(
|
||||
problems += [
|
||||
f"{name}.host"
|
||||
for name in storages
|
||||
if _is_ip_literal(getattr(settings, name).host)
|
||||
if name != TELEMETRY_SECTION
|
||||
and _is_ip_literal(getattr(settings, name).host)
|
||||
]
|
||||
if BROKER_SECTION in storages:
|
||||
problems += _broker_problems(settings.broker)
|
||||
problems += _identity_problems(BROKER_SECTION, settings.broker)
|
||||
if TELEMETRY_SECTION in storages and settings.telemetry.enabled:
|
||||
host = urlsplit(settings.telemetry.otlp_endpoint).hostname or ""
|
||||
if not host or _is_ip_literal(host):
|
||||
problems.append(f"{TELEMETRY_SECTION}.otlp_endpoint")
|
||||
problems += _identity_problems(TELEMETRY_SECTION, settings.telemetry)
|
||||
return problems
|
||||
|
||||
Reference in New Issue
Block a user