Files
mtusi2026lab7-safronov/infra/rabbitmq/start.sh
T
ricoromaandClaude Opus 5.5 8236027e92 feat: require mTLS with certificate login for RabbitMQ and split relay and worker rights
Broker accepts only TLS 1.3 with a client certificate checked against the
stand CRL; login is EXTERNAL by certificate DNS SAN, broker passwords are
gone. Relay may declare its queue and publish, worker may only consume.
Definitions and TLS material checks come from infra/rabbitmq/start.sh;
temporary stands, CI, bench and the fault hook use the same mTLS identities.
Adds make broker_mtls_check [REPORT=1] and drops the rollback broker compose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:34:47 +03:00

126 lines
5.7 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/sh
# Старт брокера стенда (change messaging-telemetry-mtls, design, решения 5, 7, 9;
# правило .claude/rules/tls.md, раздел брокера).
#
# От root до entrypoint образа:
# 1. проверки окружения: RABBITMQ_QUEUE_NAMESPACE (имя базы, ^[a-z0-9_]+$),
# RABBITMQ_PORT, tmpfs /run/rabbitmq;
# 2. проверка материалов TLS openssl образа: сертификат и ключ брокера
# разбираются и составляют пару, leaf проходит verify по CA стенда с CRL,
# CRL подписан этим CA и не просрочен. Узел сам материалы при старте не
# проверяет (без ключа он стартует, и healthcheck проходит — проба
# propose), поэтому сломанный TLS — код 1 здесь: контейнер не healthy, relay
# и worker его ждут;
# 3. копии CA, сертификата и ключа в /run/rabbitmq/tls/ (ключ 0400, владелец
# rabbitmq) и каталог CRL /run/rabbitmq/crl/<хэш издателя>.r0 — пути
# advanced.config; подмена файлов после старта до рестарта не действует;
# 4. определения брокера /run/rabbitmq/definitions.json (импорт на каждом
# старте, rabbitmq.conf): vhost /, пользователи relay и worker без пароля и
# тегов, их права (relay — объявить свою очередь и публиковать через
# default exchange, worker — только получать), рабочая очередь (classic,
# durable, без аргументов — как её объявляет код);
# 5. exec docker-entrypoint.sh rabbitmq-server (сервер — от пользователя
# rabbitmq).
# Ошибка — код 1 и строка с именем файла или переменной без содержимого.
#
# `sh start.sh --print-definitions` — только определения в stdout (проверка
# имени базы, без openssl, tmpfs и сервера): их сверяет быстрый тест
# service-tests/unit/test_broker_definitions.py. Суффикс очереди повторяет
# ATTACHMENT_QUEUE_SUFFIX (src/utils/constants.py): смена — эта строка тоже.
set -eu
QUEUE_SUFFIX="attachment.process.v1"
SECRETS_DIR=/run/secrets
RUN_DIR=/run/rabbitmq
TLS_DIR="$RUN_DIR/tls"
CRL_DIR="$RUN_DIR/crl"
DEFINITIONS="$RUN_DIR/definitions.json"
fail() {
echo "rabbitmq start: $1" >&2
exit 1
}
namespace="${RABBITMQ_QUEUE_NAMESPACE:-}"
printf '%s' "$namespace" | grep -Eq '^[a-z0-9_]+$' \
|| fail "RABBITMQ_QUEUE_NAMESPACE must match ^[a-z0-9_]+\$"
# шаблоны прав: очереди заданий своей базы и test_<база> (make test_isolated);
# точки экранированы для регулярного выражения брокера, \ — для JSON
queue_pattern="^($namespace|test_$namespace)\\\\.attachment\\\\.process\\\\.v1\$"
definitions() {
cat <<EOF
{
"vhosts": [{"name": "/"}],
"users": [
{"name": "relay", "tags": []},
{"name": "worker", "tags": []}
],
"permissions": [
{"user": "relay", "vhost": "/",
"configure": "$queue_pattern",
"write": "^amq\\\\.default\$",
"read": "^\$"},
{"user": "worker", "vhost": "/",
"configure": "^\$",
"write": "^\$",
"read": "$queue_pattern"}
],
"queues": [
{"name": "$namespace.$QUEUE_SUFFIX", "vhost": "/",
"durable": true, "auto_delete": false, "arguments": {}}
]
}
EOF
}
if [ "${1:-}" = "--print-definitions" ]; then
definitions
exit 0
fi
printf '%s' "${RABBITMQ_PORT:-}" | grep -Eq '^[0-9]+$' \
|| fail "RABBITMQ_PORT must be a port number"
# копии ключа и определения — только в памяти: каталог обязан быть tmpfs
grep -q " $RUN_DIR tmpfs " /proc/mounts || fail "$RUN_DIR is not a tmpfs"
ca="$SECRETS_DIR/ca.crt"
crl="$SECRETS_DIR/crl.pem"
cert="$SECRETS_DIR/rabbitmq.crt"
key="$SECRETS_DIR/rabbitmq.key"
# сообщения openssl — в /dev/null: в них нет ключа, но и пользы в журнале нет
for file in "$ca" "$crl" "$cert" "$key"; do
[ -r "$file" ] || fail "$file is missing or unreadable"
done
openssl x509 -in "$ca" -noout 2>/dev/null || fail "$ca is not a certificate"
openssl x509 -in "$cert" -noout 2>/dev/null \
|| fail "$cert is not a certificate"
openssl pkey -in "$key" -noout 2>/dev/null || fail "$key is not a private key"
cert_pub=$(openssl x509 -in "$cert" -noout -pubkey 2>/dev/null)
key_pub=$(openssl pkey -in "$key" -pubout 2>/dev/null)
[ "$cert_pub" = "$key_pub" ] || fail "$key does not match $cert"
openssl crl -in "$crl" -CAfile "$ca" -noout 2>/dev/null \
|| fail "$crl is not a CRL signed by $ca"
openssl verify -CAfile "$ca" -crl_check -CRLfile "$crl" "$cert" \
>/dev/null 2>&1 \
|| fail "$cert does not verify against $ca and $crl (other CA, revoked or CRL expired)"
crl_hash=$(openssl crl -in "$crl" -noout -hash 2>/dev/null) \
|| fail "$crl hash failed"
umask 077
chmod 700 "$RUN_DIR"
mkdir -p "$TLS_DIR" "$CRL_DIR"
cp "$ca" "$TLS_DIR/ca.crt"
cp "$cert" "$TLS_DIR/rabbitmq.crt"
cp "$key" "$TLS_DIR/rabbitmq.key"
cp "$crl" "$CRL_DIR/$crl_hash.r0"
definitions > "$DEFINITIONS"
chown -R rabbitmq:rabbitmq "$RUN_DIR"
chmod 400 "$TLS_DIR/rabbitmq.key"
chmod 444 "$TLS_DIR/ca.crt" "$TLS_DIR/rabbitmq.crt" "$CRL_DIR/$crl_hash.r0"
echo "rabbitmq start: TLS material verified, users relay and worker, queue namespace $namespace, port $RABBITMQ_PORT"
exec docker-entrypoint.sh rabbitmq-server