ЛР 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:
alenchha
2026-11-16 10:49:13 +03:00
parent 20afc2c790
commit 861e7722b5
116 changed files with 14522 additions and 63 deletions
Executable
+126
View File
@@ -0,0 +1,126 @@
#!/bin/sh
# OpenBao operator tool. Unseal shares and the root token live ONLY in secrets/operator/ (git-ignored, 0600) and
# are never printed. Values are passed to the CLI through the environment of `docker compose exec`, not argv.
#
# scripts/bao.sh init initialise once: 3 unseal shares, threshold 2; then unseal
# scripts/bao.sh unseal unseal after every OpenBao restart (operator action; the API does not do it)
# scripts/bao.sh bootstrap KV v2 mount, policies, cert auth roles, service secrets (idempotent)
# scripts/bao.sh status sealed/initialised state
# scripts/bao.sh rotate-worker-db new password for DB role app_worker: PostgreSQL + OpenBao (level 4)
# scripts/bao.sh seal seal OpenBao (incident drill: services keep cached secrets, new ones must wait)
#
# Production note: each share would go to a different person; here one operator holds them on one host.
set -eu
cd "$(dirname "$0")/.."
OP=secrets/operator
BS=secrets/bootstrap
ENVS="-e BAO_ADDR=https://127.0.0.1:8200 -e BAO_CACERT=/run/secrets/ca.crt"
bao() { docker compose exec -T $ENVS openbao bao "$@"; }
bao_root() { BAO_TOKEN="$(cat "$OP/root-token")" docker compose exec -T $ENVS -e BAO_TOKEN openbao bao "$@"; }
wait_up() {
i=0
until docker compose exec -T $ENVS openbao sh -c 'bao status >/dev/null 2>&1; [ $? -ne 1 ]'; do
i=$((i + 1)); [ $i -gt 60 ] && { echo "openbao not reachable" >&2; exit 1; }; sleep 1
done
}
sealed() { ! docker compose exec -T $ENVS openbao bao status >/dev/null 2>&1; }
unseal() {
wait_up
if ! sealed; then echo "openbao: already unsealed"; return 0; fi
for n in 1 2; do
UNSEAL_KEY="$(cat "$OP/unseal-$n")" docker compose exec -T $ENVS -e UNSEAL_KEY openbao \
sh -c 'bao operator unseal "$UNSEAL_KEY" >/dev/null'
done
sealed && { echo "openbao: still sealed" >&2; exit 1; }
echo "openbao: unsealed with 2 of 3 operator shares"
}
init() {
wait_up
if bao status -format=json 2>/dev/null | python3 -c 'import json,sys;sys.exit(0 if json.load(sys.stdin)["initialized"] else 1)'; then
echo "openbao: already initialised"; unseal; return 0
fi
umask 077; mkdir -p "$OP"
bao operator init -key-shares=3 -key-threshold=2 -format=json | python3 -c '
import json, sys
d = json.load(sys.stdin)
for i, key in enumerate(d["unseal_keys_b64"], 1):
open("'"$OP"'/unseal-%d" % i, "w").write(key)
open("'"$OP"'/root-token", "w").write(d["root_token"])
'
chmod 600 "$OP"/*
echo "openbao: initialised; 3 shares and root token stored in $OP/ (0600, not printed)"
unseal
}
bootstrap() {
unseal
bao_root secrets list -format=json | grep -q '"messenger/"' || bao_root secrets enable -path=messenger -version=2 kv
bao_root auth list -format=json | grep -q '"cert/"' || bao_root auth enable cert
for p in messenger-api messenger-worker; do
docker compose exec -T openbao sh -c "cat > /tmp/$p.hcl" < "infra/openbao/policies/$p.hcl"
bao_root policy write "$p" "/tmp/$p.hcl" >/dev/null
done
docker compose exec -T openbao sh -c 'cp /run/secrets/ca.crt /tmp/ca.crt'
# Identity = client certificate chained to the lab root CA AND an exact common name. Short-lived tokens.
bao_root write auth/cert/certs/api certificate=@/tmp/ca.crt allowed_common_names=api.client.messenger \
token_policies=messenger-api token_ttl=15m token_max_ttl=1h >/dev/null
bao_root write auth/cert/certs/worker certificate=@/tmp/ca.crt allowed_common_names=worker.client.messenger \
token_policies=messenger-worker token_ttl=15m token_max_ttl=1h >/dev/null
kv_api
kv_worker
echo "openbao: mount messenger/ (kv v2), policies messenger-api/worker, cert roles api/worker, secrets written"
}
# KV values are read from secrets/bootstrap and passed through stdin as JSON (never on a command line).
kv_api() {
python3 - "$BS" <<'PY' | bao_root kv put -mount=messenger api - >/dev/null
import json, sys
b = sys.argv[1]
r = lambda n: open("%s/%s" % (b, n)).read().strip()
print(json.dumps({
"database_url": "postgresql://app_api:%s@postgres:5432/messenger" % r("db_api_password"),
"s3_access_key_id": r("s3_api_access_key"), "s3_secret_access_key": r("s3_api_secret_key"),
"cache_url": "rediss://api:%s@valkey:6379/0" % r("valkey_api_password")}))
PY
}
kv_worker() {
python3 - "$BS" <<'PY' | bao_root kv put -mount=messenger worker - >/dev/null
import json, sys
b = sys.argv[1]
r = lambda n: open("%s/%s" % (b, n)).read().strip()
print(json.dumps({
"database_url": "postgresql://app_worker:%s@postgres:5432/messenger" % r("db_worker_password"),
"s3_access_key_id": r("s3_worker_access_key"), "s3_secret_access_key": r("s3_worker_secret_key")}))
PY
}
rotate_worker_db() {
unseal
umask 077
python3 -c "import secrets;print(secrets.token_urlsafe(24),end='')" > "$BS/db_worker_password.new"
chmod 644 "$BS/db_worker_password.new"
# 1) PostgreSQL first (open connections keep working), 2) OpenBao: the worker picks up the new version.
NEWPW="$(cat "$BS/db_worker_password.new")" docker compose exec -T -e NEWPW postgres sh -c \
'psql -v ON_ERROR_STOP=1 -q -U messenger -d messenger -v pw="$NEWPW" <<SQL
ALTER ROLE app_worker PASSWORD :'"'"'pw'"'"';
SQL'
mv "$BS/db_worker_password.new" "$BS/db_worker_password"
kv_worker
echo "rotated: app_worker password changed in PostgreSQL and OpenBao (messenger/worker, new KV version)"
}
case "${1:-status}" in
init) init ;;
unseal) unseal ;;
bootstrap) bootstrap ;;
rotate-worker-db) rotate_worker_db ;;
seal) wait_up; bao_root operator seal >/dev/null; echo "openbao: sealed" ;;
status) wait_up; bao status | grep -E "Initialized|Sealed|Version|Storage" ;;
*) echo "usage: $0 init|unseal|bootstrap|status|rotate-worker-db|seal" >&2; exit 2 ;;
esac
+244
View File
@@ -0,0 +1,244 @@
#!/usr/bin/env python3
"""Generates infra/grafana/dashboards/messenger.json (provisioned into Grafana at startup).
The JSON is committed; this script only keeps it readable/editable. Run: python3 scripts/gen_dashboard.py
Every expression uses metric names that really exist in Prometheus (see REPORT.md, "Схема сигналов").
"""
import json
from pathlib import Path
OUT = Path(__file__).resolve().parents[1] / "infra/grafana/dashboards/messenger.json"
PROM = {"type": "prometheus", "uid": "prometheus"}
LOKI = {"type": "loki", "uid": "loki"}
TEMPO = {"type": "tempo", "uid": "tempo"}
API = 'service_name="messenger-api"'
HTTP = "http_server_request_duration_seconds"
_ids = iter(range(1, 1000))
def target(expr, legend="", ref="A", instant=False):
return {"datasource": PROM, "expr": expr, "legendFormat": legend, "refId": ref, "range": not instant,
"instant": instant}
def ts(title, targets, unit="short", x=0, y=0, w=12, h=8, desc="", stack=False, extra=None):
panel = {
"id": next(_ids), "type": "timeseries", "title": title, "description": desc, "datasource": PROM,
"gridPos": {"x": x, "y": y, "w": w, "h": h},
"fieldConfig": {"defaults": {"unit": unit, "custom": {"lineWidth": 1, "fillOpacity": 10,
"stacking": {"mode": "normal" if stack else "none"},
"showPoints": "never"}},
"overrides": []},
"options": {"legend": {"displayMode": "table", "placement": "bottom", "calcs": ["lastNotNull", "max"]},
"tooltip": {"mode": "multi", "sort": "desc"}},
"targets": [target(*t) if isinstance(t, tuple) else t for t in targets],
}
if extra:
panel["fieldConfig"]["defaults"].update(extra)
return panel
def stat(title, expr, unit, x, y, w=4, h=4, desc="", thresholds=None, decimals=None):
steps = thresholds or [{"color": "green", "value": None}]
panel = {
"id": next(_ids), "type": "stat", "title": title, "description": desc, "datasource": PROM,
"gridPos": {"x": x, "y": y, "w": w, "h": h},
"fieldConfig": {"defaults": {"unit": unit, "thresholds": {"mode": "absolute", "steps": steps}},
"overrides": []},
"options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False},
"colorMode": "value", "graphMode": "area", "textMode": "auto"},
"targets": [target(expr, title)],
}
if decimals is not None:
panel["fieldConfig"]["defaults"]["decimals"] = decimals
return panel
def row(title, y):
return {"id": next(_ids), "type": "row", "title": title, "collapsed": False, "gridPos": {"x": 0, "y": y, "w": 24, "h": 1},
"panels": []}
def q(p, expr_inner):
return "histogram_quantile(%s, %s)" % (p, expr_inner)
panels = []
y = 0
# ------------------------------------------------------------------ SLO and alerts
panels.append(row("SLO (окно 30 мин) и алерты", y)); y += 1
red_yellow = lambda bad, warn: [{"color": "red", "value": None}, {"color": "yellow", "value": bad},
{"color": "green", "value": warn}]
panels += [
stat("Доступность (SLO 99%)", "messenger:slo_availability:ratio30m", "percentunit", 0, y,
desc="1 - 5xx/все бизнес-запросы messenger-api за 30 мин. Health-пробы не инструментированы.",
thresholds=red_yellow(0.99, 0.995), decimals=2),
stat("Латентность ≤500 ms (SLO 95%)", "messenger:slo_latency:ratio30m", "percentunit", 4, y,
desc="Доля запросов в bucket le=0.5 s за 30 мин.", thresholds=red_yellow(0.95, 0.97), decimals=2),
stat("Error ratio 5xx (2m)", "messenger:http_error_ratio:rate2m", "percentunit", 8, y,
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 0.05}], decimals=2),
stat("Старейшее задание", 'max(messenger_queue_oldest_age_seconds{queue="attachments.process"})', "s", 12, y,
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 60}]),
{"id": next(_ids), "type": "alertlist", "title": "Алерты Prometheus (firing/pending)",
"gridPos": {"x": 16, "y": y, "w": 8, "h": 8},
"options": {"alertInstanceLabelFilter": "", "alertName": "", "dashboardAlerts": False, "groupBy": [],
"groupMode": "default", "maxItems": 20, "sortOrder": 1, "stateFilter":
{"firing": True, "pending": True, "noData": False, "normal": False, "error": True},
"viewMode": "list", "datasource": "Prometheus"}},
]
y += 4
panels += [
stat("RPS API", "messenger:http_requests:rate2m", "reqps", 0, y, decimals=1),
stat("p95 API (5m)", "messenger:http_latency_p95:rate5m", "s", 4, y,
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]),
stat("Загрузка worker", "messenger:worker_saturation:ratio", "percentunit", 8, y,
thresholds=[{"color": "green", "value": None}, {"color": "orange", "value": 0.9}]),
stat("Ожидают пул БД", "max(db_client_connection_pending_requests)", "short", 12, y,
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]),
]
y += 4
# ------------------------------------------------------------------ API
panels.append(row("API (messenger-api, все реплики)", y)); y += 1
rate_count = "rate(%s_count{%s}[$__rate_interval])" % (HTTP, API)
panels += [
ts("RPS по маршруту и методу", [("sum by (http_request_method, http_route) (%s)" % rate_count,
"{{http_request_method}} {{http_route}}")], "reqps", 0, y,
desc="Counter = _count гистограммы http.server.request.duration; route — шаблон, не реальный UUID."),
ts("RPS по классу статуса", [(
'sum by (status_class) (label_replace(%s, "status_class", "${1}xx", "http_response_status_code", "(\\\\d)..")) ' % rate_count,
"{{status_class}}")], "reqps", 12, y, stack=True),
]
y += 8
bucket = "sum by (le) (rate(%s_bucket{%s}[$__rate_interval]))" % (HTTP, API)
panels += [
ts("Латентность API p50/p95/p99 (из histogram buckets)", [
(q(0.5, bucket), "p50", "A"), (q(0.95, bucket), "p95", "B"), (q(0.99, bucket), "p99", "C")], "s", 0, y,
desc="histogram_quantile по сумме buckets всех реплик; не среднее и не усреднение p99 реплик."),
ts("Доля ошибок 5xx", [
('(sum(rate(%s_count{%s,http_response_status_code=~"5.."}[$__rate_interval])) or vector(0)) / sum(%s)' % (HTTP, API, rate_count),
"5xx / все", "A")], "percentunit", 12, y,
desc="Числитель: 5xx; знаменатель: все бизнес-запросы (health исключён). 4xx не считаются отказом."),
]
y += 8
panels += [
ts("p95 по маршруту", [(q(0.95, "sum by (le, http_route) (rate(%s_bucket{%s}[$__rate_interval]))" % (HTTP, API)),
"{{http_route}}")], "s", 0, y),
ts("Запросы в обработке", [("sum by (instance) (http_server_active_requests{%s})" % API, "{{instance}}")],
"short", 12, y),
]
y += 8
# ------------------------------------------------------------------ worker and queue
panels.append(row("Очередь и worker", y)); y += 1
jb = "sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome=\"succeeded\"}[$__rate_interval]))"
rb = "sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[$__rate_interval]))"
panels += [
ts("Jobs по исходу (в сек.)", [("sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))",
"{{outcome}}")], "ops", 0, y, stack=True,
desc="succeeded / retry / failed / noop / lost / dlq / requeued; job_type=attachment.process.v1"),
ts("Длительность job (succeeded) p50/p95/p99", [(q(0.5, jb), "p50", "A"), (q(0.95, jb), "p95", "B"),
(q(0.99, jb), "p99", "C")], "s", 12, y),
]
y += 8
panels += [
ts("Глубина очереди (из PostgreSQL)", [("max by (queue, state) (messenger_queue_depth)", "{{queue}} {{state}}")],
"short", 0, y, desc="max() по репликам API: каждая публикует одно и то же значение из БД."),
ts("Возраст старейшей job", [('max(messenger_queue_oldest_age_seconds{queue="attachments.process"})', "oldest age")],
"s", 12, y, desc="От durable acceptance (COMMIT job) до сейчас; это backlog, не processing latency.",
extra={"custom": {"lineWidth": 2, "fillOpacity": 10, "showPoints": "never",
"thresholdsStyle": {"mode": "line"}},
"thresholds": {"mode": "absolute", "steps": [{"color": "green", "value": None},
{"color": "red", "value": 60}]}}),
]
y += 8
panels += [
ts("Время до ready p50/p95/p99", [(q(0.5, rb), "p50", "A"), (q(0.95, rb), "p95", "B"), (q(0.99, rb), "p99", "C")],
"s", 0, y, desc="messenger.attachment.time_to_ready: от 202 (COMMIT job) до COMMIT ready."),
ts("Насыщение worker: занято / ёмкость", [
("sum(messenger_worker_busy)", "busy", "A"), ("sum(messenger_worker_capacity)", "capacity", "B"),
("messenger:worker_saturation:ratio", "saturation", "C")], "short", 12, y),
]
y += 8
# ------------------------------------------------------------------ resources
panels.append(row("Ресурсы: пул БД, CPU, RAM", y)); y += 1
panels += [
ts("Пул БД: used / idle / waiting", [
("sum by (service_name, db_client_connection_state) (db_client_connection_count)",
"{{service_name}} {{db_client_connection_state}}", "A"),
("sum by (service_name) (db_client_connection_pending_requests)", "{{service_name}} waiting", "B"),
("sum by (service_name) (db_client_connection_max)", "{{service_name}} max", "C")], "short", 0, y),
ts("CPU процессов (ядра)", [
("sum by (service_name, instance) (rate(process_cpu_time_seconds_total[$__rate_interval]))",
"{{service_name}} {{instance}}", "A"),
("rate(otelcol_process_cpu_seconds_total[$__rate_interval])", "otel-collector", "B")], "percentunit", 12, y,
desc="worker: self + завершённые дочерние процессы обработки изображений."),
]
y += 8
panels += [
ts("RSS процессов", [("process_memory_usage_bytes", "{{service_name}} {{instance}}", "A"),
("otelcol_process_memory_rss_bytes", "otel-collector", "B")], "bytes", 0, y),
ts("Telemetry pipeline: принято / отправлено / ошибки (items/s)", [
("sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))", "accepted spans", "A"),
("sum(rate(otelcol_receiver_accepted_log_records_total[$__rate_interval]))", "accepted log records", "E"),
("sum(rate(otelcol_receiver_accepted_metric_points_total[$__rate_interval]))", "accepted metric points", "F"),
("sum by (exporter) (rate({__name__=~\"otelcol_exporter_sent_(spans|log_records|metric_points)_total\"}[$__rate_interval]))",
"sent {{exporter}}", "B"),
# Separate queries: rate() drops __name__, so a regex over several failed_* counters collides once they all exist.
("sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval])) or vector(0)", "send failed spans", "C"),
("sum(rate(otelcol_exporter_enqueue_failed_spans_total[$__rate_interval])) or vector(0)", "dropped spans (queue full)", "G"),
("sum(rate(otelcol_exporter_send_failed_log_records_total[$__rate_interval])) or vector(0)", "send failed logs", "H"),
("sum(rate(otelcol_exporter_enqueue_failed_log_records_total[$__rate_interval])) or vector(0)", "dropped logs (queue full)", "I"),
("sum by (exporter) (otelcol_exporter_queue_size)", "queue {{exporter}}", "D")], "short", 12, y),
]
y += 8
# ------------------------------------------------------------------ logs and traces
panels.append(row("Логи и трассы", y)); y += 1
panels += [
{"id": next(_ids), "type": "logs", "title": "Логи API и worker (warning/error)", "datasource": LOKI,
"gridPos": {"x": 0, "y": y, "w": 12, "h": 10},
"options": {"showTime": True, "wrapLogMessage": True, "sortOrder": "Descending", "enableLogDetails": True},
"targets": [{"datasource": LOKI, "refId": "A",
"expr": '{service_name=~"messenger-api|messenger-worker"} | severity_text=~"WARN.*|ERROR"'}]},
{"id": next(_ids), "type": "table", "title": "Трассы с ошибками или медленнее 500 ms (TraceQL)", "datasource": TEMPO,
"gridPos": {"x": 12, "y": y, "w": 12, "h": 10},
"targets": [{"datasource": TEMPO, "refId": "A", "queryType": "traceql", "limit": 20,
"query": '{resource.service.name=~"messenger-.*" && (status=error || duration>500ms)}'}]},
]
y += 10
dashboard = {
"uid": "messenger-lab6", "title": "Messenger — наблюдаемость (lab6)", "tags": ["messenger", "lab6"],
"timezone": "browser", "schemaVersion": 39, "version": 1, "editable": False, "refresh": "10s",
"time": {"from": "now-30m", "to": "now"}, "graphTooltip": 1, "panels": panels,
"annotations": {"list": [{"builtIn": 1, "datasource": {"type": "grafana", "uid": "-- Grafana --"},
"enable": True, "hide": True, "name": "Annotations & Alerts", "type": "dashboard"}]},
"templating": {"list": []},
}
OUT.write_text(json.dumps(dashboard, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("wrote %s (%d panels)" % (OUT.relative_to(OUT.parents[3]), len(panels)))
# Human-readable list of every panel: datasource, query and unit (kept in sync with the JSON by this script).
UNITS = {"reqps": "запросы/с", "percentunit": "доля (0..1)", "s": "секунды", "ops": "операции/с", "short": "штуки",
"bytes": "байты"}
DOC = OUT.parents[3] / "docs/dashboard.md"
lines = ["# Панели dashboard «%s»" % dashboard["title"], "",
"Сгенерировано `scripts/gen_dashboard.py` вместе с `infra/grafana/dashboards/messenger.json`. "
"`$__rate_interval` подставляет Grafana (не меньше 4 × scrape/export interval).", ""]
for panel in panels:
if panel["type"] == "row":
lines += ["## " + panel["title"], ""]
continue
unit = panel.get("fieldConfig", {}).get("defaults", {}).get("unit", "")
lines.append("**%s** (%s%s)" % (panel["title"], panel["type"], ", единица: " + UNITS.get(unit, unit) if unit else ""))
if panel.get("description"):
lines.append("— " + panel["description"])
lines.append("")
if panel["type"] == "alertlist":
lines += ["Правила Prometheus в состоянии pending/firing (`infra/prometheus/rules/messenger.yml`).", ""]
for t in panel.get("targets", []):
query = t.get("expr") or t.get("query")
legend = t.get("legendFormat", "")
lines += ["```%s" % ("promql" if t["datasource"]["type"] == "prometheus" else ""),
query + (" # " + legend if legend and legend != panel["title"] else ""), "```"]
lines.append("")
DOC.write_text("\n".join(lines), encoding="utf-8")
print("wrote docs/dashboard.md")
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# Operator step 1 (after scripts/pki.sh init): local .env and random bootstrap credentials in secrets/bootstrap/.
# Nothing is printed. Existing files are kept, so a re-run never changes the passwords of a live stand.
#
# Who gets what:
# stores (postgres, minio, valkey, grafana) read their OWN admin/ACL material from Docker secrets;
# API and worker get NO password files at all: scripts/bao.sh bootstrap copies their credentials into OpenBao
# and the services read them there after authenticating with their client certificate.
set -eu
cd "$(dirname "$0")/.."
[ -f .env ] || cp .env.example .env
umask 077
mkdir -p secrets/bootstrap
cd secrets/bootstrap
put() { [ -f "$1" ] || printf '%s' "$2" > "$1"; }
random() { python3 -c "import secrets;print(secrets.token_urlsafe(24),end='')"; }
put postgres_password "$(random)" # superuser `messenger`: migrations and operator only
put db_api_password "$(random)" # role app_api
put db_worker_password "$(random)" # role app_worker
put minio_root_user messenger_root
put minio_root_password "$(random)"
put s3_api_access_key messenger-api
put s3_api_secret_key "$(random)"
put s3_worker_access_key messenger-worker
put s3_worker_secret_key "$(random)"
put valkey_api_password "$(random)" # ACL user `api`
put grafana_admin_password "$(random)"
put migrate_database_url "postgresql://messenger:$(cat postgres_password)@postgres:5432/messenger"
chmod 644 ./* # read by container users through Docker secrets; the directory itself is 700
cd ..
chmod 700 . bootstrap
echo "bootstrap credentials ready in secrets/bootstrap/ (.env present)"
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Operator CLI for attachment jobs (run inside an API container: docker compose exec api-1 python scripts/jobs.py ...).
failed registry of failed jobs (the "DLQ" of business failures)
show <attachment_id> job state + audit trail
replay <attachment_id> --actor NAME explicit failed -> queued; refused (no-op) for ready/queued/processing
stats counts by state and outbox backlog
Poison messages that are not valid jobs are in the RabbitMQ queue attachments.dlq (see REPORT.md).
"""
import argparse
import asyncio
import json
import sys
sys.path.insert(0, "/app")
from starlette.concurrency import run_in_threadpool # noqa: E402
from app import jobs # noqa: E402
from app.cursor import fmt # noqa: E402
from app.db import Database # noqa: E402
from app.s3 import S3Storage # noqa: E402
def out(value) -> None:
print(json.dumps(value, ensure_ascii=False, indent=2, default=str))
async def main() -> int:
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("failed")
sub.add_parser("stats")
show = sub.add_parser("show")
show.add_argument("attachment_id")
rp = sub.add_parser("replay")
rp.add_argument("attachment_id")
rp.add_argument("--actor", required=True, help="who requests the replay (written to job_audit)")
args = parser.parse_args()
db = Database()
await db.open()
try:
if args.cmd == "failed":
async with db.connection() as conn:
out(await jobs.failed_jobs(conn))
elif args.cmd == "stats":
async with db.connection() as conn:
cur = await conn.execute("SELECT state, count(*) AS n FROM attachment_jobs GROUP BY state ORDER BY state")
states = {r["state"]: r["n"] for r in await cur.fetchall()}
cur = await conn.execute("SELECT count(*) AS n FROM outbox WHERE published_at IS NULL")
backlog = (await cur.fetchone())["n"]
out({"jobs": states, "outbox_unpublished": backlog})
elif args.cmd == "show":
async with db.connection() as conn:
cur = await conn.execute(
"SELECT j.id, j.state, j.attempt, j.max_attempts, j.error_code, j.lease_owner, j.lease_until,"
" a.status AS attachment_status FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id"
" WHERE j.attachment_id = %s", (args.attachment_id,))
job = await cur.fetchone()
cur = await conn.execute(
"SELECT action, actor, attempt, detail, created_at FROM job_audit WHERE attachment_id = %s ORDER BY id",
(args.attachment_id,))
trail = [{**r, "created_at": fmt(r["created_at"])} for r in await cur.fetchall()]
cur = await conn.execute(
"SELECT o.id, o.payload->>'attempt' AS attempt, o.available_at, o.published_at, o.publish_attempts"
" FROM outbox o JOIN attachment_jobs j ON j.id = o.job_id WHERE j.attachment_id = %s ORDER BY o.id",
(args.attachment_id,))
outbox = await cur.fetchall()
out({"job": job, "audit": trail, "outbox": outbox})
elif args.cmd == "replay":
s3 = S3Storage()
await run_in_threadpool(s3.open)
async def exists(key):
return await run_in_threadpool(s3.exists, key)
result = await db.in_transaction(
lambda conn: jobs.replay(conn, args.attachment_id, "operator:" + args.actor, exists))
out(result)
return 0 if result["result"] == "queued" else 3
finally:
await db.close()
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Versioned SQL migrations: applied once, checksum-verified, safe to re-run."""
import hashlib
import os
import pathlib
import sys
import psycopg
ROOT = pathlib.Path(__file__).resolve().parents[1]
MIGRATIONS = ROOT / "migrations"
LOCK_ID = 2026_0004
def database_url() -> str:
path = os.environ.get("DATABASE_URL_FILE")
if path:
return pathlib.Path(path).read_text(encoding="utf-8").strip()
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
sys.exit("DATABASE_URL or DATABASE_URL_FILE is required")
return url
def set_service_passwords(conn) -> None:
"""lab7: passwords of the service roles come from operator bootstrap files (never from Git or the image).
Re-running keeps them in sync with secrets/bootstrap, which scripts/bao.sh also copies into OpenBao."""
from psycopg import sql
for role, env in (("app_api", "DB_API_PASSWORD_FILE"), ("app_worker", "DB_WORKER_PASSWORD_FILE")):
path = os.environ.get(env)
if not path:
continue
with open(path, encoding="utf-8") as handle:
password = handle.read().strip()
conn.execute(sql.SQL("ALTER ROLE {} PASSWORD {}").format(sql.Identifier(role), sql.Literal(password)))
print("password set for role %s" % role)
def main() -> None:
files = sorted(MIGRATIONS.glob("*.sql"))
if not files:
sys.exit("no migration files found in %s" % MIGRATIONS)
tls = {"sslmode": os.environ.get("DATABASE_SSLMODE", "verify-full"),
"sslrootcert": os.environ.get("TLS_CA_FILE", "/run/secrets/ca.crt")}
with psycopg.connect(database_url(), autocommit=True, connect_timeout=10, **tls) as conn:
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations ("
" version text PRIMARY KEY,"
" checksum text NOT NULL,"
" applied_at timestamptz NOT NULL DEFAULT now())"
)
conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,))
rows = conn.execute("SELECT version, checksum FROM schema_migrations").fetchall()
applied = {row[0]: row[1] for row in rows}
for path in files:
version = path.stem
body = path.read_text(encoding="utf-8")
checksum = hashlib.sha256(body.encode("utf-8")).hexdigest()
if version in applied:
if applied[version] != checksum:
sys.exit("migration %s changed after it was applied" % version)
print("skip %s" % version)
continue
with conn.transaction():
conn.execute(body)
conn.execute(
"INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)",
(version, checksum),
)
print("apply %s" % version)
set_service_passwords(conn)
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
print("migrations complete: %d file(s)" % len(files))
if __name__ == "__main__":
main()
Executable
+190
View File
@@ -0,0 +1,190 @@
#!/bin/sh
# Local lab PKI (operator tool). Private keys stay in secrets/pki/ (git-ignored, never baked into images).
#
# scripts/pki.sh init create CAs and every leaf that does not exist yet (idempotent)
# scripts/pki.sh issue <leaf> (re)issue one leaf with a new key and serial (rotation)
# scripts/pki.sh revoke <leaf> add the CURRENT serial of <leaf> to secrets/pki/revoked-serials.txt
# scripts/pki.sh revoke-serial <hex> revoke a serial that is no longer the current one (after a rotation)
# scripts/pki.sh expired <leaf> test-only: an ALREADY EXPIRED copy of <leaf> (same identity) -> <leaf>-expired.*
# scripts/pki.sh serial <leaf> current serial of <leaf>
# scripts/pki.sh list leaf names, identities, serials and expiry (no key material)
#
# Trust layout (identity is checked by every server, not only the chain):
# root CA "Messenger Lab Root CA" signs every server certificate and the service client identities
# (lb, api, worker) used for LB->API, RabbitMQ (EXTERNAL = certificate CN) and OpenBao cert auth.
# ingest CA (intermediate) signs ONLY api-otel / worker-otel: the Collector trusts nothing else, so a
# root-signed certificate (e.g. the LB one) cannot push telemetry.
# telemetry CA (intermediate) signs ONLY collector-out / grafana-out / operator: Prometheus, Loki and Tempo
# accept only these clients.
# intruder root-signed, valid, but with an identity that no server allows (negative tests).
# foreign CA unrelated CA; foreign-client claims the lb/api/worker names (negative tests of chain checks).
# OpenSSL runs in a pinned container, so the host OpenSSL/LibreSSL version does not matter.
set -eu
cd "$(dirname "$0")/.."
DIR=secrets/pki
IMAGE="alpine/openssl:3.3.2@sha256:5008e829163320a6e8166883c03e68189e8925ade68cde36584dc2a41cfa5248"
LEAF_DAYS="${LEAF_DAYS:-90}"
CA_DAYS=825
# name | signer | usage | CN | DNS/IP SANs
LEAVES='
lb-server root server localhost localhost,nginx,IP:127.0.0.1
lb-client root client lb.client.messenger lb.client.messenger
api-1 root server api-1 api-1,api.internal
api-2 root server api-2 api-2,api.internal
api root client api.client.messenger api.client.messenger
worker root client worker.client.messenger worker.client.messenger
postgres root server postgres postgres
minio root server minio minio
rabbitmq root server rabbitmq rabbitmq
valkey root server valkey valkey
openbao root server openbao openbao,localhost,IP:127.0.0.1
otel-collector root server otel-collector otel-collector
prometheus root server prometheus prometheus,localhost,IP:127.0.0.1
loki root server loki loki,localhost,IP:127.0.0.1
tempo root server tempo tempo,localhost,IP:127.0.0.1
grafana root server grafana grafana,localhost,IP:127.0.0.1
api-otel ingest client api.otel.messenger api.otel.messenger
worker-otel ingest client worker.otel.messenger worker.otel.messenger
collector-out telemetry client collector.out.messenger collector.out.messenger
grafana-out telemetry client grafana.out.messenger grafana.out.messenger
operator telemetry client operator.messenger operator.messenger
intruder root client intruder.client.messenger intruder.client.messenger
'
ossl() { # quiet on success, the OpenSSL error on failure
out=$(docker run --rm -u "$(id -u):$(id -g)" -v "$PWD/$DIR:/pki" -w /pki "$IMAGE" "$@" 2>&1) || {
echo "openssl $1 failed: $out" >&2; exit 1; }
}
ca_init() { # ca_init <name> <subject> [parent]
[ -f "$DIR/$1.crt" ] && return 0
cat > "$DIR/.ext-$1" <<EOF
basicConstraints=critical,CA:true,pathlen:0
keyUsage=critical,keyCertSign,cRLSign
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid
EOF
ossl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$1.key"
if [ $# -eq 2 ]; then
ossl req -x509 -new -key "$1.key" -subj "$2" -days "$CA_DAYS" -sha256 \
-addext "basicConstraints=critical,CA:true,pathlen:1" \
-addext "keyUsage=critical,keyCertSign,cRLSign" -out "$1.crt"
else
ossl req -new -key "$1.key" -subj "$2" -out "$1.csr"
ossl x509 -req -in "$1.csr" -CA "$3.crt" -CAkey "$3.key" -CAcreateserial -days "$CA_DAYS" -sha256 \
-extfile ".ext-$1" -out "$1.crt"
rm -f "$DIR/$1.csr"
fi
rm -f "$DIR/.ext-$1"
echo "created CA $1"
}
leaf_line() { echo "$LEAVES" | awk -v n="$1" '$1==n'; }
issue() { # issue <leaf>
line=$(leaf_line "$1")
[ -n "$line" ] || { echo "unknown leaf: $1" >&2; exit 2; }
set -- $line
name=$1 signer=$2 usage=$3 cn=$4 sans=$5
eku=serverAuth; [ "$usage" = client ] && eku=clientAuth
alt=$(echo "$sans" | tr ',' '\n' | awk '/^IP:/ {print; next} {print "DNS:" $0}' | paste -sd, -)
cat > "$DIR/.ext-$name" <<EOF
basicConstraints=critical,CA:false
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=$eku
subjectAltName=$alt
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid
EOF
ossl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$name.key.new"
ossl req -new -key "$name.key.new" -subj "/O=Messenger Lab/CN=$cn" -out "$name.csr"
ossl x509 -req -in "$name.csr" -CA "$signer.crt" -CAkey "$signer.key" -CAcreateserial -days "$LEAF_DAYS" \
-sha256 -extfile ".ext-$name" -out "$name.crt.new"
# Leaf files carry the chain up to (not including) the root, so intermediates verify against ca.crt alone.
if [ -f "$DIR/$name.crt" ]; then cp "$DIR/$name.crt" "$DIR/$name.crt.previous"; cp "$DIR/$name.key" "$DIR/$name.key.previous"; fi
# Overwrite in place (cat >): the files are bind-mounted Docker secrets, a new inode would not be visible.
if [ "$signer" = root ]; then cat "$DIR/$name.crt.new" > "$DIR/$name.crt"; else cat "$DIR/$name.crt.new" "$DIR/$signer.crt" > "$DIR/$name.crt"; fi
cat "$DIR/$name.key.new" > "$DIR/$name.key"; rm -f "$DIR/$name.key.new"
rm -f "$DIR/$name.crt.new" "$DIR/$name.csr" "$DIR/.ext-$name"
echo "issued $name ($cn) serial=$(serial "$name") valid ${LEAF_DAYS}d"
}
foreign() { # an unrelated CA and a leaf that CLAIMS the LB/api/worker names: negative tests of chain checks
[ -f "$DIR/foreign-client.crt" ] && return 0
ca_init foreign "/O=Somebody Else/CN=Foreign CA"
printf '%s\n' "basicConstraints=critical,CA:false" "keyUsage=critical,digitalSignature,keyEncipherment" \
"extendedKeyUsage=clientAuth,serverAuth" \
"subjectAltName=DNS:lb.client.messenger,DNS:api.client.messenger,DNS:worker.client.messenger" \
> "$DIR/.ext-foreign-client"
ossl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out foreign-client.key
ossl req -new -key foreign-client.key -subj "/O=Somebody Else/CN=lb.client.messenger" -out foreign-client.csr
ossl x509 -req -in foreign-client.csr -CA foreign.crt -CAkey foreign.key -CAcreateserial -days 30 -sha256 \
-extfile .ext-foreign-client -out foreign-client.crt
rm -f "$DIR/foreign-client.csr" "$DIR/.ext-foreign-client"
echo "created foreign CA + foreign-client (claims lb/api/worker identities, trusted nowhere)"
}
expired() { # same CN/SAN/EKU as <leaf>, validity in the past (openssl ca allows explicit dates)
line=$(leaf_line "$1"); [ -n "$line" ] || { echo "unknown leaf: $1" >&2; exit 2; }
set -- $line
name=$1 signer=$2 usage=$3 cn=$4 sans=$5
eku=serverAuth; [ "$usage" = client ] && eku=clientAuth
alt=$(echo "$sans" | tr ',' '\n' | awk '/^IP:/ {print; next} {print "DNS:" $0}' | paste -sd, -)
t="$DIR/.ca-$name"; rm -rf "$t"; mkdir -p "$t"; touch "$t/index.txt"; echo 01 > "$t/serial"
printf '%s\n' "[ca]" "default_ca=x" "[x]" "database=/pki/.ca-$name/index.txt" "serial=/pki/.ca-$name/serial" \
"new_certs_dir=/pki/.ca-$name" "default_md=sha256" "policy=p" "unique_subject=no" "[p]" "commonName=supplied" \
"[ext]" "basicConstraints=critical,CA:false" "keyUsage=critical,digitalSignature" "extendedKeyUsage=$eku" \
"subjectAltName=$alt" > "$t/ca.cnf"
ossl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$name-expired.key"
ossl req -new -key "$name-expired.key" -subj "/O=Messenger Lab/CN=$cn" -out ".ca-$name/req.csr"
ossl ca -batch -config ".ca-$name/ca.cnf" -extensions ext -cert "$signer.crt" -keyfile "$signer.key" \
-startdate 20250101000000Z -enddate 20250102000000Z -in ".ca-$name/req.csr" -out "$name-expired.crt" -notext
rm -rf "$t"
echo "issued $name-expired ($cn), validity 2025-01-01..2025-01-02 (already expired, test only)"
}
serial() { docker run --rm -v "$PWD/$DIR:/pki" -w /pki "$IMAGE" x509 -in "$1.crt" -noout -serial | cut -d= -f2; }
finish() {
cp "$DIR/root.crt" "$DIR/ca.crt" # public CA bundle for clients (make test CA_FILE=...)
cat "$DIR/root.crt" "$DIR/ingest.crt" > "$DIR/ingest-bundle.crt"
cat "$DIR/root.crt" "$DIR/telemetry.crt" > "$DIR/telemetry-bundle.crt"
touch "$DIR/revoked-serials.txt"
# Containers run as other uids and read keys through Docker secrets: files readable, directory closed.
chmod 700 secrets "$DIR"
chmod 644 "$DIR"/*.crt "$DIR"/*.key "$DIR/revoked-serials.txt"
chmod 600 "$DIR"/*.previous 2>/dev/null || true
chmod 600 "$DIR"/root.key "$DIR"/ingest.key "$DIR"/telemetry.key "$DIR"/foreign.key
}
cmd="${1:-init}"
mkdir -p "$DIR"
case "$cmd" in
init)
ca_init root "/O=Messenger Lab/CN=Messenger Lab Root CA"
ca_init ingest "/O=Messenger Lab/CN=Messenger Telemetry Ingest CA" root
ca_init telemetry "/O=Messenger Lab/CN=Messenger Telemetry Clients CA" root
for name in $(echo "$LEAVES" | awk 'NF {print $1}'); do
[ -f "$DIR/$name.crt" ] || issue "$name"
done
foreign
finish ;;
issue) issue "$2"; finish ;;
revoke)
s=$(serial "$2"); grep -qx "$s" "$DIR/revoked-serials.txt" 2>/dev/null || echo "$s" >> "$DIR/revoked-serials.txt"
echo "revoked $2 serial=$s"; finish ;;
revoke-serial)
s=$(echo "$2" | tr 'a-f' 'A-F')
# append in place: the file is bind-mounted into the API containers (a new inode would not be seen)
grep -qx "$s" "$DIR/revoked-serials.txt" 2>/dev/null || echo "$s" >> "$DIR/revoked-serials.txt"
echo "revoked serial=$s" ;;
expired) expired "$2"; finish ;;
serial) serial "$2" ;;
list)
for name in $(echo "$LEAVES" | awk 'NF {print $1}'); do
printf '%-15s %-28s %s %s\n' "$name" "$(leaf_line "$name" | awk '{print $4}')" "$(serial "$name")" \
"$(docker run --rm -v "$PWD/$DIR:/pki" -w /pki "$IMAGE" x509 -in "$name.crt" -noout -enddate | cut -d= -f2)"
done ;;
*) echo "usage: $0 init|issue <leaf>|revoke <leaf>|revoke-serial <hex>|expired <leaf>|serial <leaf>|list" >&2; exit 2 ;;
esac
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Run one DB<->S3 reconciliation pass. Default is dry-run; pass --apply to change anything."""
import argparse
import asyncio
import json
import sys
sys.path.insert(0, "/app")
from starlette.concurrency import run_in_threadpool # noqa: E402
from app import config, reconcile # noqa: E402
from app.db import Database # noqa: E402
from app.s3 import S3Storage # noqa: E402
async def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--apply", action="store_true", help="delete/mark; without it only reports")
parser.add_argument("--grace-seconds", type=int, default=config.RECONCILE_GRACE_SECONDS)
args = parser.parse_args()
db, s3 = Database(), S3Storage()
await db.open()
await run_in_threadpool(s3.open)
try:
print(json.dumps(await reconcile.run(db, s3, args.grace_seconds, dry_run=not args.apply), sort_keys=True))
finally:
await db.close()
if __name__ == "__main__":
asyncio.run(main())
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Restart hook (tests/resilience.py --mode persistence): restart every store keeping all volumes, then the services.
# business stores: postgres, valkey, minio, rabbitmq
# secret store: openbao -> comes back SEALED; the operator step `scripts/bao.sh unseal` uses 2 of 3 shares
# from secrets/operator/ (lab compromise documented in REPORT.md). Without it the services would
# wait for OpenBao after their own restart.
# telemetry: prometheus, loki, tempo, otel-collector, grafana
# services: worker, api-1, api-2, nginx (they log in to OpenBao again and re-read their secrets)
# Never removes volumes, never re-seeds. Prints no secrets.
set -eu
cd "$(dirname "$0")/.."
docker compose restart -t 10 postgres valkey minio rabbitmq openbao >/dev/null
sh scripts/bao.sh unseal >/dev/null
docker compose restart -t 10 prometheus loki tempo otel-collector grafana >/dev/null
docker compose restart -t 25 worker api-1 api-2 nginx >/dev/null
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
cd "$(dirname "$0")/.."
docker compose stop -t 3 "$TARGET_INSTANCE_ID"