feat: import lab 7 security implementation
This commit is contained in:
+386
@@ -0,0 +1,386 @@
|
||||
"""RabbitMQ: издатель заданий (relay) и потребитель (worker), aio-pika.
|
||||
|
||||
Очередь одна — `<имя базы>.attachment-jobs`, quorum: сообщения хранятся
|
||||
на диске брокера и переживают его рестарт с volume. Лаба 7 (перенос
|
||||
messaging-telemetry-mtls): объявляет её relay при каждом соединении, worker
|
||||
только проверяет пассивно — права объявить и удалить очередь у identity
|
||||
`worker` нет. Её же создают определения брокера на старте
|
||||
(`infra/rabbitmq/start.sh`), поэтому порядок старта relay и worker
|
||||
по-прежнему не важен; нет очереди — у worker та же недоступность брокера
|
||||
(запись, пауза, повтор).
|
||||
|
||||
Соединение — только mTLS (`open_connection`): контекст `broker_context`
|
||||
(`src/client_tls.py`: CA стенда, имя, TLS 1.3, CRL, пара identity) строит
|
||||
точка входа один раз при старте, вход — механизмом EXTERNAL: имя
|
||||
пользователя брокер берёт из DNS SAN сертификата, логина и пароля нет. Отказ
|
||||
рукопожатия, проверки сертификата и входа (`ssl.SSLError`,
|
||||
`ProbableAuthenticationError`, `ACCESS_REFUSED`) — прежний путь
|
||||
недоступности.
|
||||
|
||||
Издатель: канал с publisher confirms и `mandatory`; пачка публикуется
|
||||
конвейером, а вызов возвращается, только когда брокер подтвердил каждое
|
||||
сообщение (`basic.ack`). Любая ошибка — `BrokerUnavailable`, соединение
|
||||
сбрасывается и в следующий раз открывается заново. Подтверждение
|
||||
публикации — это «брокер принял», а не «работа сделана»: последнее
|
||||
говорит только ack потребителя.
|
||||
|
||||
Тело сообщения — `contracts/jobs.schema.json`: id задания и вложения,
|
||||
версия pipeline, номер попытки. Байтов, ключей S3 и имени файла нет.
|
||||
W3C-контекст (лаба 6) — в заголовках AMQP `traceparent`/`tracestate`, а не
|
||||
в теле: тело остаётся тем же для потребителей без телеметрии.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import ssl
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
import aio_pika
|
||||
from aio_pika.abc import AbstractIncomingMessage
|
||||
|
||||
from src import telemetry
|
||||
from src.clock import from_rfc3339, to_rfc3339
|
||||
from src.config import Broker as BrokerSettings
|
||||
from src.constants import (
|
||||
BROKER_TLS_SHUTDOWN_TIMEOUT,
|
||||
JOB_SCHEMA_VERSION,
|
||||
JOB_TYPE,
|
||||
)
|
||||
from src.domain import JobMessage
|
||||
from src.log import get_logger
|
||||
|
||||
log = get_logger(__name__)
|
||||
|
||||
_QUEUE_ARGUMENTS = {"x-queue-type": "quorum"}
|
||||
_FIELDS = {
|
||||
"schema_version",
|
||||
"job_id",
|
||||
"type",
|
||||
"attachment_id",
|
||||
"pipeline_version",
|
||||
"attempt",
|
||||
"created_at",
|
||||
"traceparent",
|
||||
"tracestate",
|
||||
}
|
||||
|
||||
|
||||
class BrokerUnavailable(Exception):
|
||||
"""Брокер не принял сообщение, не подтвердил его вовремя или недоступен."""
|
||||
|
||||
|
||||
class BadMessage(ValueError):
|
||||
"""Пришёл JSON, который не проходит схему из contracts (jobs.schema.json)."""
|
||||
|
||||
|
||||
def queue_name(namespace: str) -> str:
|
||||
return f"{namespace}.attachment-jobs"
|
||||
|
||||
|
||||
class _TlsConnection(aio_pika.Connection):
|
||||
"""Соединение aio-pika с ограниченным закрытием TLS: `ssl_shutdown_timeout`
|
||||
уходит через aiormq в `asyncio.open_connection`. Без него закрытие
|
||||
соединения с замороженным брокером ждало бы close_notify 30 с (asyncio по
|
||||
умолчанию), а срок закрытия `asyncio.timeout` aiormq к этому ожиданию не
|
||||
пропускает — worker не уложился бы в `stop_grace_period`."""
|
||||
|
||||
def __init__(self, url: Any, **kwargs: Any) -> None:
|
||||
super().__init__(url, **kwargs)
|
||||
self.kwargs["ssl_shutdown_timeout"] = BROKER_TLS_SHUTDOWN_TIMEOUT
|
||||
|
||||
|
||||
def encode(message: JobMessage) -> bytes:
|
||||
body = {
|
||||
"schema_version": JOB_SCHEMA_VERSION,
|
||||
"job_id": str(message.job_id),
|
||||
"type": JOB_TYPE,
|
||||
"attachment_id": str(message.attachment_id),
|
||||
"pipeline_version": message.pipeline_version,
|
||||
"attempt": message.attempt,
|
||||
"created_at": to_rfc3339(message.created_at),
|
||||
}
|
||||
return json.dumps(body, separators=(",", ":")).encode()
|
||||
|
||||
|
||||
def _positive(value: Any) -> int:
|
||||
if type(value) is not int or value < 1:
|
||||
raise BadMessage("integer >= 1 expected")
|
||||
return value
|
||||
|
||||
|
||||
def decode(body: bytes) -> JobMessage:
|
||||
"""Строгий разбор: лишнее поле, чужой тип или версия — `BadMessage`."""
|
||||
try:
|
||||
data = json.loads(body)
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
raise BadMessage("not JSON") from None
|
||||
if not isinstance(data, dict) or not set(data) <= _FIELDS:
|
||||
raise BadMessage("unexpected fields")
|
||||
if data.get("schema_version") != JOB_SCHEMA_VERSION or data.get("type") != JOB_TYPE:
|
||||
raise BadMessage("unknown job type")
|
||||
try:
|
||||
created_at: datetime = from_rfc3339(data["created_at"])
|
||||
return JobMessage(
|
||||
job_id=UUID(data["job_id"]),
|
||||
attachment_id=UUID(data["attachment_id"]),
|
||||
pipeline_version=_positive(data["pipeline_version"]),
|
||||
attempt=_positive(data["attempt"]),
|
||||
created_at=created_at,
|
||||
)
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise BadMessage(str(exc)) from None
|
||||
|
||||
|
||||
def trace_headers(message: AbstractIncomingMessage) -> dict[str, str]:
|
||||
"""traceparent/tracestate из заголовков AMQP (aio-pika отдаёт bytes или str)."""
|
||||
found: dict[str, str] = {}
|
||||
for key in ("traceparent", "tracestate"):
|
||||
value = (message.headers or {}).get(key)
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode("ascii", "replace")
|
||||
if isinstance(value, str) and value:
|
||||
found[key] = value
|
||||
return found
|
||||
|
||||
|
||||
async def open_connection(
|
||||
settings: BrokerSettings, *, context: ssl.SSLContext
|
||||
) -> aio_pika.abc.AbstractConnection:
|
||||
"""Соединение по mTLS identity процесса (`context` — `broker_context`),
|
||||
вход EXTERNAL без логина и пароля. Ошибка рукопожатия и входа уходит
|
||||
вызывающему."""
|
||||
return await aio_pika.connect(
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
virtualhost=settings.vhost,
|
||||
ssl=True,
|
||||
ssl_context=context,
|
||||
timeout=settings.timeout,
|
||||
connection_class=_TlsConnection,
|
||||
# параметры запроса URL aiormq: механизм входа и heartbeat
|
||||
auth="external",
|
||||
heartbeat=settings.heartbeat,
|
||||
)
|
||||
|
||||
|
||||
async def _declare(channel: aio_pika.abc.AbstractChannel, name: str) -> Any:
|
||||
"""Активное объявление (relay): право `configure` на свою очередь."""
|
||||
return await channel.declare_queue(
|
||||
name, durable=True, arguments=_QUEUE_ARGUMENTS, timeout=10
|
||||
)
|
||||
|
||||
|
||||
async def _check(channel: aio_pika.abc.AbstractChannel, name: str) -> Any:
|
||||
"""Пассивная проверка (worker): прав не требует; нет очереди — ошибка
|
||||
канала, то есть та же недоступность брокера."""
|
||||
return await channel.declare_queue(name, passive=True, timeout=10)
|
||||
|
||||
|
||||
class JobPublisher:
|
||||
"""Публикация пачки с подтверждением; одно ленивое соединение."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: BrokerSettings,
|
||||
*,
|
||||
namespace: str,
|
||||
context: ssl.SSLContext,
|
||||
) -> None:
|
||||
self._settings = settings
|
||||
self._context = context
|
||||
self.queue = queue_name(namespace)
|
||||
self._connection: aio_pika.abc.AbstractConnection | None = None
|
||||
self._channel: aio_pika.abc.AbstractChannel | None = None
|
||||
self._queue: Any = None
|
||||
|
||||
async def _ready(self) -> None:
|
||||
if self._channel is not None and not self._channel.is_closed:
|
||||
return
|
||||
await self.close()
|
||||
self._connection = await open_connection(self._settings, context=self._context)
|
||||
# on_return_raises: сообщение, которое некуда положить, — ошибка,
|
||||
# а не молча выброшенное
|
||||
self._channel = await self._connection.channel(
|
||||
publisher_confirms=True, on_return_raises=True
|
||||
)
|
||||
self._queue = await _declare(self._channel, self.queue)
|
||||
|
||||
async def _publish_one(self, exchange: Any, message: JobMessage) -> None:
|
||||
"""Одно сообщение под producer span (лаба 6): родитель — контекст
|
||||
загрузки из строки задания, в заголовки уходит контекст этого span."""
|
||||
stored = {
|
||||
key: value
|
||||
for key, value in (
|
||||
("traceparent", message.traceparent),
|
||||
("tracestate", message.tracestate),
|
||||
)
|
||||
if value
|
||||
}
|
||||
attributes = {
|
||||
"messaging.system": "rabbitmq",
|
||||
"messaging.operation.type": "send",
|
||||
"messaging.destination.name": self.queue,
|
||||
"messenger.job.id": str(message.job_id),
|
||||
"messenger.attachment.id": str(message.attachment_id),
|
||||
"messenger.job.attempt": message.attempt,
|
||||
}
|
||||
with telemetry.producer_span(
|
||||
f"publish {self.queue}", stored, attributes
|
||||
) as headers:
|
||||
await exchange.publish(
|
||||
aio_pika.Message(
|
||||
encode(message),
|
||||
content_type="application/json",
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=str(message.job_id),
|
||||
type=JOB_TYPE,
|
||||
headers=headers or None,
|
||||
),
|
||||
routing_key=self.queue,
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
async def publish(self, messages: Sequence[JobMessage]) -> None:
|
||||
try:
|
||||
async with asyncio.timeout(self._settings.timeout):
|
||||
await self._ready()
|
||||
assert self._channel is not None
|
||||
exchange = self._channel.default_exchange
|
||||
await asyncio.gather(
|
||||
*(self._publish_one(exchange, message) for message in messages)
|
||||
)
|
||||
except Exception as exc:
|
||||
log.warning(
|
||||
"broker publish failed queue=%s messages=%d error_type=%s",
|
||||
self.queue,
|
||||
len(messages),
|
||||
type(exc).__name__,
|
||||
)
|
||||
await self.close()
|
||||
raise BrokerUnavailable from exc
|
||||
|
||||
async def ready_messages(self) -> int:
|
||||
"""Сообщений, ждущих потребителя (без выданных и неподтверждённых)."""
|
||||
try:
|
||||
async with asyncio.timeout(self._settings.timeout):
|
||||
await self._ready()
|
||||
assert self._channel is not None
|
||||
queue = await self._channel.declare_queue(self.queue, passive=True)
|
||||
return int(queue.declaration_result.message_count or 0)
|
||||
except Exception as exc:
|
||||
await self.close()
|
||||
raise BrokerUnavailable from exc
|
||||
|
||||
async def close(self) -> None:
|
||||
connection, self._connection, self._channel = self._connection, None, None
|
||||
if connection is not None and not connection.is_closed:
|
||||
try:
|
||||
async with asyncio.timeout(self._settings.timeout):
|
||||
await connection.close()
|
||||
except Exception as exc:
|
||||
log.debug("broker close failed error_type=%s", type(exc).__name__)
|
||||
|
||||
|
||||
class JobConsumer:
|
||||
"""Потребитель: свои соединение и канал, `prefetch` неподтверждённых."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: BrokerSettings,
|
||||
*,
|
||||
namespace: str,
|
||||
prefetch: int,
|
||||
context: ssl.SSLContext,
|
||||
) -> None:
|
||||
self._settings = settings
|
||||
self._context = context
|
||||
self.queue = queue_name(namespace)
|
||||
self._prefetch = prefetch
|
||||
self._connection: aio_pika.abc.AbstractConnection | None = None
|
||||
|
||||
async def consume(
|
||||
self,
|
||||
deliver: Callable[[AbstractIncomingMessage], Awaitable[None]],
|
||||
*,
|
||||
stop: asyncio.Event,
|
||||
) -> None:
|
||||
"""Пока не `stop`: подключиться, подписаться, ждать обрыва. Обрыв —
|
||||
пауза и заново; сообщения без ack брокер выдаст снова.
|
||||
|
||||
По `stop` подписка снимается, а соединение остаётся открытым:
|
||||
начатые задания ещё подтвердят свои сообщения. Закрывает `close()`.
|
||||
"""
|
||||
pause = 1.0
|
||||
while not stop.is_set():
|
||||
try:
|
||||
connection = await open_connection(
|
||||
self._settings, context=self._context
|
||||
)
|
||||
except Exception as exc:
|
||||
log.warning(
|
||||
"broker connect failed host=%s port=%d error_type=%s retry_in=%gs",
|
||||
self._settings.host,
|
||||
self._settings.port,
|
||||
type(exc).__name__,
|
||||
pause,
|
||||
)
|
||||
await _sleep_or_stop(stop, pause)
|
||||
pause = min(pause * 2, 15.0)
|
||||
continue
|
||||
self._connection = connection
|
||||
pause = 1.0
|
||||
lost = asyncio.Event()
|
||||
connection.close_callbacks.add(lambda *_, lost=lost: lost.set())
|
||||
try:
|
||||
channel = await connection.channel()
|
||||
await channel.set_qos(prefetch_count=self._prefetch)
|
||||
queue = await _check(channel, self.queue)
|
||||
tag = await queue.consume(deliver)
|
||||
log.info(
|
||||
"broker consuming queue=%s prefetch=%d", self.queue, self._prefetch
|
||||
)
|
||||
await _first(stop.wait(), lost.wait())
|
||||
if not lost.is_set():
|
||||
await queue.cancel(tag)
|
||||
return
|
||||
log.warning("broker connection lost queue=%s", self.queue)
|
||||
except Exception as exc:
|
||||
log.warning(
|
||||
"broker consume failed queue=%s error_type=%s",
|
||||
self.queue,
|
||||
type(exc).__name__,
|
||||
)
|
||||
await self.close()
|
||||
await _sleep_or_stop(stop, pause)
|
||||
|
||||
async def close(self) -> None:
|
||||
connection, self._connection = self._connection, None
|
||||
if connection is not None and not connection.is_closed:
|
||||
await _close_quietly(connection)
|
||||
|
||||
|
||||
async def _close_quietly(connection: aio_pika.abc.AbstractConnection) -> None:
|
||||
try:
|
||||
async with asyncio.timeout(5):
|
||||
await connection.close()
|
||||
except Exception as exc:
|
||||
log.debug("broker close failed error_type=%s", type(exc).__name__)
|
||||
|
||||
|
||||
async def _first(*waits: Awaitable[Any]) -> None:
|
||||
tasks = [asyncio.ensure_future(w) for w in waits]
|
||||
try:
|
||||
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
finally:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
|
||||
|
||||
async def _sleep_or_stop(stop: asyncio.Event, seconds: float) -> None:
|
||||
try:
|
||||
await asyncio.wait_for(stop.wait(), timeout=seconds)
|
||||
except TimeoutError:
|
||||
return
|
||||
Reference in New Issue
Block a user