forked from mtusi2026/mtusi2026lab7
ЛР 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.
This commit is contained in:
+100
@@ -0,0 +1,100 @@
|
||||
"""Transactional outbox relay (runs inside every API replica; SKIP LOCKED keeps replicas from double work).
|
||||
|
||||
Rows are locked while they are published; `published_at` is set in the same transaction only after the
|
||||
broker confirmed the message. A crash between confirm and COMMIT republishes the row: duplicates are
|
||||
expected and harmless (the worker's claim is idempotent). A crash between the upload COMMIT and publish
|
||||
leaves an unpublished row that any replica picks up within OUTBOX_POLL_SECONDS.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from app import config, telemetry
|
||||
|
||||
log = logging.getLogger("messenger.outbox")
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self, db, publisher) -> None:
|
||||
self.db = db
|
||||
self.publisher = publisher
|
||||
self.wake = asyncio.Event()
|
||||
self.broker_ok = False
|
||||
self.published = 0
|
||||
|
||||
def notify(self) -> None:
|
||||
self.wake.set()
|
||||
|
||||
async def run_once(self) -> int:
|
||||
sent, failure = 0, None
|
||||
async with self.db.connection() as conn:
|
||||
async with conn.transaction():
|
||||
cur = await conn.execute(
|
||||
"SELECT id, payload FROM outbox WHERE published_at IS NULL AND available_at <= clock_timestamp()"
|
||||
" ORDER BY available_at, id LIMIT %s FOR UPDATE SKIP LOCKED",
|
||||
(config.OUTBOX_BATCH,),
|
||||
)
|
||||
for row in await cur.fetchall():
|
||||
try:
|
||||
await self.publish(row["payload"])
|
||||
except Exception as exc:
|
||||
# Keep what was already confirmed: commit those rows, record the error, stop the batch.
|
||||
await conn.execute(
|
||||
"UPDATE outbox SET publish_attempts = publish_attempts + 1, last_error = %s WHERE id = %s",
|
||||
(type(exc).__name__, row["id"]),
|
||||
)
|
||||
failure = exc
|
||||
break
|
||||
await conn.execute(
|
||||
"UPDATE outbox SET published_at = clock_timestamp(), publish_attempts = publish_attempts + 1"
|
||||
" WHERE id = %s",
|
||||
(row["id"],),
|
||||
)
|
||||
sent += 1
|
||||
self.published += sent
|
||||
if failure is not None:
|
||||
raise failure
|
||||
return sent
|
||||
|
||||
async def publish(self, payload: dict) -> None:
|
||||
"""PRODUCER span, child of the context stored with the job (upload request or failed attempt);
|
||||
the message then carries the producer's own traceparent, so the consumer becomes its child."""
|
||||
attrs = {"messaging.system": "rabbitmq", "messaging.operation.type": "publish",
|
||||
"messaging.destination.name": config.BROKER_EXCHANGE, "messaging.message.id": payload["job_id"],
|
||||
"messenger.job.attempt": payload["attempt"], "messenger.attachment_id": payload["attachment_id"]}
|
||||
with telemetry.span(config.BROKER_QUEUE + " publish", kind=SpanKind.PRODUCER,
|
||||
context=telemetry.extract(payload), attributes=attrs):
|
||||
body = {k: v for k, v in payload.items() if k not in ("traceparent", "tracestate")}
|
||||
body.update(telemetry.inject())
|
||||
await self.publisher.publish(body)
|
||||
|
||||
async def loop(self) -> None:
|
||||
delay = config.OUTBOX_POLL_SECONDS
|
||||
while True:
|
||||
try:
|
||||
await asyncio.wait_for(self.wake.wait(), delay)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
self.wake.clear()
|
||||
try:
|
||||
while await self.run_once() == config.OUTBOX_BATCH:
|
||||
pass
|
||||
if not self.broker_ok:
|
||||
log.info("outbox_relay_resumed: broker reachable")
|
||||
self.broker_ok = True
|
||||
delay = config.OUTBOX_POLL_SECONDS
|
||||
except Exception as exc:
|
||||
if self.broker_ok:
|
||||
log.warning("outbox_relay_paused: %s; jobs stay in outbox", type(exc).__name__)
|
||||
self.broker_ok = False
|
||||
await self.publisher.close()
|
||||
delay = min(10.0, max(delay * 2, 1.0))
|
||||
|
||||
async def cleanup(self) -> int:
|
||||
async with self.db.connection() as conn:
|
||||
cur = await conn.execute(
|
||||
"DELETE FROM outbox WHERE published_at < clock_timestamp() - make_interval(secs => %s)",
|
||||
(config.OUTBOX_RETENTION_SECONDS,),
|
||||
)
|
||||
return cur.rowcount
|
||||
Reference in New Issue
Block a user