lab7: TLS ко всем зависимостям и телеметрии; раздельные роли PostgreSQL (GRANT по коду), ACL Valkey, AMQPS, HTTPS S3, mTLS Collector/Prometheus/Loki/Tempo/Grafana

This commit is contained in:
Alexey Bodanyuk
2026-11-27 16:29:09 +03:00
parent f36da97951
commit 93f4ed1013
28 changed files with 621 additions and 201 deletions
+10
View File
@@ -21,6 +21,7 @@ from __future__ import annotations
import datetime as dt
import json
import re
import ssl
import uuid
EXCHANGE = "messenger.jobs"
@@ -28,6 +29,15 @@ QUEUE = "messenger.attachment-jobs"
DLX = "messenger.jobs.dlx"
DLQ = "messenger.attachment-jobs.dlq"
ROUTING_KEY = "attachment.process.v1"
def ssl_context(settings) -> ssl.SSLContext | None:
"""Lab 7: amqps:// -> TLS context that verifies the broker (internal CA + hostname `broker`).
A plain amqp:// URL gets None and is refused by the broker anyway (its TCP listener is off)."""
if not settings.broker_url.startswith("amqps://"):
return None
from .tls import client_context
return client_context(settings.tls_ca_file)
JOB_TYPE = "attachment.process.v1"
MAX_MESSAGE_BYTES = 4096
+4
View File
@@ -157,6 +157,9 @@ class Settings:
# Lab 7: TLS of the API listener (mTLS, src/messenger/tls.py) and the loopback health port.
tls_cert_file: str = ""
tls_key_file: str = ""
# CA that every OUTGOING TLS connection verifies the server with (internal CA): S3, Valkey,
# RabbitMQ (PostgreSQL: sslrootcert in DATABASE_URL, OTLP: OTEL_EXPORTER_OTLP_CERTIFICATE).
tls_ca_file: str = ""
tls_client_ca_file: str = ""
health_port: int = 0
@@ -307,6 +310,7 @@ def s3_settings(*, credentials_required: bool = True) -> dict:
janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.0, 3600.0),
fault_points=faults,
fault_values=fault_values,
tls_ca_file=_path("TLS_CA_FILE"),
)
+1 -1
View File
@@ -58,7 +58,7 @@ class Relay:
async def connect(self) -> None:
self.connection = await aio_pika.connect(
self.settings.broker_url, timeout=5,
self.settings.broker_url, timeout=5, ssl_context=broker.ssl_context(self.settings),
client_properties={"connection_name": "relay@" + self.settings.instance_id})
self.lost = service.watch_connection(self.connection)
# Confirm mode: every publish() waits for basic.ack of the broker (message in the quorum log).
+4 -1
View File
@@ -18,6 +18,7 @@ from __future__ import annotations
import asyncio
import os
import ssl
import sys
import time
import urllib.error
@@ -36,8 +37,10 @@ def say(text: str) -> None:
def anonymous_status(url: str) -> int:
"""HTTP status of an UNSIGNED request (what anyone on the network could do)."""
ca = os.environ.get("TLS_CA_FILE", "").strip() or None
context = ssl.create_default_context(cafile=ca) if url.startswith("https://") else None
try:
with urllib.request.urlopen(url, timeout=3) as response:
with urllib.request.urlopen(url, timeout=3, context=context) as response:
return response.status
except urllib.error.HTTPError as exc:
return exc.code
+7
View File
@@ -18,6 +18,7 @@ Two interchangeable stores (SESSION_STORE):
from __future__ import annotations
import asyncio
import ssl
import datetime as dt
import hashlib
import json
@@ -107,12 +108,18 @@ class ValkeySessionStore:
def __init__(self, settings: Settings):
self.timeout = settings.cache_timeout_seconds
tls = {}
if settings.cache_url.startswith("rediss://"):
# Lab 7: TLS to Valkey, server verified by the internal CA AND hostname (SAN valkey).
tls = {"ssl_ca_certs": settings.tls_ca_file or None, "ssl_cert_reqs": "required",
"ssl_check_hostname": True, "ssl_min_version": ssl.TLSVersion.TLSv1_2}
self.client = Redis.from_url(
settings.cache_url,
socket_timeout=self.timeout,
socket_connect_timeout=self.timeout,
retry=Retry(NoBackoff(), 0), # no hidden retries: a failure is reported at once
decode_responses=False,
**tls,
)
def _key(self, token: str) -> str:
+4 -1
View File
@@ -68,6 +68,7 @@ class Storage:
self._region = settings.s3_region
self._access_key = access_key or settings.s3_access_key_id
self._secret_key = secret_key or settings.s3_secret_access_key
self._ca_file = settings.tls_ca_file
self._config = AioConfig(
connect_timeout=settings.s3_connect_timeout_seconds,
read_timeout=settings.s3_timeout_seconds,
@@ -86,7 +87,9 @@ class Storage:
session = get_session()
self._client = await self._stack.enter_async_context(session.create_client(
"s3", endpoint_url=self._endpoint, region_name=self._region,
aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, config=self._config))
aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, config=self._config,
# Lab 7: https endpoint, chain AND hostname verified against the internal CA only.
verify=self._ca_file or True))
async def close(self) -> None:
if self._stack is not None:
+1 -1
View File
@@ -74,7 +74,7 @@ class Worker:
# ---------------------------------------------------------------- broker
async def connect(self) -> None:
self.connection = await aio_pika.connect(
self.settings.broker_url, timeout=5,
self.settings.broker_url, timeout=5, ssl_context=broker.ssl_context(self.settings),
client_properties={"connection_name": "worker@" + self.name})
self.lost = service.watch_connection(self.connection)
self.channel = await self.connection.channel()