Files
mtusi2026lab7/app/broker.py
alenchha 861e7722b5 ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
2026-11-16 10:49:13 +03:00

82 lines
3.4 KiB
Python

"""RabbitMQ topology and confirmed publishing (aio-pika).
Topology (lab7: declared by the operator in infra/rabbitmq/definitions.json; services only check it passively):
exchange attachments direct, durable
queue attachments.process quorum, durable, dead-letter -> attachments.dlx, x-delivery-limit
exchange attachments.dlx fanout, durable
queue attachments.dlq quorum, durable (poison / undeliverable messages for the operator)
Messages are persistent; the channel uses publisher confirms, so `publish` returns only after the broker
has taken responsibility for the message (written to the quorum log).
"""
import json
import logging
import ssl
import aio_pika
from aio_pika import DeliveryMode, ExchangeType, Message
from app import config
log = logging.getLogger("messenger.broker")
ROUTING_KEY = "attachment.process.v1"
def tls_context() -> ssl.SSLContext:
"""lab7: AMQPS with mutual TLS. The broker verifies our client certificate and maps its CN to the RabbitMQ user
(auth=external): api.client.messenger may only publish, worker.client.messenger may only consume."""
ctx = ssl.create_default_context(cafile=config.TLS_CA_FILE)
ctx.load_cert_chain(config.TLS_CLIENT_CERT_FILE, config.TLS_CLIENT_KEY_FILE)
return ctx
async def connect():
return await aio_pika.connect_robust(config.BROKER_URL, timeout=5, ssl_context=tls_context(),
client_properties={"connection_name": config.INSTANCE_ID})
async def get_exchange(channel):
"""Passive: the topology (exchanges, quorum queues, DLX, bindings) is created by the operator from
infra/rabbitmq/definitions.json. Services have NO configure permission, so they only check that it exists."""
return await channel.get_exchange(config.BROKER_EXCHANGE, ensure=True)
async def get_queue(channel):
return await channel.get_queue(config.BROKER_QUEUE, ensure=True)
class Publisher:
def __init__(self) -> None:
self.connection = None
self.channel = None
self.exchange = None
async def ensure(self) -> None:
if self.channel is not None and not self.channel.is_closed:
return
if self.connection is None or self.connection.is_closed:
self.connection = await connect()
self.channel = await self.connection.channel(publisher_confirms=True)
self.exchange = await get_exchange(self.channel)
async def publish(self, body: dict) -> None:
await self.ensure()
message = Message(
json.dumps(body, separators=(",", ":")).encode(),
content_type="application/json",
delivery_mode=DeliveryMode.PERSISTENT,
message_id=body["job_id"],
type=body["type"],
# Native AMQP headers duplicate the body carrier (same W3C values) for broker-side tooling.
headers={"attempt": body["attempt"], **{k: body[k] for k in ("traceparent", "tracestate") if k in body}},
)
# mandatory: an unroutable message is an error, not a silent drop; awaited confirm = broker ack.
await self.exchange.publish(message, routing_key=ROUTING_KEY, mandatory=True, timeout=5)
async def close(self) -> None:
try:
if self.connection is not None:
await self.connection.close()
except Exception:
pass
self.connection = self.channel = self.exchange = None