lab7: PKI, mTLS infra, OpenBao non-dev, hardening, lifecycle scripts
This commit is contained in:
+13
-10
@@ -1,19 +1,22 @@
|
||||
#!/bin/sh
|
||||
# Black-box набор приложения (app/test/*.e2e-spec.ts) против поднятого стенда.
|
||||
# Требует loopback-портов PostgreSQL, Redis и MinIO из compose.yaml.
|
||||
# Black-box набор приложения (app/test/*.e2e-spec.ts) против локального стенда.
|
||||
# В lab7 PostgreSQL и Redis намеренно не публикуются на хост, поэтому для
|
||||
# host-side e2e передайте явные DATABASE_URL и REDIS_URL (или запускайте
|
||||
# unit/contract/lab7 проверки). Секреты в .env отсутствуют.
|
||||
set -eu
|
||||
|
||||
env_file="${COMPOSE_ENV_FILE:-.env}"
|
||||
compose_dir="$(pwd)"
|
||||
# shellcheck disable=SC1090
|
||||
set -a
|
||||
. "./$env_file"
|
||||
set +a
|
||||
if [ -f "./$env_file" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
set -a
|
||||
. "./$env_file"
|
||||
set +a
|
||||
fi
|
||||
|
||||
export API_BASE_URL="${API_BASE_URL:-http://127.0.0.1:${APP_PUBLIC_PORT:-8080}}"
|
||||
export DATABASE_URL="postgresql://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in $env_file}@127.0.0.1:${POSTGRES_PUBLISHED_PORT:-5432}/${POSTGRES_DB:-messenger}"
|
||||
export REDIS_URL="redis://127.0.0.1:${REDIS_PUBLISHED_PORT:-6379}"
|
||||
export E2E_S3_PUBLIC_ENDPOINT="${S3_PUBLIC_ENDPOINT:-http://localhost:9000}"
|
||||
export API_BASE_URL="${API_BASE_URL:-https://localhost:${APP_PUBLIC_PORT:-8443}}"
|
||||
export NODE_EXTRA_CA_CERTS="${NODE_EXTRA_CA_CERTS:-${compose_dir}/secrets/pki/ca.crt}"
|
||||
export E2E_S3_PUBLIC_ENDPOINT="${S3_PUBLIC_ENDPOINT:-https://localhost:${S3_PUBLIC_PORT:-9000}}"
|
||||
export E2E_S3_BUCKET="${S3_BUCKET:-messenger-attachments}"
|
||||
export E2E_COMPOSE_DIR="$compose_dir"
|
||||
export E2E_COMPOSE_ENV_FILE="$env_file"
|
||||
|
||||
+85
-56
@@ -1,77 +1,106 @@
|
||||
#!/bin/sh
|
||||
# Идемпотентно создаёт .env и secrets/* для локального стенда. Значения не печатает.
|
||||
set -eu
|
||||
#!/usr/bin/env bash
|
||||
# Idempotently creates non-secret .env and stateful infra-only bootstrap secrets
|
||||
# under ./secrets/infra/. Never prints secret values and NEVER creates
|
||||
# application credentials (DB/Redis/S3/Broker/Metrics app creds live ONLY in
|
||||
# OpenBao Raft KV v2 and backend auth stores).
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
(
|
||||
umask 077
|
||||
pg=$(openssl rand -hex 24)
|
||||
mt=$(openssl rand -hex 16)
|
||||
sed \
|
||||
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${pg}|" \
|
||||
-e "s|^DATABASE_URL=.*|DATABASE_URL=postgresql://messenger:${pg}@postgres:5432/messenger|" \
|
||||
-e "s|^METRICS_TOKEN=.*|METRICS_TOKEN=${mt}|" \
|
||||
.env.example > .env
|
||||
)
|
||||
echo "created .env"
|
||||
cp .env.example .env
|
||||
chmod 0644 .env
|
||||
echo "created .env (non-secret topology config only)"
|
||||
else
|
||||
echo "kept .env"
|
||||
fi
|
||||
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
mkdir -p secrets secrets/infra
|
||||
chmod 0700 secrets secrets/infra
|
||||
|
||||
write_secret() {
|
||||
name=$1
|
||||
value=$2
|
||||
if [ -s "secrets/$name" ]; then
|
||||
echo "kept secrets/$name"
|
||||
return
|
||||
# Host isolation is enforced by 0700 on ./secrets and ./secrets/infra; individual
|
||||
# secret files are 0644 so heterogeneous non-root container UIDs (70, 99, 472,
|
||||
# 999, 1000, 10001, 65534) can read only the specific secret mounted to them.
|
||||
write_infra_secret() {
|
||||
local name="$1"
|
||||
local value="$2"
|
||||
local path="secrets/infra/${name}"
|
||||
if [ -s "$path" ]; then
|
||||
echo "kept ${path}"
|
||||
return 0
|
||||
fi
|
||||
(umask 133; printf '%s' "$value" > "secrets/$name")
|
||||
chmod 0644 "secrets/$name"
|
||||
echo "created secrets/$name"
|
||||
local tmp="${path}.tmp.$$"
|
||||
(umask 133; printf '%s' "$value" > "$tmp")
|
||||
chmod 0644 "$tmp"
|
||||
mv -f "$tmp" "$path"
|
||||
echo "created ${path}"
|
||||
}
|
||||
|
||||
write_secret minio_root_user "root-$(openssl rand -hex 6)"
|
||||
write_secret minio_root_password "$(openssl rand -hex 24)"
|
||||
write_secret s3_api_access_key_id "api-$(openssl rand -hex 8)"
|
||||
write_secret s3_api_secret_access_key "$(openssl rand -hex 24)"
|
||||
write_secret s3_worker_access_key_id "worker-$(openssl rand -hex 8)"
|
||||
write_secret s3_worker_secret_access_key "$(openssl rand -hex 24)"
|
||||
write_secret grafana_admin_password "$(openssl rand -hex 24)"
|
||||
bcrypt_hash() {
|
||||
local password="$1"
|
||||
python3 -c '
|
||||
import sys, bcrypt
|
||||
pw = sys.stdin.read().encode("utf-8")
|
||||
print(bcrypt.hashpw(pw, bcrypt.gensalt(rounds=10)).decode("ascii"), end="")
|
||||
' <<< "$password"
|
||||
}
|
||||
|
||||
if [ -s secrets/broker_worker_password ] && [ -s secrets/broker_worker_url ]; then
|
||||
echo "kept secrets/broker_worker_password secrets/broker_worker_url"
|
||||
write_infra_secret postgres_superuser_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret minio_root_user "root-$(openssl rand -hex 6)"
|
||||
write_infra_secret minio_root_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret redis_admin_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret redis_health_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret grafana_admin_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret grafana_prometheus_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret otel_prometheus_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret prometheus_self_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret prometheus_operator_password "$(openssl rand -hex 24)"
|
||||
write_infra_secret haproxy_stats_password "$(openssl rand -hex 24)"
|
||||
|
||||
# Render Prometheus web.yml (HTTPS + mTLS + Basic Auth bcrypt hashes) from template.
|
||||
if [ -s secrets/infra/prometheus_web.yml ]; then
|
||||
echo "kept secrets/infra/prometheus_web.yml"
|
||||
else
|
||||
wp=$(openssl rand -hex 24)
|
||||
(umask 133; printf '%s' "$wp" > secrets/broker_worker_password)
|
||||
chmod 0644 secrets/broker_worker_password
|
||||
(umask 133; printf '%s' "amqp://messenger-worker:${wp}@broker:5672/messenger" > secrets/broker_worker_url)
|
||||
chmod 0644 secrets/broker_worker_url
|
||||
echo "created secrets/broker_worker_password secrets/broker_worker_url"
|
||||
op_hash="$(bcrypt_hash "$(cat secrets/infra/prometheus_operator_password)")"
|
||||
gr_hash="$(bcrypt_hash "$(cat secrets/infra/grafana_prometheus_password)")"
|
||||
ot_hash="$(bcrypt_hash "$(cat secrets/infra/otel_prometheus_password)")"
|
||||
sf_hash="$(bcrypt_hash "$(cat secrets/infra/prometheus_self_password)")"
|
||||
|
||||
tmp="secrets/infra/prometheus_web.yml.tmp.$$"
|
||||
(
|
||||
umask 133
|
||||
python3 - "$op_hash" "$gr_hash" "$ot_hash" "$sf_hash" <<'PY' > "$tmp"
|
||||
import sys
|
||||
from pathlib import Path
|
||||
op_h, gr_h, ot_h, sf_h = sys.argv[1:5]
|
||||
tpl = Path("infra/prometheus/web.yml").read_text(encoding="utf-8")
|
||||
out = (
|
||||
tpl.replace("__OPERATOR_BCRYPT__", op_h)
|
||||
.replace("__GRAFANA_BCRYPT__", gr_h)
|
||||
.replace("__OTEL_BCRYPT__", ot_h)
|
||||
.replace("__SELF_BCRYPT__", sf_h)
|
||||
)
|
||||
sys.stdout.write(out)
|
||||
PY
|
||||
)
|
||||
chmod 0644 "$tmp"
|
||||
mv -f "$tmp" secrets/infra/prometheus_web.yml
|
||||
echo "created secrets/infra/prometheus_web.yml"
|
||||
fi
|
||||
|
||||
# Broker password lives in one place and is rendered into both files, so the
|
||||
# URL used by the app and the RabbitMQ config cannot drift apart.
|
||||
if [ -s secrets/broker_url ] && [ -s secrets/rabbitmq.conf ]; then
|
||||
echo "kept secrets/broker_url secrets/rabbitmq.conf"
|
||||
# Render HAProxy stats Basic Auth userlist fragment (SHA-512 crypt hash).
|
||||
if [ -s secrets/infra/haproxy_stats_auth.cfg ]; then
|
||||
echo "kept secrets/infra/haproxy_stats_auth.cfg"
|
||||
else
|
||||
bp=$(openssl rand -hex 24)
|
||||
(umask 133; printf '%s' "amqp://messenger:${bp}@broker:5672/messenger" > secrets/broker_url)
|
||||
chmod 0644 secrets/broker_url
|
||||
stats_hash="$(openssl passwd -6 -stdin < secrets/infra/haproxy_stats_password)"
|
||||
tmp="secrets/infra/haproxy_stats_auth.cfg.tmp.$$"
|
||||
(
|
||||
umask 133
|
||||
{
|
||||
printf 'default_vhost = messenger\n'
|
||||
printf 'default_user = messenger\n'
|
||||
printf 'default_pass = %s\n' "$bp"
|
||||
printf 'default_permissions.configure = ^(attachments\\.jobs|attachments\\.process|attachments\\.dlx|attachments\\.process\\.dlq)$\n'
|
||||
printf 'default_permissions.read = ^attachments\\.(jobs|process|dlx|process\\.dlq)$\n'
|
||||
printf 'default_permissions.write = ^attachments\\.(jobs|process|dlx|process\\.dlq)$\n'
|
||||
} > secrets/rabbitmq.conf
|
||||
printf 'userlist ops_stats\n'
|
||||
printf ' user operator password %s\n' "$stats_hash"
|
||||
} > "$tmp"
|
||||
)
|
||||
chmod 0644 secrets/rabbitmq.conf
|
||||
echo "created secrets/broker_url secrets/rabbitmq.conf"
|
||||
chmod 0644 "$tmp"
|
||||
mv -f "$tmp" secrets/infra/haproxy_stats_auth.cfg
|
||||
echo "created secrets/infra/haproxy_stats_auth.cfg"
|
||||
fi
|
||||
|
||||
@@ -1,54 +1,97 @@
|
||||
#!/bin/sh
|
||||
# Проверка приватности S3 вне API: анонимный доступ, права отдельных credentials
|
||||
# API, закрытая консоль. Секреты не печатаются.
|
||||
#!/usr/bin/env bash
|
||||
# Проверка приватности S3 вне API (lab7 HTTPS + CA + OpenBao-managed API IAM):
|
||||
# анонимный доступ -> 403, права отдельного API-пользователя из OpenBao,
|
||||
# закрытая консоль :9001. Секреты не печатаются.
|
||||
set -u
|
||||
cd "$(dirname "$0")/../.."
|
||||
env_file="${COMPOSE_ENV_FILE:-.env}"
|
||||
# shellcheck disable=SC1090
|
||||
set -a; . "./$env_file"; set +a
|
||||
endpoint="${S3_PUBLIC_ENDPOINT:-http://localhost:9000}"
|
||||
if [ -f "./$env_file" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
set -a; . "./$env_file"; set +a
|
||||
fi
|
||||
|
||||
endpoint="${S3_PUBLIC_ENDPOINT:-https://localhost:${S3_PUBLIC_PORT:-9000}}"
|
||||
bucket="${S3_BUCKET:-messenger-attachments}"
|
||||
compose="docker compose --env-file $env_file"
|
||||
ca_file="${CA_FILE:-$(pwd)/secrets/pki/ca.crt}"
|
||||
operator_dir="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
bao_addr="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
compose=(docker compose --env-file "$env_file")
|
||||
mc_image="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
|
||||
fail=0
|
||||
|
||||
report() { # status name
|
||||
if [ "$1" = ok ]; then echo "PASS $2"; else echo "FAIL $2"; fail=1; fi
|
||||
}
|
||||
|
||||
key=$($compose exec -T postgres psql -U "${POSTGRES_USER:-messenger}" -d "${POSTGRES_DB:-messenger}" -At \
|
||||
key=$("${compose[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -At \
|
||||
-c "SELECT object_key FROM attachments WHERE status = 'ready' ORDER BY created_at DESC LIMIT 1")
|
||||
if [ -z "$key" ]; then
|
||||
echo "FAIL no ready attachment to check; upload one first (make test)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' "$endpoint/$bucket/$key")
|
||||
[ "$code" = 403 ] && report ok "anonymous GET of a ready object -> 403" || report fail "anonymous GET of a ready object -> $code (want 403)"
|
||||
code=$(curl -s --cacert "$ca_file" -o /dev/null -w '%{http_code}' "$endpoint/$bucket/$key")
|
||||
[ "$code" = 403 ] && report ok "anonymous HTTPS GET of a ready object -> 403" || report fail "anonymous HTTPS GET of a ready object -> $code (want 403)"
|
||||
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' "$endpoint/$bucket/")
|
||||
[ "$code" = 403 ] && report ok "anonymous list of the bucket -> 403" || report fail "anonymous list of the bucket -> $code (want 403)"
|
||||
code=$(curl -s --cacert "$ca_file" -o /dev/null -w '%{http_code}' "$endpoint/$bucket/")
|
||||
[ "$code" = 403 ] && report ok "anonymous HTTPS list of the bucket -> 403" || report fail "anonymous HTTPS list of the bucket -> $code (want 403)"
|
||||
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' -X PUT --data-binary x "$endpoint/$bucket/attachments/anonymous-write")
|
||||
[ "$code" = 403 ] && report ok "anonymous PUT -> 403" || report fail "anonymous PUT -> $code (want 403)"
|
||||
code=$(curl -s --cacert "$ca_file" -o /dev/null -w '%{http_code}' -X PUT --data-binary x "$endpoint/$bucket/attachments/anonymous-write")
|
||||
[ "$code" = 403 ] && report ok "anonymous HTTPS PUT -> 403" || report fail "anonymous HTTPS PUT -> $code (want 403)"
|
||||
|
||||
# Fetch API S3 credentials cleanly via OpenBao operator mTLS auth (zero static app secrets on disk).
|
||||
tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/lab7-s3sec.XXXXXX")"
|
||||
trap 'rm -rf "$tmp_dir"' EXIT
|
||||
op_token="$(curl -fsS --cacert "$ca_file" \
|
||||
--cert "${operator_dir}/operator/operator.crt" \
|
||||
--key "${operator_dir}/operator/operator.key" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${bao_addr}/v1/auth/cert/login" | jq -r '.auth.client_token // empty')"
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "${tmp_dir}/auth.cfg"
|
||||
chmod 0600 "${tmp_dir}/auth.cfg"
|
||||
api_kv="$(curl -fsS --cacert "$ca_file" -K "${tmp_dir}/auth.cfg" \
|
||||
"${bao_addr}/v1/secret/data/messenger/api" | jq -c '.data.data')"
|
||||
curl -fsS --cacert "$ca_file" -K "${tmp_dir}/auth.cfg" -X POST \
|
||||
"${bao_addr}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
|
||||
api_key="$(printf '%s' "$api_kv" | jq -r '.s3_access_key_id')"
|
||||
api_sec="$(printf '%s' "$api_kv" | jq -r '.s3_secret_access_key')"
|
||||
|
||||
s3_cid="$("${compose[@]}" ps -q s3 | head -n 1)"
|
||||
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
|
||||
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
|
||||
|
||||
# The API credentials only, inside a one-off container (secrets come from files).
|
||||
api_mc() {
|
||||
$compose run --rm --no-deps -T --entrypoint /bin/sh s3-init -c '
|
||||
IFS= read -r k < /run/secrets/s3_api_access_key_id
|
||||
IFS= read -r s < /run/secrets/s3_api_secret_access_key
|
||||
export MC_CONFIG_DIR=/tmp/.mc MC_HOST_api="http://$k:$s@s3:9000"
|
||||
exec mc "$@"' sh "$@" >/dev/null 2>&1
|
||||
printf '%s\n%s\n' "$api_key" "$api_sec" \
|
||||
| docker run --rm -i \
|
||||
--network "$app_data_net" \
|
||||
--user 1000:1000 \
|
||||
--read-only --cap-drop ALL --security-opt no-new-privileges:true \
|
||||
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
|
||||
-v "${ca_file}:/run/certs/ca.crt:ro" \
|
||||
--entrypoint /bin/sh "$mc_image" -c '
|
||||
set -eu
|
||||
IFS= read -r k; IFS= read -r s
|
||||
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
export MC_HOST_api="https://${k}:${s}@s3:9000"
|
||||
exec mc "$@"
|
||||
' sh "$@" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
api_mc mb api/forbidden-bucket && report fail "API credentials can create buckets" || report ok "API credentials cannot create buckets"
|
||||
api_mc admin info api && report fail "API credentials can use admin API" || report ok "API credentials cannot use admin API"
|
||||
api_mc stat "api/$bucket/$key" && report ok "API credentials can read attachments/*" || report fail "API credentials cannot read attachments/*"
|
||||
api_mc stat "api/$bucket/outside-prefix" ; rc=$?
|
||||
api_mc cp /etc/hostname "api/$bucket/outside-prefix" && report fail "API credentials can write outside attachments/" || report ok "API credentials cannot write outside attachments/"
|
||||
: "$rc"
|
||||
api_mc stat "api/$bucket/$key" && report ok "API credentials can read attachments/* over HTTPS" || report fail "API credentials cannot read attachments/*"
|
||||
api_mc cp /etc/hostname "api/$bucket/outside-prefix" && report fail "API credentials can write outside staging/" || report ok "API credentials cannot write outside staging/"
|
||||
|
||||
port=$($compose port s3 9001 2>/dev/null || true)
|
||||
port=$("${compose[@]}" port s3 9001 2>/dev/null || true)
|
||||
[ -z "$port" ] && report ok "console port 9001 is not published" || report fail "console port 9001 is published ($port)"
|
||||
if curl -s -o /dev/null --max-time 3 http://localhost:9001; then report fail "console reachable on localhost:9001"; else report ok "console not reachable on localhost:9001"; fi
|
||||
if curl -s -o /dev/null --max-time 3 https://localhost:9001 --cacert "$ca_file"; then
|
||||
report fail "console reachable on localhost:9001"
|
||||
else
|
||||
report ok "console not reachable on localhost:9001"
|
||||
fi
|
||||
|
||||
exit "$fail"
|
||||
|
||||
+15
-3
@@ -58,12 +58,24 @@ def cli(*args, stdin=None):
|
||||
raise Failure('jobs.cli did not return JSON for ' + ' '.join(args))
|
||||
|
||||
|
||||
def redis_admin(*args):
|
||||
"""Run redis-cli as redis_admin over mTLS inside the redis container."""
|
||||
return compose(
|
||||
'exec', '-T', 'redis', 'sh', '-c',
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/redis_admin_password)" '
|
||||
'exec redis-cli --tls --cacert /run/certs/ca.crt '
|
||||
'--cert /run/certs/health.crt --key /run/certs/health.key '
|
||||
'--user redis_admin -h localhost -p 6379 "$@"',
|
||||
'--', *args,
|
||||
)
|
||||
|
||||
|
||||
def set_fault(key, value):
|
||||
compose('exec', '-T', 'redis', 'redis-cli', 'SET', key, value)
|
||||
redis_admin('SET', key, value)
|
||||
|
||||
|
||||
def clear_fault(key):
|
||||
compose('exec', '-T', 'redis', 'redis-cli', 'DEL', key)
|
||||
redis_admin('DEL', key)
|
||||
|
||||
|
||||
def clear_faults():
|
||||
@@ -71,7 +83,7 @@ def clear_faults():
|
||||
"local keys=redis.call('keys',ARGV[1]) "
|
||||
"for i=1,#keys do redis.call('del',keys[i]) end return #keys"
|
||||
)
|
||||
compose('exec', '-T', 'redis', 'redis-cli', 'EVAL', script, '0', 'fault:*')
|
||||
redis_admin('EVAL', script, '0', 'fault:*')
|
||||
|
||||
|
||||
def rabbit_queues():
|
||||
|
||||
@@ -283,7 +283,7 @@ def sequential_uploads(ctx, actor, chat, count, delay):
|
||||
elapsed = (time.monotonic() - started) * 1000
|
||||
consumed = True
|
||||
if delay:
|
||||
out = stand.compose('exec', '-T', 'redis', 'redis-cli', 'GET', key).stdout.strip()
|
||||
out = stand.redis_admin('GET', key).stdout.strip()
|
||||
consumed = out == ''
|
||||
rows.append({'request_id': r['headers']['X-Request-Id'], 'status': r['status'],
|
||||
'elapsed_ms': elapsed, 'consumed': consumed,
|
||||
|
||||
+155
-56
@@ -1,11 +1,13 @@
|
||||
"""Shared lab6 helpers: Prometheus/Loki/Tempo/Grafana client, controlled app
|
||||
environment, SQL table lock, batch drain. Python 3.9+, standard library only."""
|
||||
"""Shared lab6 helpers (updated for lab7 HTTPS/mTLS + Basic Auth + network
|
||||
isolation): Prometheus/Loki/Tempo/Grafana client, controlled app environment,
|
||||
SQL table lock, batch drain. Python 3.9+, standard library only."""
|
||||
import base64
|
||||
import binascii
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -59,25 +61,93 @@ SDK_DEFAULTS = {
|
||||
'LOG_LEVEL': 'INFO',
|
||||
}
|
||||
|
||||
_DEFAULT_CA_FILE = None
|
||||
_PROM_PREFIX = None
|
||||
|
||||
|
||||
def utc_now():
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
|
||||
|
||||
def _operator_dir():
|
||||
env_dir = os.environ.get('LAB7_OPERATOR_DIR')
|
||||
if env_dir:
|
||||
return Path(env_dir)
|
||||
xdg = os.environ.get('XDG_STATE_HOME')
|
||||
base = Path(xdg) if xdg else (Path.home() / '.local/state')
|
||||
return base / 'mtusi-lab7-operator'
|
||||
|
||||
|
||||
def _default_ca_path(ca_file=None):
|
||||
for candidate in (ca_file, _DEFAULT_CA_FILE, os.environ.get('CA_FILE'),
|
||||
str(ROOT / 'secrets/pki/ca.crt')):
|
||||
if candidate and Path(candidate).is_file():
|
||||
return str(candidate)
|
||||
return None
|
||||
|
||||
|
||||
def _is_prometheus_url(url):
|
||||
if _PROM_PREFIX and url.startswith(_PROM_PREFIX):
|
||||
return True
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
return parsed.port == 9090 or parsed.path.startswith('/api/v1/query') or \
|
||||
parsed.path.startswith('/api/v1/series') or \
|
||||
parsed.path.startswith('/api/v1/metadata') or \
|
||||
parsed.path.startswith('/api/v1/label/') or \
|
||||
parsed.path.startswith('/api/v1/rules') or \
|
||||
parsed.path == '/-/ready'
|
||||
|
||||
|
||||
def _prom_basic_auth_header():
|
||||
pw_path = ROOT / 'secrets/infra/prometheus_operator_password'
|
||||
if not pw_path.is_file():
|
||||
return None
|
||||
token = base64.b64encode(b'operator:' + pw_path.read_bytes().strip()).decode()
|
||||
return {'Authorization': 'Basic ' + token}
|
||||
|
||||
|
||||
def _ssl_context_for(url, ca_file=None, use_client_cert=False):
|
||||
if not url.startswith('https://'):
|
||||
return None
|
||||
ca_path = _default_ca_path(ca_file)
|
||||
ctx = ssl.create_default_context(cafile=ca_path)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if use_client_cert:
|
||||
op_dir = _operator_dir() / 'operator'
|
||||
cert = op_dir / 'operator.crt'
|
||||
key = op_dir / 'operator.key'
|
||||
if cert.is_file() and key.is_file():
|
||||
ctx.load_cert_chain(certfile=str(cert), keyfile=str(key))
|
||||
return ctx
|
||||
|
||||
|
||||
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
|
||||
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
_NoRedirect())
|
||||
def _opener_for(url, ca_file=None, use_client_cert=False):
|
||||
handlers = [urllib.request.ProxyHandler({}), _NoRedirect()]
|
||||
ctx = _ssl_context_for(url, ca_file=ca_file, use_client_cert=use_client_cert)
|
||||
if ctx is not None:
|
||||
handlers.append(urllib.request.HTTPSHandler(context=ctx))
|
||||
return urllib.request.build_opener(*handlers)
|
||||
|
||||
|
||||
def http_get(url, headers=None, timeout=HTTP_TIMEOUT):
|
||||
def http_get(url, headers=None, timeout=HTTP_TIMEOUT, ca_file=None,
|
||||
use_client_cert=None):
|
||||
"""GET returning (status, bytes); never prints the URL query/headers."""
|
||||
request = urllib.request.Request(url, headers=headers or {})
|
||||
is_prom = _is_prometheus_url(url)
|
||||
need_mtls = is_prom if use_client_cert is None else bool(use_client_cert)
|
||||
req_headers = dict(headers or {})
|
||||
if is_prom and 'Authorization' not in req_headers:
|
||||
prom_auth = _prom_basic_auth_header()
|
||||
if prom_auth:
|
||||
req_headers.update(prom_auth)
|
||||
request = urllib.request.Request(url, headers=req_headers)
|
||||
opener = _opener_for(url, ca_file=ca_file, use_client_cert=need_mtls)
|
||||
try:
|
||||
with _OPENER.open(request, timeout=timeout) as response:
|
||||
with opener.open(request, timeout=timeout) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
with error:
|
||||
@@ -87,8 +157,10 @@ def http_get(url, headers=None, timeout=HTTP_TIMEOUT):
|
||||
type(exc).__name__ + ')') from None
|
||||
|
||||
|
||||
def http_json(url, headers=None, timeout=HTTP_TIMEOUT, allow=(200,)):
|
||||
status, data = http_get(url, headers, timeout)
|
||||
def http_json(url, headers=None, timeout=HTTP_TIMEOUT, allow=(200,),
|
||||
ca_file=None, use_client_cert=None):
|
||||
status, data = http_get(url, headers, timeout, ca_file=ca_file,
|
||||
use_client_cert=use_client_cert)
|
||||
if status not in allow:
|
||||
raise Failure('GET ' + url.split('?')[0] + ': status ' + str(status))
|
||||
try:
|
||||
@@ -196,25 +268,34 @@ def normalize_trace(document):
|
||||
class ObsClient:
|
||||
def __init__(self, prometheus_url, grafana_url, password_file=None,
|
||||
base_url=None, ca_file=None):
|
||||
global _DEFAULT_CA_FILE, _PROM_PREFIX
|
||||
self.prometheus = prometheus_url.rstrip('/')
|
||||
self.grafana = grafana_url.rstrip('/')
|
||||
self.base_url = base_url
|
||||
self.ca_file = ca_file
|
||||
path = Path(password_file) if password_file else (
|
||||
ROOT / 'secrets/grafana_admin_password')
|
||||
if ca_file:
|
||||
_DEFAULT_CA_FILE = ca_file
|
||||
_PROM_PREFIX = self.prometheus
|
||||
candidates = [Path(password_file)] if password_file else [
|
||||
ROOT / 'secrets/infra/grafana_admin_password',
|
||||
ROOT / 'secrets/grafana_admin_password',
|
||||
]
|
||||
self._auth = None
|
||||
if path.exists():
|
||||
token = base64.b64encode(
|
||||
b'admin:' + path.read_bytes().strip()).decode()
|
||||
self._auth = {'Authorization': 'Basic ' + token}
|
||||
for path in candidates:
|
||||
if path.exists():
|
||||
token = base64.b64encode(
|
||||
b'admin:' + path.read_bytes().strip()).decode()
|
||||
self._auth = {'Authorization': 'Basic ' + token}
|
||||
break
|
||||
|
||||
# -- Prometheus
|
||||
# -- Prometheus (HTTPS + mTLS operator cert + Basic Auth)
|
||||
def prom_query(self, expr, at=None):
|
||||
params = {'query': expr}
|
||||
if at is not None:
|
||||
params['time'] = str(at)
|
||||
_, body = http_json(self.prometheus + '/api/v1/query?' +
|
||||
urllib.parse.urlencode(params))
|
||||
urllib.parse.urlencode(params),
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
if not isinstance(body, dict) or body.get('status') != 'success':
|
||||
raise Failure('Prometheus query failed')
|
||||
return body['data']['result']
|
||||
@@ -229,20 +310,23 @@ class ObsClient:
|
||||
params = {'query': expr, 'start': str(start), 'end': str(end),
|
||||
'step': str(step)}
|
||||
_, body = http_json(self.prometheus + '/api/v1/query_range?' +
|
||||
urllib.parse.urlencode(params))
|
||||
urllib.parse.urlencode(params),
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
if not isinstance(body, dict) or body.get('status') != 'success':
|
||||
raise Failure('Prometheus range query failed')
|
||||
return body['data']['result']
|
||||
|
||||
def prom_names(self):
|
||||
_, body = http_json(self.prometheus + '/api/v1/label/__name__/values')
|
||||
_, body = http_json(self.prometheus + '/api/v1/label/__name__/values',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
return sorted(body['data'])
|
||||
|
||||
# -- Grafana proxied backends
|
||||
# -- Grafana proxied backends (HTTPS + Basic Auth; Grafana->DS uses mTLS)
|
||||
def _grafana_get(self, path, allow=(200,)):
|
||||
if self._auth is None:
|
||||
raise Failure('Grafana password file is missing')
|
||||
return http_get(self.grafana + path, self._auth)
|
||||
return http_get(self.grafana + path, self._auth,
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
|
||||
def grafana_json(self, path, allow=(200,)):
|
||||
status, data = self._grafana_get(path)
|
||||
@@ -305,7 +389,8 @@ class ObsClient:
|
||||
raise Failure('Grafana password file is missing')
|
||||
status, data = http_get(
|
||||
self.grafana + path,
|
||||
{**self._auth, 'Accept': 'application/json'})
|
||||
{**self._auth, 'Accept': 'application/json'},
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
if status == 200:
|
||||
try:
|
||||
return normalize_trace(json.loads(data))
|
||||
@@ -317,14 +402,22 @@ class ObsClient:
|
||||
return None
|
||||
time.sleep(1)
|
||||
|
||||
# -- closed backends from inside the compose network
|
||||
# -- closed backends from inside the compose network (HTTPS + CA verified)
|
||||
def internal_get(self, service, port, path):
|
||||
script = (
|
||||
"const fs=require('node:fs'),https=require('node:https');"
|
||||
"const [h,p,u]=process.argv.slice(1);"
|
||||
"fetch('http://'+h+':'+p+u,{signal:AbortSignal.timeout(5000)})"
|
||||
".then(async r=>{const b=await r.text();"
|
||||
"console.log(JSON.stringify({status:r.status,body:b.slice(0,1048576)}))})"
|
||||
".catch(e=>{console.log(JSON.stringify({status:0,body:String(e.name)}))})")
|
||||
"const req=https.request({host:h,port:Number(p),path:u,method:'GET',"
|
||||
"ca:fs.readFileSync('/run/certs/ca.crt'),servername:h,"
|
||||
"rejectUnauthorized:true,timeout:5000},res=>{"
|
||||
"let b='';res.setEncoding('utf8');"
|
||||
"res.on('data',c=>{if(b.length<1048576)b+=c});"
|
||||
"res.on('end',()=>console.log(JSON.stringify({status:res.statusCode,body:b})));"
|
||||
"});"
|
||||
"req.on('timeout',()=>req.destroy(new Error('Timeout')));"
|
||||
"req.on('error',e=>console.log(JSON.stringify({status:0,body:String(e.code||e.message)})));"
|
||||
"req.end();"
|
||||
)
|
||||
result = stand.compose('exec', '-T', 'api', 'node', '-e', script,
|
||||
service, str(port), path, check_result=False)
|
||||
try:
|
||||
@@ -342,26 +435,40 @@ class ObsClient:
|
||||
problems = []
|
||||
if self.base_url:
|
||||
try:
|
||||
status, _ = http_get(self.base_url.rstrip('/') + '/health/ready')
|
||||
status, _ = http_get(self.base_url.rstrip('/') + '/health/ready',
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
self._check(problems, 'api-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('api-ready')
|
||||
probes = (('otel-collector', 13133, '/', 'collector-health'),
|
||||
('loki', 3100, '/ready', 'loki-ready'),
|
||||
('tempo', 3200, '/ready', 'tempo-ready'))
|
||||
for service, port, path, name in probes:
|
||||
try:
|
||||
status, _ = self.internal_get(service, port, path)
|
||||
self._check(problems, name, status == 200)
|
||||
except Failure:
|
||||
problems.append(name)
|
||||
# Collector health over HTTPS from api (same app_data network).
|
||||
try:
|
||||
status, _ = http_get(self.prometheus + '/-/ready')
|
||||
status, _ = self.internal_get('otel-collector', 13133, '/')
|
||||
self._check(problems, 'collector-health', status == 200)
|
||||
except Failure:
|
||||
problems.append('collector-health')
|
||||
# Loki and Tempo live on isolated obs_net; verify via Grafana's mTLS proxy.
|
||||
try:
|
||||
body = self.grafana_json('/api/datasources/uid/loki/health',
|
||||
allow=(200, 400, 404, 500))
|
||||
self._check(problems, 'loki-ready',
|
||||
isinstance(body, dict) and
|
||||
body.get('status', '').upper() == 'OK')
|
||||
except Failure:
|
||||
problems.append('loki-ready')
|
||||
try:
|
||||
status, _ = self._grafana_get('/api/datasources/proxy/uid/tempo/api/echo')
|
||||
self._check(problems, 'tempo-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('tempo-ready')
|
||||
try:
|
||||
status, _ = http_get(self.prometheus + '/-/ready',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
self._check(problems, 'prometheus-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('prometheus-ready')
|
||||
try:
|
||||
status, _ = http_get(self.grafana + '/api/health')
|
||||
status, _ = http_get(self.grafana + '/api/health',
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
self._check(problems, 'grafana-health', status == 200)
|
||||
except Failure:
|
||||
problems.append('grafana-health')
|
||||
@@ -388,8 +495,6 @@ class ObsClient:
|
||||
try:
|
||||
for uid in DATASOURCE_UIDS:
|
||||
if uid == 'tempo':
|
||||
# The Tempo plugin has no health resource; its API echo
|
||||
# through the datasource proxy proves the connection.
|
||||
status, _ = self._grafana_get(
|
||||
'/api/datasources/proxy/uid/tempo/api/echo')
|
||||
self._check(problems, 'datasource:tempo', status == 200)
|
||||
@@ -400,7 +505,8 @@ class ObsClient:
|
||||
self._check(problems, 'datasource:' + uid,
|
||||
isinstance(body, dict) and
|
||||
body.get('status', '').upper() == 'OK')
|
||||
_, rules = http_json(self.prometheus + '/api/v1/rules')
|
||||
_, rules = http_json(self.prometheus + '/api/v1/rules',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
names = {r['name'] for g in rules['data']['groups']
|
||||
for r in g['rules']}
|
||||
for alert in RULE_ALERTS:
|
||||
@@ -518,8 +624,6 @@ class ObsClient:
|
||||
yield set_overrides
|
||||
finally:
|
||||
if dirty[0]:
|
||||
# Restore the original effective values as controller env so the
|
||||
# recreated containers match what was running before.
|
||||
for key in MUTABLE_KEYS:
|
||||
original = baseline.get(('api', key))
|
||||
if original is not None and key in touched:
|
||||
@@ -542,10 +646,9 @@ class ObsClient:
|
||||
self.wait_ready(app_telemetry=True, provisioning=True,
|
||||
timeout=120)
|
||||
|
||||
# -- foreign faults
|
||||
# -- foreign faults (Redis over mTLS + redis_admin ACL)
|
||||
def foreign_faults(self):
|
||||
result = stand.compose('exec', '-T', 'redis', 'redis-cli', '--scan',
|
||||
'--pattern', 'fault:*')
|
||||
result = stand.redis_admin('--scan', '--pattern', 'fault:*')
|
||||
return sorted(line for line in result.stdout.split() if line)
|
||||
|
||||
def require_no_foreign_faults(self):
|
||||
@@ -558,8 +661,8 @@ class ObsClient:
|
||||
# --------------------------------------------------------------- PostgreSQL
|
||||
|
||||
def psql(sql, timeout=30):
|
||||
script = 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 ' \
|
||||
'-At -F , -c "$SQL"'
|
||||
script = 'psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" ' \
|
||||
'-v ON_ERROR_STOP=1 -At -F , -c "$SQL"'
|
||||
result = subprocess.run(
|
||||
['docker', 'compose', '--env-file', stand.ENV_FILE, 'exec', '-T',
|
||||
'-e', 'SQL=' + sql, 'postgres', 'sh', '-c', script],
|
||||
@@ -579,7 +682,8 @@ def hold_table_lock(table):
|
||||
process = subprocess.Popen(
|
||||
['docker', 'compose', '--env-file', stand.ENV_FILE, 'exec', '-T',
|
||||
'postgres', 'sh', '-c',
|
||||
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -At'],
|
||||
'psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" '
|
||||
'-v ON_ERROR_STOP=1 -At'],
|
||||
cwd=ROOT, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, bufsize=1)
|
||||
pid = None
|
||||
@@ -630,12 +734,7 @@ def hold_table_lock(table):
|
||||
|
||||
|
||||
def wait_drained(attachment_ids, obs=None, timeout=120, flush_telemetry=True):
|
||||
"""Batch-check jobs/outbox/attachments in PostgreSQL (no HTTP polling).
|
||||
|
||||
Returns {'drained': bool, 'states': {id: status}, 'queued': n,
|
||||
'outbox': n, 'seconds': t, 'timestamps': ...}. A vanished known ID is a
|
||||
Failure; non-ready at the deadline is reported, not raised.
|
||||
"""
|
||||
"""Batch-check jobs/outbox/attachments in PostgreSQL (no HTTP polling)."""
|
||||
ids = list(attachment_ids)
|
||||
for item in ids:
|
||||
uuid.UUID(item)
|
||||
|
||||
Executable
+391
@@ -0,0 +1,391 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Idempotent OpenBao & Backend Store Bootstrap (non-dev Raft).
|
||||
# - Initializes OpenBao if uninitialized (5 Shamir shares, threshold 3 saved 0600
|
||||
# in $LAB7_OPERATOR_DIR/openbao/ outside Git, NEVER mounted into containers).
|
||||
# - Unseals via scripts/openbao-unseal.sh.
|
||||
# - Enables kv-v2 at secret/ and auth/cert, uploads ca.crl, writes least-privilege
|
||||
# HCL policies and cert roles, verifies operator mTLS login, and REVOKES the
|
||||
# initial root token (never persisted to disk, .env, or containers).
|
||||
# - Idempotently seeds scoped KV v2 secrets and converges live accounts in
|
||||
# PostgreSQL, Redis (mTLS + ACL SAVE), MinIO (HTTPS + CA), and RabbitMQ
|
||||
# (EXTERNAL passwordless CN users + strict producer/consumer ACLs).
|
||||
# - Never prints secrets, tokens, or unseal shares.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
BAO_OP_DIR="${OPERATOR_DIR}/openbao"
|
||||
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
|
||||
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
|
||||
CA_CERT="${CA_FILE:-$(pwd)/secrets/pki/ca.crt}"
|
||||
CRL_FILE="$(pwd)/secrets/pki/ca.crl"
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
COMPOSE_ENV="${COMPOSE_ENV_FILE:-.env}"
|
||||
COMPOSE=(docker compose --env-file "$COMPOSE_ENV")
|
||||
MC_IMAGE="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
|
||||
|
||||
umask 077
|
||||
mkdir -p "$BAO_OP_DIR"
|
||||
chmod 0700 "$BAO_OP_DIR"
|
||||
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-bao-boot.XXXXXX")"
|
||||
ROOT_CFG="${TMP_DIR}/root-auth.cfg"
|
||||
OP_CFG="${TMP_DIR}/op-auth.cfg"
|
||||
|
||||
cleanup() {
|
||||
if [ -s "$OP_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
if [ -s "$ROOT_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$ROOT_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$TMP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
for req in "$CA_CERT" "$CRL_FILE" "$OP_CERT" "$OP_KEY"; do
|
||||
if [ ! -s "$req" ]; then
|
||||
echo "error: required PKI artifact missing: ${req}; run scripts/pki-bootstrap.sh first" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
write_token_cfg() {
|
||||
local cfg_path="$1"
|
||||
local token="$2"
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$token" > "$cfg_path"
|
||||
chmod 0600 "$cfg_path"
|
||||
}
|
||||
|
||||
bao_api() {
|
||||
local cfg="$1"
|
||||
local method="$2"
|
||||
local path="$3"
|
||||
shift 3
|
||||
curl -fsS --cacert "$CA_CERT" -K "$cfg" -X "$method" "$@" "${BAO_ADDR}/v1/${path}"
|
||||
}
|
||||
|
||||
bao_login_operator() {
|
||||
local login_json token
|
||||
login_json="$(curl -fsS --cacert "$CA_CERT" \
|
||||
--cert "$OP_CERT" --key "$OP_KEY" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${BAO_ADDR}/v1/auth/cert/login")"
|
||||
token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty')"
|
||||
if [ -z "$token" ]; then
|
||||
echo "error: operator mTLS login to OpenBao failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
write_token_cfg "$OP_CFG" "$token"
|
||||
}
|
||||
|
||||
write_policy() {
|
||||
local cfg="$1"
|
||||
local name="$2"
|
||||
local hcl_file="$3"
|
||||
jq -Rs '{policy: .}' < "$hcl_file" \
|
||||
| bao_api "$cfg" PUT "sys/policies/acl/${name}" \
|
||||
-H 'Content-Type: application/json' --data-binary @- >/dev/null
|
||||
}
|
||||
|
||||
write_cert_role() {
|
||||
local cfg="$1"
|
||||
local role="$2"
|
||||
local cn_pattern="$3"
|
||||
local dns_san="$4"
|
||||
local policy="$5"
|
||||
local no_default="$6"
|
||||
local ttl="$7"
|
||||
local max_ttl="$8"
|
||||
jq -n \
|
||||
--rawfile cert "$CA_CERT" \
|
||||
--arg role "$role" \
|
||||
--arg cn "$cn_pattern" \
|
||||
--arg san "$dns_san" \
|
||||
--arg policy "$policy" \
|
||||
--argjson no_def "$no_default" \
|
||||
--arg ttl "$ttl" \
|
||||
--arg max_ttl "$max_ttl" \
|
||||
'{
|
||||
display_name: $role,
|
||||
certificate: $cert,
|
||||
allowed_common_names: [$cn],
|
||||
allowed_dns_sans: [$san],
|
||||
token_policies: [$policy],
|
||||
token_no_default_policy: $no_def,
|
||||
token_ttl: $ttl,
|
||||
token_max_ttl: $max_ttl
|
||||
}' \
|
||||
| bao_api "$cfg" POST "auth/cert/certs/${role}" \
|
||||
-H 'Content-Type: application/json' --data-binary @- >/dev/null
|
||||
}
|
||||
|
||||
upload_crl() {
|
||||
local cfg="$1"
|
||||
jq -Rs '{crl: .}' < "$CRL_FILE" \
|
||||
| bao_api "$cfg" POST "auth/cert/crls/lab7-ca" \
|
||||
-H 'Content-Type: application/json' --data-binary @- >/dev/null
|
||||
}
|
||||
|
||||
# 1. Wait for OpenBao HTTPS listener
|
||||
seal_json=""
|
||||
for _ in $(seq 1 40); do
|
||||
if seal_json="$(curl -fsS --cacert "$CA_CERT" "${BAO_ADDR}/v1/sys/seal-status" 2>/dev/null)"; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ -z "$seal_json" ]; then
|
||||
echo "error: OpenBao HTTPS listener unreachable at ${BAO_ADDR}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
initialized="$(printf '%s' "$seal_json" | jq -r '.initialized')"
|
||||
sealed="$(printf '%s' "$seal_json" | jq -r '.sealed')"
|
||||
|
||||
# 2. First-time initialization (or idempotent operator re-login)
|
||||
if [ "$initialized" != "true" ]; then
|
||||
init_json="$(curl -fsS --cacert "$CA_CERT" -X POST \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data '{"secret_shares":5,"secret_threshold":3}' \
|
||||
"${BAO_ADDR}/v1/sys/init")"
|
||||
|
||||
for i in 0 1 2 3 4; do
|
||||
idx=$((i + 1))
|
||||
printf '%s' "$init_json" | jq -r ".keys_base64[${i}]" > "${BAO_OP_DIR}/unseal-share-${idx}"
|
||||
chmod 0600 "${BAO_OP_DIR}/unseal-share-${idx}"
|
||||
done
|
||||
|
||||
root_token="$(printf '%s' "$init_json" | jq -r '.root_token')"
|
||||
write_token_cfg "$ROOT_CFG" "$root_token"
|
||||
unset init_json root_token
|
||||
echo "initialized OpenBao (5 shares / threshold 3 saved in ${BAO_OP_DIR})"
|
||||
|
||||
./scripts/openbao-unseal.sh --from-operator-dir "$BAO_OP_DIR"
|
||||
|
||||
# Wait briefly after unseal for Raft leader readiness
|
||||
for _ in $(seq 1 20); do
|
||||
if bao_api "$ROOT_CFG" GET "sys/mounts" >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# Enable kv-v2 at secret/
|
||||
mounts_json="$(bao_api "$ROOT_CFG" GET "sys/mounts")"
|
||||
if ! printf '%s' "$mounts_json" | jq -e 'has("secret/")' >/dev/null; then
|
||||
bao_api "$ROOT_CFG" POST "sys/mounts/secret" \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data '{"type":"kv","options":{"version":"2"}}' >/dev/null
|
||||
fi
|
||||
|
||||
# Enable auth/cert
|
||||
auth_json="$(bao_api "$ROOT_CFG" GET "sys/auth")"
|
||||
if ! printf '%s' "$auth_json" | jq -e 'has("cert/")' >/dev/null; then
|
||||
bao_api "$ROOT_CFG" POST "sys/auth/cert" \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data '{"type":"cert"}' >/dev/null
|
||||
fi
|
||||
|
||||
# Install all 4 ACL policies
|
||||
write_policy "$ROOT_CFG" "api-policy" infra/openbao/policies/api.hcl
|
||||
write_policy "$ROOT_CFG" "worker-policy" infra/openbao/policies/worker.hcl
|
||||
write_policy "$ROOT_CFG" "migrator-policy" infra/openbao/policies/migrator.hcl
|
||||
write_policy "$ROOT_CFG" "operator-policy" infra/openbao/policies/operator.hcl
|
||||
|
||||
# Upload initial CRL and register all 4 cert roles
|
||||
upload_crl "$ROOT_CFG"
|
||||
write_cert_role "$ROOT_CFG" "messenger-api" "messenger-api-*" "messenger-api" "api-policy" true "5m" "30m"
|
||||
write_cert_role "$ROOT_CFG" "messenger-worker" "messenger-worker-*" "messenger-worker" "worker-policy" true "5m" "30m"
|
||||
write_cert_role "$ROOT_CFG" "messenger-migrator" "messenger-migrator-*" "messenger-migrator" "migrator-policy" true "2m" "5m"
|
||||
write_cert_role "$ROOT_CFG" "messenger-operator" "messenger-operator-*" "messenger-operator" "operator-policy" false "15m" "1h"
|
||||
|
||||
# Verify operator mTLS auth succeeds BEFORE revoking root token
|
||||
bao_login_operator
|
||||
|
||||
# Permanently revoke the initial root token (zero root token custody on disk!)
|
||||
bao_api "$ROOT_CFG" POST "auth/token/revoke-self" >/dev/null
|
||||
rm -f "$ROOT_CFG"
|
||||
echo "configured OpenBao kv-v2, auth/cert, policies, CRL and revoked initial root token"
|
||||
else
|
||||
if [ "$sealed" = "true" ]; then
|
||||
./scripts/openbao-unseal.sh --from-operator-dir "$BAO_OP_DIR"
|
||||
fi
|
||||
bao_login_operator
|
||||
# Idempotently converge workload policies, cert roles, and CRL using operator cert
|
||||
write_policy "$OP_CFG" "api-policy" infra/openbao/policies/api.hcl
|
||||
write_policy "$OP_CFG" "worker-policy" infra/openbao/policies/worker.hcl
|
||||
write_policy "$OP_CFG" "migrator-policy" infra/openbao/policies/migrator.hcl
|
||||
upload_crl "$OP_CFG"
|
||||
write_cert_role "$OP_CFG" "messenger-api" "messenger-api-*" "messenger-api" "api-policy" true "5m" "30m"
|
||||
write_cert_role "$OP_CFG" "messenger-worker" "messenger-worker-*" "messenger-worker" "worker-policy" true "5m" "30m"
|
||||
write_cert_role "$OP_CFG" "messenger-migrator" "messenger-migrator-*" "messenger-migrator" "migrator-policy" true "2m" "5m"
|
||||
echo "authenticated to initialized OpenBao via messenger-operator mTLS cert"
|
||||
fi
|
||||
|
||||
# 3. Read or generate scoped KV v2 secrets (never written to .env or ./secrets/)
|
||||
read_kv_optional() {
|
||||
local path="$1"
|
||||
local body code
|
||||
code="$(curl -sS --cacert "$CA_CERT" -K "$OP_CFG" -o "${TMP_DIR}/kv.out" -w '%{http_code}' \
|
||||
"${BAO_ADDR}/v1/secret/data/${path}")"
|
||||
if [ "$code" = "200" ]; then
|
||||
jq -c '.data.data' "${TMP_DIR}/kv.out"
|
||||
else
|
||||
printf ''
|
||||
fi
|
||||
}
|
||||
|
||||
write_kv() {
|
||||
local path="$1"
|
||||
local payload="$2"
|
||||
printf '%s' "$payload" \
|
||||
| jq '{data: .}' \
|
||||
| bao_api "$OP_CFG" POST "secret/data/${path}" \
|
||||
-H 'Content-Type: application/json' --data-binary @- >/dev/null
|
||||
}
|
||||
|
||||
api_cn="$(openssl x509 -in secrets/pki/api/client.crt -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
worker_cn="$(openssl x509 -in secrets/pki/worker/client.crt -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
api_cn="${api_cn:-messenger-api-g1}"
|
||||
worker_cn="${worker_cn:-messenger-worker-g1}"
|
||||
|
||||
api_kv="$(read_kv_optional "messenger/api")"
|
||||
if [ -z "$api_kv" ]; then
|
||||
api_kv="$(jq -n \
|
||||
--arg db_pass "$(openssl rand -hex 24)" \
|
||||
--arg redis_pass "$(openssl rand -hex 24)" \
|
||||
--arg s3_key "api-$(openssl rand -hex 8)" \
|
||||
--arg s3_sec "$(openssl rand -hex 24)" \
|
||||
--arg metrics "$(openssl rand -hex 24)" \
|
||||
'{
|
||||
db_user: "messenger_api",
|
||||
db_password: $db_pass,
|
||||
redis_user: "messenger_api",
|
||||
redis_password: $redis_pass,
|
||||
s3_access_key_id: $s3_key,
|
||||
s3_secret_access_key: $s3_sec,
|
||||
metrics_token: $metrics
|
||||
}')"
|
||||
write_kv "messenger/api" "$api_kv"
|
||||
echo "seeded OpenBao secret/messenger/api"
|
||||
else
|
||||
echo "kept existing OpenBao secret/messenger/api"
|
||||
fi
|
||||
|
||||
worker_kv="$(read_kv_optional "messenger/worker")"
|
||||
if [ -z "$worker_kv" ]; then
|
||||
worker_kv="$(jq -n \
|
||||
--arg db_pass "$(openssl rand -hex 24)" \
|
||||
--arg s3_key "worker-$(openssl rand -hex 8)" \
|
||||
--arg s3_sec "$(openssl rand -hex 24)" \
|
||||
--arg broker_user "$worker_cn" \
|
||||
'{
|
||||
db_user: "messenger_worker",
|
||||
db_password: $db_pass,
|
||||
s3_access_key_id: $s3_key,
|
||||
s3_secret_access_key: $s3_sec,
|
||||
broker_user: $broker_user
|
||||
}')"
|
||||
write_kv "messenger/worker" "$worker_kv"
|
||||
echo "seeded OpenBao secret/messenger/worker"
|
||||
else
|
||||
echo "kept existing OpenBao secret/messenger/worker"
|
||||
fi
|
||||
|
||||
migrator_kv="$(read_kv_optional "messenger/migrator")"
|
||||
if [ -z "$migrator_kv" ]; then
|
||||
migrator_kv="$(jq -n \
|
||||
--arg db_pass "$(openssl rand -hex 24)" \
|
||||
'{
|
||||
db_user: "messenger_migrator",
|
||||
db_password: $db_pass
|
||||
}')"
|
||||
write_kv "messenger/migrator" "$migrator_kv"
|
||||
echo "seeded OpenBao secret/messenger/migrator"
|
||||
else
|
||||
echo "kept existing OpenBao secret/messenger/migrator"
|
||||
fi
|
||||
|
||||
# Seed operator-admin reference copy (operator-policy ONLY)
|
||||
op_admin_kv="$(jq -n \
|
||||
--rawfile pg_pass secrets/infra/postgres_superuser_password \
|
||||
--rawfile minio_user secrets/infra/minio_root_user \
|
||||
--rawfile minio_pass secrets/infra/minio_root_password \
|
||||
--rawfile redis_admin secrets/infra/redis_admin_password \
|
||||
--rawfile grafana_pass secrets/infra/grafana_admin_password \
|
||||
'{
|
||||
pg_admin_password: ($pg_pass | gsub("\r|\n"; "")),
|
||||
minio_root_user: ($minio_user | gsub("\r|\n"; "")),
|
||||
minio_root_password: ($minio_pass | gsub("\r|\n"; "")),
|
||||
redis_admin_password: ($redis_admin | gsub("\r|\n"; "")),
|
||||
grafana_admin_password: ($grafana_pass | gsub("\r|\n"; ""))
|
||||
}')"
|
||||
write_kv "messenger/operator-admin" "$op_admin_kv"
|
||||
|
||||
# 4. Converge live backend auth stores (PostgreSQL, Redis, MinIO, RabbitMQ)
|
||||
|
||||
# 4a. PostgreSQL least-privilege roles & scram-sha-256 passwords
|
||||
pg_migrator_pass="$(printf '%s' "$migrator_kv" | jq -r '.db_password')"
|
||||
pg_api_pass="$(printf '%s' "$api_kv" | jq -r '.db_password')"
|
||||
pg_worker_pass="$(printf '%s' "$worker_kv" | jq -r '.db_password')"
|
||||
|
||||
{
|
||||
cat infra/postgres/01-init-roles.sql
|
||||
printf "\nSET password_encryption = 'scram-sha-256';\n"
|
||||
printf "ALTER ROLE messenger_migrator WITH LOGIN PASSWORD '%s';\n" "$pg_migrator_pass"
|
||||
printf "ALTER ROLE messenger_api WITH LOGIN PASSWORD '%s';\n" "$pg_api_pass"
|
||||
printf "ALTER ROLE messenger_worker WITH LOGIN PASSWORD '%s';\n" "$pg_worker_pass"
|
||||
} | "${COMPOSE[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -v ON_ERROR_STOP=1 >/dev/null
|
||||
echo "converged PostgreSQL roles (messenger_migrator, messenger_api, messenger_worker)"
|
||||
|
||||
# 4b. Redis mTLS ACL user (messenger_api ONLY; zero worker Redis access)
|
||||
redis_api_pass="$(printf '%s' "$api_kv" | jq -r '.redis_password')"
|
||||
printf 'ACL SETUSER messenger_api reset on >%s ~session:sha256:* ~messages:* ~lock:messages:* ~rl:* ~fault:* -@all +ping +hello +client|setinfo +quit +get +set +del +incr +expire +pexpire +ttl +pttl +@scripting +multi +exec +discard\nACL SAVE\n' \
|
||||
"$redis_api_pass" \
|
||||
| "${COMPOSE[@]}" exec -T redis sh -c \
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/redis_admin_password)" redis-cli --tls --cacert /run/certs/ca.crt --cert /run/certs/health.crt --key /run/certs/health.key --user redis_admin -h localhost -p 6379 >/dev/null'
|
||||
echo "converged Redis ACL (messenger_api saved to /data/users.acl)"
|
||||
|
||||
# 4c. MinIO bucket, tightened policies & scoped IAM users over HTTPS + CA
|
||||
s3_api_key="$(printf '%s' "$api_kv" | jq -r '.s3_access_key_id')"
|
||||
s3_api_sec="$(printf '%s' "$api_kv" | jq -r '.s3_secret_access_key')"
|
||||
s3_worker_key="$(printf '%s' "$worker_kv" | jq -r '.s3_access_key_id')"
|
||||
s3_worker_sec="$(printf '%s' "$worker_kv" | jq -r '.s3_secret_access_key')"
|
||||
|
||||
s3_cid="$("${COMPOSE[@]}" ps -q s3 | head -n 1)"
|
||||
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
|
||||
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
|
||||
if [ -z "$app_data_net" ]; then
|
||||
echo "error: could not detect app_data network for s3 container" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '%s\n%s\n%s\n%s\n' "$s3_api_key" "$s3_api_sec" "$s3_worker_key" "$s3_worker_sec" \
|
||||
| docker run --rm -i \
|
||||
--network "$app_data_net" \
|
||||
--user 1000:1000 \
|
||||
--read-only \
|
||||
--cap-drop ALL \
|
||||
--security-opt no-new-privileges:true \
|
||||
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
|
||||
-e "S3_BUCKET=${S3_BUCKET:-messenger-attachments}" \
|
||||
-v "$(pwd)/infra/minio:/bootstrap:ro" \
|
||||
-v "$(pwd)/secrets/pki/ca.crt:/run/certs/ca.crt:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_user:/run/secrets/minio_root_user:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_password:/run/secrets/minio_root_password:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
"$MC_IMAGE" /bootstrap/bootstrap.sh
|
||||
|
||||
# 4d. RabbitMQ EXTERNAL passwordless CN users & strict producer/consumer ACLs
|
||||
"${COMPOSE[@]}" exec -T broker /bin/sh /etc/rabbitmq/init-worker.sh "$api_cn" "$worker_cn"
|
||||
|
||||
echo "openbao-bootstrap complete (root token revoked, zero secrets printed)"
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env bash
|
||||
# Operator-only OpenBao unseal command.
|
||||
# Reads 3 Shamir shares from $LAB7_OPERATOR_DIR/openbao/ (outside Git, never
|
||||
# mounted into containers) and unseals OpenBao over HTTPS with CA verification.
|
||||
# Never prints unseal keys. Idempotent if OpenBao is already unsealed.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
SHARES_DIR=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--from-operator-dir)
|
||||
shift
|
||||
SHARES_DIR="${1:?missing path for --from-operator-dir}"
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [--from-operator-dir <dir>]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if [ -z "$SHARES_DIR" ]; then
|
||||
SHARES_DIR="${OPERATOR_DIR}/openbao"
|
||||
fi
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
CA_CERT="${CA_FILE:-$(pwd)/secrets/pki/ca.crt}"
|
||||
|
||||
if [ ! -s "$CA_CERT" ]; then
|
||||
echo "error: CA certificate not found at ${CA_CERT}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Wait briefly for listener readiness after container restart
|
||||
seal_json=""
|
||||
for _ in $(seq 1 30); do
|
||||
if seal_json="$(curl -fsS --cacert "$CA_CERT" "${BAO_ADDR}/v1/sys/seal-status" 2>/dev/null)"; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
if [ -z "$seal_json" ]; then
|
||||
echo "error: OpenBao not reachable at ${BAO_ADDR}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
initialized="$(printf '%s' "$seal_json" | jq -r '.initialized')"
|
||||
sealed="$(printf '%s' "$seal_json" | jq -r '.sealed')"
|
||||
|
||||
if [ "$initialized" != "true" ]; then
|
||||
echo "error: OpenBao is not initialized yet; run scripts/openbao-bootstrap.sh first" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$sealed" = "false" ]; then
|
||||
echo "openbao already unsealed (${BAO_ADDR})"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
for idx in 1 2 3; do
|
||||
share_file="${SHARES_DIR}/unseal-share-${idx}"
|
||||
if [ ! -s "$share_file" ]; then
|
||||
echo "error: missing unseal share file ${share_file}" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Pipe share strictly via stdin so key material never appears in process argv.
|
||||
resp="$(jq -Rs '{key: (gsub("\r|\n"; ""))}' < "$share_file" \
|
||||
| curl -fsS --cacert "$CA_CERT" -X PUT \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data-binary @- \
|
||||
"${BAO_ADDR}/v1/sys/unseal")"
|
||||
sealed="$(printf '%s' "$resp" | jq -r '.sealed')"
|
||||
if [ "$sealed" = "false" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$sealed" != "false" ]; then
|
||||
echo "error: OpenBao remained sealed after submitting 3 shares" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "openbao unsealed ok (${BAO_ADDR})"
|
||||
Executable
+373
@@ -0,0 +1,373 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Idempotent Local PKI Bootstrap.
|
||||
# - Operator CA private key, OpenSSL CA DB, foreign-ca, rogue-client, and
|
||||
# messenger-operator-g1 live strictly outside Git in $LAB7_OPERATOR_DIR (0700)
|
||||
# and are NEVER mounted into any container.
|
||||
# - Runtime per-service leaf certs, ca.crt, and ca.crl are installed atomically
|
||||
# into gitignored ./secrets/pki/<service>/ with strict EKU separation
|
||||
# (serverAuth ONLY vs clientAuth ONLY) and single-DNS-SAN client identities.
|
||||
# - Never prints private keys. Re-running is idempotent unless --force is set.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
FORCE=0
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--force) FORCE=1 ;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [--force]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
PKI_OP_DIR="${OPERATOR_DIR}/pki"
|
||||
BAO_OP_DIR="${OPERATOR_DIR}/openbao"
|
||||
OP_CERT_DIR="${OPERATOR_DIR}/operator"
|
||||
RUNTIME_PKI_DIR="$(pwd)/secrets/pki"
|
||||
|
||||
umask 077
|
||||
mkdir -p "$OPERATOR_DIR" "$PKI_OP_DIR/newcerts" "$PKI_OP_DIR/issued" "$BAO_OP_DIR" "$OP_CERT_DIR"
|
||||
chmod 0700 "$OPERATOR_DIR" "$PKI_OP_DIR" "$PKI_OP_DIR/newcerts" "$PKI_OP_DIR/issued" "$BAO_OP_DIR" "$OP_CERT_DIR"
|
||||
|
||||
mkdir -p secrets "$RUNTIME_PKI_DIR"
|
||||
chmod 0700 secrets "$RUNTIME_PKI_DIR"
|
||||
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-pki.XXXXXX")"
|
||||
trap 'rm -rf "$TMP_DIR"' EXIT
|
||||
|
||||
CA_CNF="${PKI_OP_DIR}/ca.cnf"
|
||||
write_ca_cnf() {
|
||||
cat > "${CA_CNF}" <<EOF
|
||||
[ ca ]
|
||||
default_ca = CA_default
|
||||
|
||||
[ CA_default ]
|
||||
dir = ${PKI_OP_DIR}
|
||||
certs = \$dir
|
||||
crl_dir = \$dir
|
||||
new_certs_dir = \$dir/newcerts
|
||||
database = \$dir/index.txt
|
||||
serial = \$dir/serial
|
||||
crlnumber = \$dir/crlnumber
|
||||
certificate = \$dir/ca.crt
|
||||
private_key = \$dir/ca.key
|
||||
default_md = sha256
|
||||
default_days = 30
|
||||
default_crl_days = 30
|
||||
preserve = no
|
||||
unique_subject = no
|
||||
policy = policy_loose
|
||||
copy_extensions = copy
|
||||
crl_extensions = crl_ext
|
||||
|
||||
[ policy_loose ]
|
||||
organizationName = optional
|
||||
commonName = supplied
|
||||
|
||||
[ req ]
|
||||
default_md = sha256
|
||||
distinguished_name = req_dn
|
||||
prompt = no
|
||||
|
||||
[ req_dn ]
|
||||
O = mtusi-lab7
|
||||
CN = mtusi-lab7-local-ca
|
||||
|
||||
[ v3_ca ]
|
||||
subjectKeyIdentifier = hash
|
||||
authorityKeyIdentifier = keyid:always,issuer
|
||||
basicConstraints = critical, CA:true, pathlen:0
|
||||
keyUsage = critical, keyCertSign, cRLSign
|
||||
|
||||
[ v3_server ]
|
||||
basicConstraints = critical, CA:false
|
||||
subjectKeyIdentifier = hash
|
||||
authorityKeyIdentifier = keyid:always,issuer
|
||||
keyUsage = critical, digitalSignature
|
||||
extendedKeyUsage = serverAuth
|
||||
|
||||
[ v3_client ]
|
||||
basicConstraints = critical, CA:false
|
||||
subjectKeyIdentifier = hash
|
||||
authorityKeyIdentifier = keyid:always,issuer
|
||||
keyUsage = critical, digitalSignature
|
||||
extendedKeyUsage = clientAuth
|
||||
|
||||
[ crl_ext ]
|
||||
authorityKeyIdentifier = keyid:always
|
||||
EOF
|
||||
chmod 0600 "${CA_CNF}"
|
||||
}
|
||||
|
||||
atomic_install() {
|
||||
local src="$1"
|
||||
local dst="$2"
|
||||
local mode="$3"
|
||||
local dir
|
||||
dir="$(dirname "$dst")"
|
||||
mkdir -p "$dir"
|
||||
local tmp="${dst}.tmp.$$"
|
||||
cp "$src" "$tmp"
|
||||
chmod "$mode" "$tmp"
|
||||
mv -f "$tmp" "$dst"
|
||||
}
|
||||
|
||||
if [ "$FORCE" -eq 1 ]; then
|
||||
rm -f "${PKI_OP_DIR}/ca.key" "${PKI_OP_DIR}/ca.crt" "${PKI_OP_DIR}/ca.crl" \
|
||||
"${PKI_OP_DIR}/index.txt" "${PKI_OP_DIR}/index.txt.old" "${PKI_OP_DIR}/index.txt.attr" "${PKI_OP_DIR}/index.txt.attr.old" \
|
||||
"${PKI_OP_DIR}/serial" "${PKI_OP_DIR}/serial.old" "${PKI_OP_DIR}/crlnumber" "${PKI_OP_DIR}/crlnumber.old" \
|
||||
"${PKI_OP_DIR}/foreign-ca.key" "${PKI_OP_DIR}/foreign-ca.crt" \
|
||||
"${PKI_OP_DIR}/foreign-client.key" "${PKI_OP_DIR}/foreign-client.crt" \
|
||||
"${PKI_OP_DIR}/rogue-client.key" "${PKI_OP_DIR}/rogue-client.crt" \
|
||||
"${OP_CERT_DIR}/operator.key" "${OP_CERT_DIR}/operator.crt"
|
||||
rm -rf "${PKI_OP_DIR}/newcerts" "${PKI_OP_DIR}/issued"
|
||||
mkdir -p "${PKI_OP_DIR}/newcerts" "${PKI_OP_DIR}/issued"
|
||||
chmod 0700 "${PKI_OP_DIR}/newcerts" "${PKI_OP_DIR}/issued"
|
||||
fi
|
||||
|
||||
write_ca_cnf
|
||||
|
||||
# 1. Local Root CA (ECDSA P-256, pathlen:0, 365d)
|
||||
if [ ! -s "${PKI_OP_DIR}/ca.key" ] || [ ! -s "${PKI_OP_DIR}/ca.crt" ]; then
|
||||
: > "${PKI_OP_DIR}/index.txt"
|
||||
printf 'unique_subject = no\n' > "${PKI_OP_DIR}/index.txt.attr"
|
||||
printf '1000\n' > "${PKI_OP_DIR}/serial"
|
||||
printf '1000\n' > "${PKI_OP_DIR}/crlnumber"
|
||||
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "${PKI_OP_DIR}/ca.key"
|
||||
chmod 0600 "${PKI_OP_DIR}/ca.key"
|
||||
openssl req -new -x509 -sha256 -days 365 \
|
||||
-key "${PKI_OP_DIR}/ca.key" \
|
||||
-config "${CA_CNF}" -extensions v3_ca \
|
||||
-subj "/O=mtusi-lab7/CN=mtusi-lab7-local-ca" \
|
||||
-out "${PKI_OP_DIR}/ca.crt"
|
||||
chmod 0644 "${PKI_OP_DIR}/ca.crt"
|
||||
echo "created Root CA in ${PKI_OP_DIR}"
|
||||
else
|
||||
[ -f "${PKI_OP_DIR}/index.txt" ] || : > "${PKI_OP_DIR}/index.txt"
|
||||
[ -f "${PKI_OP_DIR}/index.txt.attr" ] || printf 'unique_subject = no\n' > "${PKI_OP_DIR}/index.txt.attr"
|
||||
[ -f "${PKI_OP_DIR}/serial" ] || printf '1000\n' > "${PKI_OP_DIR}/serial"
|
||||
[ -f "${PKI_OP_DIR}/crlnumber" ] || printf '1000\n' > "${PKI_OP_DIR}/crlnumber"
|
||||
echo "kept Root CA in ${PKI_OP_DIR}"
|
||||
fi
|
||||
|
||||
# Generate or refresh CRL v2
|
||||
if [ ! -s "${PKI_OP_DIR}/ca.crl" ] || [ "$FORCE" -eq 1 ]; then
|
||||
openssl ca -batch -config "${CA_CNF}" -gencrl -out "${PKI_OP_DIR}/ca.crl" >/dev/null 2>&1
|
||||
chmod 0644 "${PKI_OP_DIR}/ca.crl"
|
||||
fi
|
||||
|
||||
# 2. Foreign CA + Foreign Client (strictly in operator dir for negative tests)
|
||||
if [ ! -s "${PKI_OP_DIR}/foreign-ca.key" ] || [ ! -s "${PKI_OP_DIR}/foreign-ca.crt" ]; then
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "${PKI_OP_DIR}/foreign-ca.key"
|
||||
chmod 0600 "${PKI_OP_DIR}/foreign-ca.key"
|
||||
openssl req -new -x509 -sha256 -days 365 \
|
||||
-key "${PKI_OP_DIR}/foreign-ca.key" \
|
||||
-subj "/O=mtusi-lab7-foreign/CN=mtusi-lab7-foreign-ca" \
|
||||
-addext "basicConstraints=critical,CA:true,pathlen:0" \
|
||||
-addext "keyUsage=critical,keyCertSign,cRLSign" \
|
||||
-out "${PKI_OP_DIR}/foreign-ca.crt"
|
||||
chmod 0644 "${PKI_OP_DIR}/foreign-ca.crt"
|
||||
fi
|
||||
|
||||
if [ ! -s "${PKI_OP_DIR}/foreign-client.key" ] || [ ! -s "${PKI_OP_DIR}/foreign-client.crt" ]; then
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "${PKI_OP_DIR}/foreign-client.key"
|
||||
chmod 0600 "${PKI_OP_DIR}/foreign-client.key"
|
||||
openssl req -new -sha256 \
|
||||
-key "${PKI_OP_DIR}/foreign-client.key" \
|
||||
-subj "/O=mtusi-lab7-foreign/CN=foreign-client" \
|
||||
-out "${TMP_DIR}/foreign-client.csr"
|
||||
cat > "${TMP_DIR}/foreign-client.ext" <<EOF
|
||||
basicConstraints = critical, CA:false
|
||||
keyUsage = critical, digitalSignature
|
||||
extendedKeyUsage = clientAuth
|
||||
subjectAltName = DNS:foreign-client
|
||||
EOF
|
||||
openssl x509 -req -sha256 -days 30 \
|
||||
-in "${TMP_DIR}/foreign-client.csr" \
|
||||
-CA "${PKI_OP_DIR}/foreign-ca.crt" -CAkey "${PKI_OP_DIR}/foreign-ca.key" -CAcreateserial \
|
||||
-extfile "${TMP_DIR}/foreign-client.ext" \
|
||||
-out "${PKI_OP_DIR}/foreign-client.crt" >/dev/null 2>&1
|
||||
chmod 0644 "${PKI_OP_DIR}/foreign-client.crt"
|
||||
rm -f "${PKI_OP_DIR}/foreign-ca.srl"
|
||||
fi
|
||||
|
||||
# Helper: issue leaf cert signed by our Local Root CA via `openssl ca` (tracks serial in index.txt)
|
||||
issue_leaf() {
|
||||
local cert_id="$1"
|
||||
local kind="$2" # server | client
|
||||
local cn="$3"
|
||||
local san="$4"
|
||||
local out_crt="$5"
|
||||
local out_key="$6"
|
||||
local key_mode="${7:-0644}"
|
||||
|
||||
if [ "$FORCE" -eq 0 ] && [ -s "$out_crt" ] && [ -s "$out_key" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local ext_section="v3_server"
|
||||
[ "$kind" = "client" ] && ext_section="v3_client"
|
||||
|
||||
local req_cnf="${TMP_DIR}/${cert_id}.req.cnf"
|
||||
local key_tmp="${TMP_DIR}/${cert_id}.key"
|
||||
local csr_tmp="${TMP_DIR}/${cert_id}.csr"
|
||||
local crt_tmp="${TMP_DIR}/${cert_id}.crt"
|
||||
|
||||
cat > "$req_cnf" <<EOF
|
||||
[ req ]
|
||||
default_md = sha256
|
||||
distinguished_name = dn
|
||||
req_extensions = req_ext
|
||||
prompt = no
|
||||
|
||||
[ dn ]
|
||||
O = mtusi-lab7
|
||||
CN = ${cn}
|
||||
|
||||
[ req_ext ]
|
||||
subjectAltName = ${san}
|
||||
EOF
|
||||
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "$key_tmp"
|
||||
openssl req -new -sha256 -key "$key_tmp" -config "$req_cnf" -out "$csr_tmp"
|
||||
openssl ca -batch -notext -config "${CA_CNF}" -extensions "$ext_section" \
|
||||
-in "$csr_tmp" -out "$crt_tmp" >/dev/null 2>&1
|
||||
|
||||
atomic_install "$crt_tmp" "$out_crt" 0644
|
||||
atomic_install "$key_tmp" "$out_key" "$key_mode"
|
||||
# Keep public cert reference in operator DB for deterministic revocation later.
|
||||
atomic_install "$crt_tmp" "${PKI_OP_DIR}/issued/${cert_id}.crt" 0644
|
||||
echo "issued ${cert_id} (kind=${kind} cn=${cn})"
|
||||
}
|
||||
|
||||
make_bundle() {
|
||||
local crt="$1"
|
||||
local key="$2"
|
||||
local bundle="$3"
|
||||
local tmp="${TMP_DIR}/bundle.pem"
|
||||
cat "$crt" "$key" > "$tmp"
|
||||
atomic_install "$tmp" "$bundle" 0644
|
||||
}
|
||||
|
||||
# 3. Operator-only certs signed by our Root CA (NEVER mounted into containers)
|
||||
issue_leaf rogue-client client rogue-client "DNS:rogue-client" \
|
||||
"${PKI_OP_DIR}/rogue-client.crt" "${PKI_OP_DIR}/rogue-client.key" 0600
|
||||
|
||||
issue_leaf messenger-operator client messenger-operator-g1 "DNS:messenger-operator" \
|
||||
"${OP_CERT_DIR}/operator.crt" "${OP_CERT_DIR}/operator.key" 0600
|
||||
|
||||
# 4. Prepare isolated per-service runtime cert dirs (0755 inside 0700 host parent)
|
||||
SERVICES=(
|
||||
haproxy api worker migrate postgres redis s3 broker
|
||||
otel-gateway otel-collector prometheus loki tempo grafana openbao
|
||||
)
|
||||
for svc in "${SERVICES[@]}"; do
|
||||
mkdir -p "${RUNTIME_PKI_DIR}/${svc}"
|
||||
chmod 0755 "${RUNTIME_PKI_DIR}/${svc}"
|
||||
done
|
||||
mkdir -p "${RUNTIME_PKI_DIR}/s3/CAs"
|
||||
chmod 0755 "${RUNTIME_PKI_DIR}/s3/CAs"
|
||||
|
||||
# 5. Server certificates (EKU=serverAuth ONLY, per unified-contract.md §1.2)
|
||||
issue_leaf haproxy-ingress server localhost "DNS:localhost,DNS:haproxy" \
|
||||
"${RUNTIME_PKI_DIR}/haproxy/server.crt" "${RUNTIME_PKI_DIR}/haproxy/server.key" 0644
|
||||
make_bundle "${RUNTIME_PKI_DIR}/haproxy/server.crt" "${RUNTIME_PKI_DIR}/haproxy/server.key" \
|
||||
"${RUNTIME_PKI_DIR}/haproxy/server.pem"
|
||||
|
||||
issue_leaf api-server server api "DNS:api" \
|
||||
"${RUNTIME_PKI_DIR}/api/server.crt" "${RUNTIME_PKI_DIR}/api/server.key" 0644
|
||||
|
||||
issue_leaf postgres-server server postgres "DNS:postgres,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/postgres/server.crt" "${RUNTIME_PKI_DIR}/postgres/server.key" 0644
|
||||
|
||||
issue_leaf redis-server server redis "DNS:redis,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/redis/server.crt" "${RUNTIME_PKI_DIR}/redis/server.key" 0644
|
||||
|
||||
issue_leaf s3-server server s3 "DNS:s3,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/s3/public.crt" "${RUNTIME_PKI_DIR}/s3/private.key" 0644
|
||||
|
||||
issue_leaf broker-server server broker "DNS:broker" \
|
||||
"${RUNTIME_PKI_DIR}/broker/server.crt" "${RUNTIME_PKI_DIR}/broker/server.key" 0644
|
||||
|
||||
issue_leaf otel-server server otel-collector "DNS:otel-collector,DNS:otel-gateway" \
|
||||
"${RUNTIME_PKI_DIR}/otel-gateway/server.crt" "${RUNTIME_PKI_DIR}/otel-gateway/server.key" 0644
|
||||
make_bundle "${RUNTIME_PKI_DIR}/otel-gateway/server.crt" "${RUNTIME_PKI_DIR}/otel-gateway/server.key" \
|
||||
"${RUNTIME_PKI_DIR}/otel-gateway/server.pem"
|
||||
|
||||
issue_leaf prometheus-server server prometheus "DNS:prometheus,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/prometheus/server.crt" "${RUNTIME_PKI_DIR}/prometheus/server.key" 0644
|
||||
|
||||
issue_leaf loki-server server loki "DNS:loki" \
|
||||
"${RUNTIME_PKI_DIR}/loki/server.crt" "${RUNTIME_PKI_DIR}/loki/server.key" 0644
|
||||
|
||||
issue_leaf tempo-server server tempo "DNS:tempo" \
|
||||
"${RUNTIME_PKI_DIR}/tempo/server.crt" "${RUNTIME_PKI_DIR}/tempo/server.key" 0644
|
||||
|
||||
issue_leaf grafana-server server grafana "DNS:grafana,DNS:localhost" \
|
||||
"${RUNTIME_PKI_DIR}/grafana/server.crt" "${RUNTIME_PKI_DIR}/grafana/server.key" 0644
|
||||
|
||||
issue_leaf openbao-server server openbao "DNS:openbao,DNS:localhost,IP:127.0.0.1" \
|
||||
"${RUNTIME_PKI_DIR}/openbao/server.crt" "${RUNTIME_PKI_DIR}/openbao/server.key" 0644
|
||||
|
||||
# 6. Client identity certificates (EKU=clientAuth ONLY, single DNS SAN, per unified-contract.md §1.3)
|
||||
issue_leaf haproxy-client client haproxy-lb-g1 "DNS:haproxy-lb" \
|
||||
"${RUNTIME_PKI_DIR}/haproxy/client.crt" "${RUNTIME_PKI_DIR}/haproxy/client.key" 0644
|
||||
make_bundle "${RUNTIME_PKI_DIR}/haproxy/client.crt" "${RUNTIME_PKI_DIR}/haproxy/client.key" \
|
||||
"${RUNTIME_PKI_DIR}/haproxy/client.pem"
|
||||
|
||||
issue_leaf api-client client messenger-api-g1 "DNS:messenger-api" \
|
||||
"${RUNTIME_PKI_DIR}/api/client.crt" "${RUNTIME_PKI_DIR}/api/client.key" 0644
|
||||
|
||||
issue_leaf worker-client client messenger-worker-g1 "DNS:messenger-worker" \
|
||||
"${RUNTIME_PKI_DIR}/worker/client.crt" "${RUNTIME_PKI_DIR}/worker/client.key" 0644
|
||||
|
||||
issue_leaf migrator-client client messenger-migrator-g1 "DNS:messenger-migrator" \
|
||||
"${RUNTIME_PKI_DIR}/migrate/client.crt" "${RUNTIME_PKI_DIR}/migrate/client.key" 0644
|
||||
|
||||
issue_leaf otel-collector-client client otel-collector "DNS:otel-collector" \
|
||||
"${RUNTIME_PKI_DIR}/otel-collector/client.crt" "${RUNTIME_PKI_DIR}/otel-collector/client.key" 0644
|
||||
|
||||
issue_leaf grafana-client client grafana "DNS:grafana" \
|
||||
"${RUNTIME_PKI_DIR}/grafana/client.crt" "${RUNTIME_PKI_DIR}/grafana/client.key" 0644
|
||||
|
||||
issue_leaf prometheus-client client prometheus "DNS:prometheus" \
|
||||
"${RUNTIME_PKI_DIR}/prometheus/client.crt" "${RUNTIME_PKI_DIR}/prometheus/client.key" 0644
|
||||
|
||||
issue_leaf redis-health client redis-health "DNS:redis-health" \
|
||||
"${RUNTIME_PKI_DIR}/redis/health.crt" "${RUNTIME_PKI_DIR}/redis/health.key" 0644
|
||||
|
||||
# 7. Distribute public CA cert and CRL atomically into runtime PKI dirs
|
||||
atomic_install "${PKI_OP_DIR}/ca.crt" "${RUNTIME_PKI_DIR}/ca.crt" 0644
|
||||
atomic_install "${PKI_OP_DIR}/ca.crl" "${RUNTIME_PKI_DIR}/ca.crl" 0644
|
||||
atomic_install "${PKI_OP_DIR}/ca.crt" "${RUNTIME_PKI_DIR}/s3/CAs/ca.crt" 0644
|
||||
|
||||
for svc in haproxy api worker migrate postgres redis broker otel-gateway otel-collector prometheus loki tempo grafana openbao; do
|
||||
atomic_install "${PKI_OP_DIR}/ca.crt" "${RUNTIME_PKI_DIR}/${svc}/ca.crt" 0644
|
||||
done
|
||||
|
||||
for svc in haproxy api worker migrate postgres redis broker otel-gateway prometheus openbao; do
|
||||
atomic_install "${PKI_OP_DIR}/ca.crl" "${RUNTIME_PKI_DIR}/${svc}/ca.crl" 0644
|
||||
done
|
||||
|
||||
# 8. OTel Gateway mTLS CN & SAN allowlists (mounted via /run/certs:ro; never dirty Git)
|
||||
if [ "$FORCE" -eq 1 ] || [ ! -s "${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-cn.lst" ]; then
|
||||
api_cn="$(openssl x509 -in "${RUNTIME_PKI_DIR}/api/client.crt" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
worker_cn="$(openssl x509 -in "${RUNTIME_PKI_DIR}/worker/client.crt" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
printf '%s\n%s\n' "${api_cn:-messenger-api-g1}" "${worker_cn:-messenger-worker-g1}" > "${TMP_DIR}/allowed-otlp-cn.lst"
|
||||
atomic_install "${TMP_DIR}/allowed-otlp-cn.lst" "${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-cn.lst" 0644
|
||||
fi
|
||||
|
||||
if [ "$FORCE" -eq 1 ] || [ ! -s "${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-san.lst" ]; then
|
||||
printf 'DNS:messenger-api\nDNS:messenger-worker\n' > "${TMP_DIR}/allowed-otlp-san.lst"
|
||||
atomic_install "${TMP_DIR}/allowed-otlp-san.lst" "${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-san.lst" 0644
|
||||
fi
|
||||
|
||||
echo "pki-bootstrap ok: operator_dir=${OPERATOR_DIR} runtime_dir=${RUNTIME_PKI_DIR}"
|
||||
+11
-4
@@ -1,8 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
|
||||
# Semantic and evidence notes: tests/README.md ("Проверка сохранности") and REPORT.md.
|
||||
# Restarts all application, stateful data, and telemetry containers with volumes
|
||||
# preserved. OpenBao remains unsealed across ordinary stand restarts (per
|
||||
# contracts/trust-matrix.md); OpenBao restart + manual operator unseal is tested
|
||||
# explicitly in scripts/lab7/openbao_lifecycle.py.
|
||||
set -euo pipefail
|
||||
|
||||
compose=(docker compose --env-file .env)
|
||||
"${compose[@]}" restart postgres redis s3 broker api worker haproxy otel-collector prometheus loki tempo grafana
|
||||
"${compose[@]}" up -d --no-recreate --no-deps --wait postgres redis s3 broker api worker haproxy otel-collector prometheus loki tempo grafana
|
||||
compose=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
|
||||
# Stop otel-collector before restarting otel-gateway (shared netns owner) so
|
||||
# otel-collector cleanly re-attaches to the fresh otel-gateway network namespace.
|
||||
"${compose[@]}" stop otel-collector
|
||||
"${compose[@]}" restart postgres redis s3 broker api worker haproxy otel-gateway prometheus loki tempo grafana
|
||||
"${compose[@]}" up -d --no-build --no-recreate --no-deps --wait postgres redis s3 broker api worker haproxy otel-gateway prometheus loki tempo grafana
|
||||
"${compose[@]}" up -d --no-build --no-deps otel-collector
|
||||
|
||||
Executable
+232
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Grade 5 Track 1 («Компрометация worker»): Full Containment & Recovery.
|
||||
# Zero image rebuild, zero root token (uses operator mTLS cert).
|
||||
# Usage: scripts/revoke-worker.sh [--no-start] [--old-cn <cn>] [--new-cn <cn>]
|
||||
#
|
||||
# Containment actions across ALL control planes:
|
||||
# 1. OpenSSL CA revoke old worker cert -> regenerate & distribute ca.crl ->
|
||||
# upload CRL to OpenBao auth/cert/crls/lab7-ca -> reload api/haproxy/postgres.
|
||||
# 2. Selectively revoke active OpenBao token accessors for messenger-worker
|
||||
# (leaves messenger-api and messenger-operator tokens completely intact).
|
||||
# 3. OTel Gateway: remove old CN from allowed-otlp-cn.lst, add new CN, SIGUSR2.
|
||||
# 4. RabbitMQ: delete_user <old_cn> (kills active AMQPS connections immediately)
|
||||
# and create passwordless EXTERNAL user <new_cn> with consumer-only ACL.
|
||||
# 5. PostgreSQL: rotate messenger_worker password + pg_terminate_backend on
|
||||
# active messenger_worker sessions.
|
||||
# 6. MinIO: create new worker-<hex> IAM user with messenger-worker policy and
|
||||
# delete old worker IAM user over HTTPS + CA.
|
||||
# 7. PKI: issue new worker leaf cert (<new_cn>, SAN=DNS:messenger-worker).
|
||||
# 8. OpenBao KV v2: write version N+1 to secret/messenger/worker.
|
||||
# 9. Unless --no-start is set, start/restart worker with --no-build --wait.
|
||||
# Never prints secrets, passwords, keys, or tokens.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
NO_START=0
|
||||
OLD_CN=""
|
||||
NEW_CN=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--no-start) NO_START=1 ;;
|
||||
--old-cn)
|
||||
shift
|
||||
OLD_CN="${1:?missing value for --old-cn}"
|
||||
;;
|
||||
--new-cn)
|
||||
shift
|
||||
NEW_CN="${1:?missing value for --new-cn}"
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [--no-start] [--old-cn <cn>] [--new-cn <cn>]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
|
||||
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
|
||||
RUNTIME_PKI_DIR="$(pwd)/secrets/pki"
|
||||
CA_CERT="${CA_FILE:-${RUNTIME_PKI_DIR}/ca.crt}"
|
||||
WORKER_CRT="${RUNTIME_PKI_DIR}/worker/client.crt"
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
COMPOSE=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
|
||||
MC_IMAGE="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
|
||||
|
||||
if [ ! -s "$WORKER_CRT" ]; then
|
||||
echo "error: current worker certificate not found at ${WORKER_CRT}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$OLD_CN" ]; then
|
||||
OLD_CN="$(openssl x509 -in "$WORKER_CRT" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p')"
|
||||
fi
|
||||
OLD_CN="${OLD_CN:-messenger-worker-g1}"
|
||||
|
||||
if [ -z "$NEW_CN" ]; then
|
||||
if [[ "$OLD_CN" =~ ^(.*-g)([0-9]+)$ ]]; then
|
||||
NEW_CN="${BASH_REMATCH[1]}$((BASH_REMATCH[2] + 1))"
|
||||
else
|
||||
NEW_CN="messenger-worker-g2"
|
||||
fi
|
||||
fi
|
||||
|
||||
OLD_SERIAL="$(openssl x509 -in "$WORKER_CRT" -noout -serial | cut -d= -f2)"
|
||||
|
||||
umask 077
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-revoke-wrk.XXXXXX")"
|
||||
OP_CFG="${TMP_DIR}/op-auth.cfg"
|
||||
cleanup() {
|
||||
if [ -s "$OP_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$TMP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# Authenticate as operator via mTLS cert (zero root token)
|
||||
login_json="$(curl -fsS --cacert "$CA_CERT" --cert "$OP_CERT" --key "$OP_KEY" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${BAO_ADDR}/v1/auth/cert/login")"
|
||||
op_token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty')"
|
||||
if [ -z "$op_token" ]; then
|
||||
echo "error: operator mTLS login to OpenBao failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "$OP_CFG"
|
||||
chmod 0600 "$OP_CFG"
|
||||
unset login_json op_token
|
||||
|
||||
# 1. Read existing worker KV secret (to identify old MinIO IAM user)
|
||||
cur_worker_kv="$(curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" \
|
||||
"${BAO_ADDR}/v1/secret/data/messenger/worker" | jq -c '.data.data')"
|
||||
old_s3_key="$(printf '%s' "$cur_worker_kv" | jq -r '.s3_access_key_id // empty')"
|
||||
|
||||
# 2. Rotate worker leaf cert WITH CRL revocation & OTel Gateway allowlist update
|
||||
# (handles OpenSSL ca -revoke, ca.crl distribution, OpenBao CRL upload,
|
||||
# OTel allowed-otlp-cn.lst replacement + SIGUSR2, api SIGHUP, haproxy SIGUSR2, postgres reload)
|
||||
rot_out="$(./scripts/rotate-cert.sh worker --revoke --cn "$NEW_CN")"
|
||||
NEW_SERIAL="$(printf '%s' "$rot_out" | sed -n 's/.*new_serial=\([^ ]*\).*/\1/p')"
|
||||
|
||||
# 3. Selectively revoke active OpenBao token accessors for messenger-worker ONLY
|
||||
revoked_accessors=0
|
||||
accessors_json="$(curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X LIST \
|
||||
"${BAO_ADDR}/v1/auth/token/accessors" 2>/dev/null || echo '{"data":{"keys":[]}}')"
|
||||
for acc in $(printf '%s' "$accessors_json" | jq -r '.data.keys[]? // empty'); do
|
||||
lookup="$(jq -n --arg a "$acc" '{accessor: $a}' \
|
||||
| curl -sS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/auth/token/lookup-accessor" 2>/dev/null || true)"
|
||||
cert_name="$(printf '%s' "$lookup" | jq -r '.data.meta.cert_name // empty' 2>/dev/null || true)"
|
||||
common_name="$(printf '%s' "$lookup" | jq -r '.data.meta.common_name // empty' 2>/dev/null || true)"
|
||||
if [ "$cert_name" = "messenger-worker" ] || [ "$common_name" = "$OLD_CN" ]; then
|
||||
jq -n --arg a "$acc" '{accessor: $a}' \
|
||||
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-accessor" >/dev/null 2>&1 || true
|
||||
revoked_accessors=$((revoked_accessors + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
# 4. RabbitMQ: delete compromised EXTERNAL user (closes active connections) & create new generation user
|
||||
"${COMPOSE[@]}" exec -T broker sh -eu -c '
|
||||
old_cn=$1
|
||||
new_cn=$2
|
||||
if rabbitmqctl -q list_users | awk "{print \$1}" | grep -Fxq "$old_cn"; then
|
||||
rabbitmqctl -q delete_user "$old_cn"
|
||||
fi
|
||||
if ! rabbitmqctl -q list_users | awk "{print \$1}" | grep -Fxq "$new_cn"; then
|
||||
rabbitmqctl -q add_user "$new_cn" "tmp-$(head -c 16 /dev/urandom | od -An -tx1 | tr -d " \n")"
|
||||
fi
|
||||
rabbitmqctl -q clear_password "$new_cn"
|
||||
rabbitmqctl -q set_user_tags "$new_cn"
|
||||
rabbitmqctl -q set_permissions -p messenger "$new_cn" "^$" "^$" "^attachments\.process$"
|
||||
' _ "$OLD_CN" "$NEW_CN"
|
||||
|
||||
# 5. PostgreSQL: rotate messenger_worker password & terminate active worker sessions
|
||||
new_pg_pass="$(openssl rand -hex 24)"
|
||||
{
|
||||
printf "SET password_encryption = 'scram-sha-256';\n"
|
||||
printf "ALTER ROLE messenger_worker WITH LOGIN PASSWORD '%s';\n" "$new_pg_pass"
|
||||
printf "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'messenger_worker' AND pid <> pg_backend_pid();\n"
|
||||
} | "${COMPOSE[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -v ON_ERROR_STOP=1 >/dev/null
|
||||
|
||||
# 6. MinIO: add new scoped worker IAM user & immediately remove old compromised IAM user (HTTPS + CA)
|
||||
new_s3_key="worker-$(openssl rand -hex 8)"
|
||||
new_s3_sec="$(openssl rand -hex 24)"
|
||||
|
||||
s3_cid="$("${COMPOSE[@]}" ps -q s3 | head -n 1)"
|
||||
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
|
||||
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
|
||||
|
||||
printf '%s\n%s\n%s\n' "$new_s3_key" "$new_s3_sec" "$old_s3_key" \
|
||||
| docker run --rm -i \
|
||||
--network "$app_data_net" \
|
||||
--user 1000:1000 \
|
||||
--read-only \
|
||||
--cap-drop ALL \
|
||||
--security-opt no-new-privileges:true \
|
||||
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
|
||||
-v "$(pwd)/secrets/pki/ca.crt:/run/certs/ca.crt:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_user:/run/secrets/minio_root_user:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_password:/run/secrets/minio_root_password:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
"$MC_IMAGE" -c '
|
||||
set -eu
|
||||
IFS= read -r ru < /run/secrets/minio_root_user || [ -n "$ru" ]
|
||||
IFS= read -r rp < /run/secrets/minio_root_password || [ -n "$rp" ]
|
||||
IFS= read -r nk; IFS= read -r ns; IFS= read -r ok || true
|
||||
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
export MC_HOST_stand="https://${ru}:${rp}@s3:9000"
|
||||
mc admin user add stand "$nk" "$ns" >/dev/null
|
||||
mc admin policy attach stand messenger-worker --user "$nk" >/dev/null
|
||||
if [ -n "$ok" ] && [ "$ok" != "$nk" ]; then
|
||||
mc admin user remove stand "$ok" >/dev/null 2>&1 || true
|
||||
fi
|
||||
'
|
||||
|
||||
# 7. Write OpenBao KV v2 version N+1 for messenger/worker
|
||||
kv_ver="$(jq -n \
|
||||
--arg db_pass "$new_pg_pass" \
|
||||
--arg s3_key "$new_s3_key" \
|
||||
--arg s3_sec "$new_s3_sec" \
|
||||
--arg broker_user "$NEW_CN" \
|
||||
'{
|
||||
data: {
|
||||
db_user: "messenger_worker",
|
||||
db_password: $db_pass,
|
||||
s3_access_key_id: $s3_key,
|
||||
s3_secret_access_key: $s3_sec,
|
||||
broker_user: $broker_user
|
||||
}
|
||||
}' \
|
||||
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/secret/data/messenger/worker" \
|
||||
| jq -r '.data.version')"
|
||||
|
||||
# 8. Recover worker without image rebuild (unless --no-start was requested)
|
||||
worker_started="false"
|
||||
if [ "$NO_START" -eq 0 ]; then
|
||||
if [ -n "$("${COMPOSE[@]}" ps -q --status running worker 2>/dev/null || true)" ]; then
|
||||
"${COMPOSE[@]}" restart worker >/dev/null
|
||||
fi
|
||||
"${COMPOSE[@]}" up -d --no-build --no-deps --wait worker >/dev/null
|
||||
worker_started="true"
|
||||
fi
|
||||
|
||||
echo "revoke-worker ok: old_cn=${OLD_CN} new_cn=${NEW_CN} old_serial=${OLD_SERIAL} new_serial=${NEW_SERIAL} revoked_accessors=${revoked_accessors} kv_version=${kv_ver} worker_started=${worker_started}"
|
||||
Executable
+405
@@ -0,0 +1,405 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Zero-Rebuild Leaf Certificate Rotation & CRL Revocation.
|
||||
# Modes:
|
||||
# 1. scripts/rotate-cert.sh <target> [--revoke] [--cn <new-cn>]
|
||||
# Rotates leaf cert atomically into ./secrets/pki/<svc>/, optionally revokes
|
||||
# old serial into OpenSSL CRL + distributes ca.crl + uploads CRL to OpenBao,
|
||||
# and triggers live reload (SIGHUP / SIGUSR2 / pg_reload_conf) with ZERO
|
||||
# image rebuild.
|
||||
# 2. scripts/rotate-cert.sh --revoke-cert <pem-path>
|
||||
# Revokes the given certificate PEM in operator CA DB, regenerates and
|
||||
# distributes ca.crl everywhere, uploads CRL to OpenBao, and reloads
|
||||
# CRL-enforcing services (api, haproxy, otel-gateway, postgres).
|
||||
# 3. scripts/rotate-cert.sh --issue-test-client <name> <cn> <san> <out-dir>
|
||||
# Issues a temporary CA-signed EKU=clientAuth leaf cert into <out-dir> for
|
||||
# safe revocation testing without disturbing production service certs.
|
||||
# Never prints private keys or tokens.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
PKI_OP_DIR="${OPERATOR_DIR}/pki"
|
||||
CA_CNF="${PKI_OP_DIR}/ca.cnf"
|
||||
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
|
||||
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
|
||||
RUNTIME_PKI_DIR="$(pwd)/secrets/pki"
|
||||
CA_CERT="${RUNTIME_PKI_DIR}/ca.crt"
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
COMPOSE=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
|
||||
|
||||
umask 077
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-rot-cert.XXXXXX")"
|
||||
OP_CFG="${TMP_DIR}/op-auth.cfg"
|
||||
cleanup() {
|
||||
if [ -s "$OP_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$TMP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
atomic_install() {
|
||||
local src="$1"
|
||||
local dst="$2"
|
||||
local mode="$3"
|
||||
mkdir -p "$(dirname "$dst")"
|
||||
local tmp="${dst}.tmp.$$"
|
||||
cp "$src" "$tmp"
|
||||
chmod "$mode" "$tmp"
|
||||
mv -f "$tmp" "$dst"
|
||||
}
|
||||
|
||||
cert_serial() {
|
||||
openssl x509 -in "$1" -noout -serial | cut -d= -f2
|
||||
}
|
||||
|
||||
cert_fp256() {
|
||||
openssl x509 -in "$1" -noout -fingerprint -sha256 | cut -d= -f2
|
||||
}
|
||||
|
||||
cert_cn() {
|
||||
openssl x509 -in "$1" -noout -subject -nameopt RFC2253 | sed -n 's/.*CN=\([^,]*\).*/\1/p'
|
||||
}
|
||||
|
||||
is_running() {
|
||||
[ -n "$("${COMPOSE[@]}" ps -q --status running "$1" 2>/dev/null || true)" ]
|
||||
}
|
||||
|
||||
reload_service() {
|
||||
local svc="$1"
|
||||
local sig="$2"
|
||||
if is_running "$svc"; then
|
||||
"${COMPOSE[@]}" kill -s "$sig" "$svc" >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
refresh_postgres_tls() {
|
||||
if is_running postgres; then
|
||||
"${COMPOSE[@]}" exec -T postgres sh -c '
|
||||
set -eu
|
||||
d=/var/run/postgresql/certs
|
||||
mkdir -p "$d" && chmod 0700 "$d"
|
||||
for f in ca.crt ca.crl server.crt; do
|
||||
cp "/run/certs/$f" "$d/$f.tmp" && chmod 0644 "$d/$f.tmp" && mv -f "$d/$f.tmp" "$d/$f"
|
||||
done
|
||||
cp /run/certs/server.key "$d/server.key.tmp" && chmod 0600 "$d/server.key.tmp" && mv -f "$d/server.key.tmp" "$d/server.key"
|
||||
psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -c "SELECT pg_reload_conf();" >/dev/null
|
||||
' >/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
upload_crl_to_openbao() {
|
||||
[ -s "$CA_CERT" ] && [ -s "$OP_CERT" ] && [ -s "$OP_KEY" ] || return 0
|
||||
local seal_json sealed
|
||||
seal_json="$(curl -fsS --cacert "$CA_CERT" "${BAO_ADDR}/v1/sys/seal-status" 2>/dev/null || true)"
|
||||
sealed="$(printf '%s' "$seal_json" | jq -r '.sealed // "true"' 2>/dev/null || echo true)"
|
||||
if [ "$sealed" != "false" ]; then
|
||||
return 0
|
||||
fi
|
||||
local login_json op_token
|
||||
login_json="$(curl -fsS --cacert "$CA_CERT" --cert "$OP_CERT" --key "$OP_KEY" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${BAO_ADDR}/v1/auth/cert/login" 2>/dev/null || true)"
|
||||
op_token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty' 2>/dev/null || true)"
|
||||
[ -n "$op_token" ] || return 0
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "$OP_CFG"
|
||||
chmod 0600 "$OP_CFG"
|
||||
jq -Rs '{crl: .}' < "${PKI_OP_DIR}/ca.crl" \
|
||||
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/auth/cert/crls/lab7-ca" >/dev/null
|
||||
}
|
||||
|
||||
regenerate_and_distribute_crl() {
|
||||
openssl ca -batch -config "$CA_CNF" -gencrl -out "${TMP_DIR}/ca.crl" >/dev/null 2>&1
|
||||
atomic_install "${TMP_DIR}/ca.crl" "${PKI_OP_DIR}/ca.crl" 0644
|
||||
atomic_install "${TMP_DIR}/ca.crl" "${RUNTIME_PKI_DIR}/ca.crl" 0644
|
||||
for svc in haproxy api worker migrate postgres redis broker otel-gateway prometheus openbao; do
|
||||
if [ -d "${RUNTIME_PKI_DIR}/${svc}" ]; then
|
||||
atomic_install "${TMP_DIR}/ca.crl" "${RUNTIME_PKI_DIR}/${svc}/ca.crl" 0644
|
||||
fi
|
||||
done
|
||||
upload_crl_to_openbao
|
||||
refresh_postgres_tls
|
||||
reload_service api HUP
|
||||
reload_service haproxy USR2
|
||||
reload_service otel-gateway USR2
|
||||
}
|
||||
|
||||
revoke_pem() {
|
||||
local pem="$1"
|
||||
if [ ! -s "$pem" ]; then
|
||||
echo "error: certificate not found for revocation: ${pem}" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Revoke (ignore "Already revoked" error cleanly for idempotency)
|
||||
local err_file="${TMP_DIR}/revoke.err"
|
||||
if ! openssl ca -batch -config "$CA_CNF" -revoke "$pem" 2>"$err_file"; then
|
||||
if ! grep -qi "Already revoked" "$err_file"; then
|
||||
cat "$err_file" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
issue_new_leaf() {
|
||||
local kind="$1"
|
||||
local cn="$2"
|
||||
local san="$3"
|
||||
local out_crt="$4"
|
||||
local out_key="$5"
|
||||
local key_mode="$6"
|
||||
|
||||
local ext_section="v3_server"
|
||||
[ "$kind" = "client" ] && ext_section="v3_client"
|
||||
|
||||
local req_cnf="${TMP_DIR}/leaf.req.cnf"
|
||||
local key_tmp="${TMP_DIR}/leaf.key"
|
||||
local csr_tmp="${TMP_DIR}/leaf.csr"
|
||||
local crt_tmp="${TMP_DIR}/leaf.crt"
|
||||
|
||||
cat > "$req_cnf" <<EOF
|
||||
[ req ]
|
||||
default_md = sha256
|
||||
distinguished_name = dn
|
||||
req_extensions = req_ext
|
||||
prompt = no
|
||||
|
||||
[ dn ]
|
||||
O = mtusi-lab7
|
||||
CN = ${cn}
|
||||
|
||||
[ req_ext ]
|
||||
subjectAltName = ${san}
|
||||
EOF
|
||||
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out "$key_tmp"
|
||||
openssl req -new -sha256 -key "$key_tmp" -config "$req_cnf" -out "$csr_tmp"
|
||||
openssl ca -batch -notext -config "$CA_CNF" -extensions "$ext_section" \
|
||||
-in "$csr_tmp" -out "$crt_tmp" >/dev/null 2>&1
|
||||
|
||||
atomic_install "$crt_tmp" "$out_crt" 0644
|
||||
atomic_install "$key_tmp" "$out_key" "$key_mode"
|
||||
}
|
||||
|
||||
update_otel_cn_allowlist() {
|
||||
local old_cn="$1"
|
||||
local new_cn="$2"
|
||||
local list_file="${RUNTIME_PKI_DIR}/otel-gateway/allowed-otlp-cn.lst"
|
||||
[ -f "$list_file" ] || return 0
|
||||
local tmp="${TMP_DIR}/allowed-otlp-cn.lst"
|
||||
grep -Fxv "$old_cn" "$list_file" > "$tmp" || true
|
||||
if ! grep -Fxq "$new_cn" "$tmp"; then
|
||||
printf '%s\n' "$new_cn" >> "$tmp"
|
||||
fi
|
||||
atomic_install "$tmp" "$list_file" 0644
|
||||
reload_service otel-gateway USR2
|
||||
}
|
||||
|
||||
if [ $# -lt 1 ]; then
|
||||
echo "Usage: $0 <target> [--revoke] [--cn <new-cn>] | --revoke-cert <pem> | --issue-test-client <name> <cn> <san> <out-dir>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Mode 2: standalone PEM revocation
|
||||
if [ "$1" = "--revoke-cert" ]; then
|
||||
pem="${2:?missing pem path}"
|
||||
ser="$(cert_serial "$pem")"
|
||||
revoke_pem "$pem"
|
||||
regenerate_and_distribute_crl
|
||||
echo "revoke-cert ok: serial=${ser} crl_updated=true"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Mode 3: issue temporary test client cert
|
||||
if [ "$1" = "--issue-test-client" ]; then
|
||||
t_name="${2:?missing name}"
|
||||
t_cn="${3:?missing cn}"
|
||||
t_san="${4:?missing san}"
|
||||
t_dir="${5:?missing out-dir}"
|
||||
mkdir -p "$t_dir"
|
||||
issue_new_leaf client "$t_cn" "$t_san" "${t_dir}/${t_name}.crt" "${t_dir}/${t_name}.key" 0644
|
||||
cat "${t_dir}/${t_name}.crt" "${t_dir}/${t_name}.key" > "${TMP_DIR}/test.pem"
|
||||
atomic_install "${TMP_DIR}/test.pem" "${t_dir}/${t_name}.pem" 0644
|
||||
echo "issue-test-client ok: name=${t_name} cn=${t_cn} serial=$(cert_serial "${t_dir}/${t_name}.crt") fingerprint=$(cert_fp256 "${t_dir}/${t_name}.crt")"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Mode 1: rotate named target leaf cert
|
||||
TARGET="$1"
|
||||
shift
|
||||
REVOKE=0
|
||||
NEW_CN=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--revoke) REVOKE=1 ;;
|
||||
--cn)
|
||||
shift
|
||||
NEW_CN="${1:?missing value for --cn}"
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 <target> [--revoke] [--cn <new-cn>]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
kind="" cn="" san="" crt_path="" key_path="" bundle_path="" key_mode="0644" reload_svc="" reload_sig=""
|
||||
case "$TARGET" in
|
||||
api|api-server)
|
||||
kind=server; cn="api"; san="DNS:api"
|
||||
crt_path="${RUNTIME_PKI_DIR}/api/server.crt"; key_path="${RUNTIME_PKI_DIR}/api/server.key"
|
||||
reload_svc="api"; reload_sig="HUP"
|
||||
;;
|
||||
api-client)
|
||||
kind=client; cn="messenger-api-g1"; san="DNS:messenger-api"
|
||||
crt_path="${RUNTIME_PKI_DIR}/api/client.crt"; key_path="${RUNTIME_PKI_DIR}/api/client.key"
|
||||
reload_svc="api"; reload_sig="HUP"
|
||||
;;
|
||||
worker|worker-client)
|
||||
kind=client; cn="messenger-worker-g1"; san="DNS:messenger-worker"
|
||||
crt_path="${RUNTIME_PKI_DIR}/worker/client.crt"; key_path="${RUNTIME_PKI_DIR}/worker/client.key"
|
||||
reload_svc="worker"; reload_sig="HUP"
|
||||
;;
|
||||
migrate|migrator-client)
|
||||
kind=client; cn="messenger-migrator-g1"; san="DNS:messenger-migrator"
|
||||
crt_path="${RUNTIME_PKI_DIR}/migrate/client.crt"; key_path="${RUNTIME_PKI_DIR}/migrate/client.key"
|
||||
;;
|
||||
haproxy|haproxy-ingress|haproxy-server)
|
||||
kind=server; cn="localhost"; san="DNS:localhost,DNS:haproxy"
|
||||
crt_path="${RUNTIME_PKI_DIR}/haproxy/server.crt"; key_path="${RUNTIME_PKI_DIR}/haproxy/server.key"
|
||||
bundle_path="${RUNTIME_PKI_DIR}/haproxy/server.pem"
|
||||
reload_svc="haproxy"; reload_sig="USR2"
|
||||
;;
|
||||
haproxy-client)
|
||||
kind=client; cn="haproxy-lb-g1"; san="DNS:haproxy-lb"
|
||||
crt_path="${RUNTIME_PKI_DIR}/haproxy/client.crt"; key_path="${RUNTIME_PKI_DIR}/haproxy/client.key"
|
||||
bundle_path="${RUNTIME_PKI_DIR}/haproxy/client.pem"
|
||||
reload_svc="haproxy"; reload_sig="USR2"
|
||||
;;
|
||||
postgres)
|
||||
kind=server; cn="postgres"; san="DNS:postgres,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/postgres/server.crt"; key_path="${RUNTIME_PKI_DIR}/postgres/server.key"
|
||||
reload_svc="postgres"; reload_sig="PG"
|
||||
;;
|
||||
redis)
|
||||
kind=server; cn="redis"; san="DNS:redis,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/redis/server.crt"; key_path="${RUNTIME_PKI_DIR}/redis/server.key"
|
||||
;;
|
||||
s3)
|
||||
kind=server; cn="s3"; san="DNS:s3,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/s3/public.crt"; key_path="${RUNTIME_PKI_DIR}/s3/private.key"
|
||||
;;
|
||||
broker)
|
||||
kind=server; cn="broker"; san="DNS:broker"
|
||||
crt_path="${RUNTIME_PKI_DIR}/broker/server.crt"; key_path="${RUNTIME_PKI_DIR}/broker/server.key"
|
||||
;;
|
||||
otel-gateway)
|
||||
kind=server; cn="otel-collector"; san="DNS:otel-collector,DNS:otel-gateway"
|
||||
crt_path="${RUNTIME_PKI_DIR}/otel-gateway/server.crt"; key_path="${RUNTIME_PKI_DIR}/otel-gateway/server.key"
|
||||
bundle_path="${RUNTIME_PKI_DIR}/otel-gateway/server.pem"
|
||||
reload_svc="otel-gateway"; reload_sig="USR2"
|
||||
;;
|
||||
otel-collector)
|
||||
kind=client; cn="otel-collector"; san="DNS:otel-collector"
|
||||
crt_path="${RUNTIME_PKI_DIR}/otel-collector/client.crt"; key_path="${RUNTIME_PKI_DIR}/otel-collector/client.key"
|
||||
;;
|
||||
prometheus)
|
||||
kind=server; cn="prometheus"; san="DNS:prometheus,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/prometheus/server.crt"; key_path="${RUNTIME_PKI_DIR}/prometheus/server.key"
|
||||
reload_svc="prometheus"; reload_sig="HUP"
|
||||
;;
|
||||
prometheus-client)
|
||||
kind=client; cn="prometheus"; san="DNS:prometheus"
|
||||
crt_path="${RUNTIME_PKI_DIR}/prometheus/client.crt"; key_path="${RUNTIME_PKI_DIR}/prometheus/client.key"
|
||||
reload_svc="prometheus"; reload_sig="HUP"
|
||||
;;
|
||||
loki)
|
||||
kind=server; cn="loki"; san="DNS:loki"
|
||||
crt_path="${RUNTIME_PKI_DIR}/loki/server.crt"; key_path="${RUNTIME_PKI_DIR}/loki/server.key"
|
||||
;;
|
||||
tempo)
|
||||
kind=server; cn="tempo"; san="DNS:tempo"
|
||||
crt_path="${RUNTIME_PKI_DIR}/tempo/server.crt"; key_path="${RUNTIME_PKI_DIR}/tempo/server.key"
|
||||
;;
|
||||
grafana)
|
||||
kind=server; cn="grafana"; san="DNS:grafana,DNS:localhost"
|
||||
crt_path="${RUNTIME_PKI_DIR}/grafana/server.crt"; key_path="${RUNTIME_PKI_DIR}/grafana/server.key"
|
||||
;;
|
||||
grafana-client)
|
||||
kind=client; cn="grafana"; san="DNS:grafana"
|
||||
crt_path="${RUNTIME_PKI_DIR}/grafana/client.crt"; key_path="${RUNTIME_PKI_DIR}/grafana/client.key"
|
||||
;;
|
||||
openbao)
|
||||
kind=server; cn="openbao"; san="DNS:openbao,DNS:localhost,IP:127.0.0.1"
|
||||
crt_path="${RUNTIME_PKI_DIR}/openbao/server.crt"; key_path="${RUNTIME_PKI_DIR}/openbao/server.key"
|
||||
reload_svc="openbao"; reload_sig="HUP"
|
||||
;;
|
||||
operator)
|
||||
kind=client; cn="messenger-operator-g1"; san="DNS:messenger-operator"
|
||||
crt_path="${OP_CERT}"; key_path="${OP_KEY}"; key_mode="0600"
|
||||
;;
|
||||
rogue-client)
|
||||
kind=client; cn="rogue-client"; san="DNS:rogue-client"
|
||||
crt_path="${PKI_OP_DIR}/rogue-client.crt"; key_path="${PKI_OP_DIR}/rogue-client.key"; key_mode="0600"
|
||||
;;
|
||||
*)
|
||||
echo "error: unknown cert target '${TARGET}'" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
old_serial="none"
|
||||
old_cn=""
|
||||
if [ -s "$crt_path" ]; then
|
||||
old_serial="$(cert_serial "$crt_path")"
|
||||
old_cn="$(cert_cn "$crt_path")"
|
||||
cp "$crt_path" "${TMP_DIR}/old.crt"
|
||||
fi
|
||||
|
||||
if [ -n "$NEW_CN" ]; then
|
||||
cn="$NEW_CN"
|
||||
elif [ -n "$old_cn" ]; then
|
||||
cn="$old_cn"
|
||||
fi
|
||||
|
||||
issue_new_leaf "$kind" "$cn" "$san" "$crt_path" "$key_path" "$key_mode"
|
||||
if [ -n "$bundle_path" ]; then
|
||||
cat "$crt_path" "$key_path" > "${TMP_DIR}/bundle.pem"
|
||||
atomic_install "${TMP_DIR}/bundle.pem" "$bundle_path" 0644
|
||||
fi
|
||||
|
||||
if [ -n "$old_cn" ] && [ "$old_cn" != "$cn" ]; then
|
||||
case "$TARGET" in
|
||||
api-client|worker|worker-client)
|
||||
update_otel_cn_allowlist "$old_cn" "$cn"
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
if [ "$REVOKE" -eq 1 ] && [ -s "${TMP_DIR}/old.crt" ]; then
|
||||
revoke_pem "${TMP_DIR}/old.crt"
|
||||
regenerate_and_distribute_crl
|
||||
fi
|
||||
|
||||
if [ "$reload_svc" = "postgres" ]; then
|
||||
refresh_postgres_tls
|
||||
elif [ -n "$reload_svc" ] && [ -n "$reload_sig" ]; then
|
||||
reload_service "$reload_svc" "$reload_sig"
|
||||
fi
|
||||
|
||||
new_serial="$(cert_serial "$crt_path")"
|
||||
new_fp="$(cert_fp256 "$crt_path")"
|
||||
echo "rotate-cert ok: target=${TARGET} cn=${cn} old_serial=${old_serial} new_serial=${new_serial} fingerprint=${new_fp} revoked=$([ "$REVOKE" -eq 1 ] && echo true || echo false)"
|
||||
Executable
+248
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env bash
|
||||
# Lab 7 Zero-Rebuild Working Secret Rotation (operator mTLS auth, zero root token).
|
||||
# Usage: scripts/rotate-secret.sh [api-db|api-redis|api-s3|worker-db|worker-s3|migrator-db|api|worker]
|
||||
# Rotates credential in both live backend store AND OpenBao KV v2, then signals
|
||||
# SIGHUP to running workload(s) for immediate live pickup without image rebuild.
|
||||
# Never prints secret values.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
TARGET="${1:-api-db}"
|
||||
case "$TARGET" in
|
||||
api-db|api-redis|api-s3|worker-db|worker-s3|migrator-db|api|worker) ;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [api-db|api-redis|api-s3|worker-db|worker-s3|migrator-db|api|worker]"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "error: unknown rotation target '${TARGET}'" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -f .env ]; then
|
||||
# shellcheck disable=SC1091
|
||||
set -a; . ./.env; set +a
|
||||
fi
|
||||
|
||||
OPERATOR_DIR="${LAB7_OPERATOR_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mtusi-lab7-operator}"
|
||||
OP_CERT="${OPERATOR_DIR}/operator/operator.crt"
|
||||
OP_KEY="${OPERATOR_DIR}/operator/operator.key"
|
||||
CA_CERT="${CA_FILE:-$(pwd)/secrets/pki/ca.crt}"
|
||||
BAO_ADDR="${BAO_ADDR_HOST:-https://localhost:${OPENBAO_PORT:-8200}}"
|
||||
COMPOSE=(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}")
|
||||
MC_IMAGE="minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727"
|
||||
|
||||
umask 077
|
||||
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/lab7-rot-sec.XXXXXX")"
|
||||
OP_CFG="${TMP_DIR}/op-auth.cfg"
|
||||
cleanup() {
|
||||
if [ -s "$OP_CFG" ]; then
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
"${BAO_ADDR}/v1/auth/token/revoke-self" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$TMP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
login_json="$(curl -fsS --cacert "$CA_CERT" --cert "$OP_CERT" --key "$OP_KEY" \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"name":"messenger-operator"}' \
|
||||
"${BAO_ADDR}/v1/auth/cert/login")"
|
||||
op_token="$(printf '%s' "$login_json" | jq -r '.auth.client_token // empty')"
|
||||
if [ -z "$op_token" ]; then
|
||||
echo "error: operator mTLS auth to OpenBao failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf 'header = "X-Vault-Token: %s"\n' "$op_token" > "$OP_CFG"
|
||||
chmod 0600 "$OP_CFG"
|
||||
unset login_json op_token
|
||||
|
||||
read_kv() {
|
||||
curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" "${BAO_ADDR}/v1/secret/data/${1}" | jq -c '.data.data'
|
||||
}
|
||||
|
||||
write_kv() {
|
||||
local path="$1"
|
||||
local data_json="$2"
|
||||
printf '%s' "$data_json" \
|
||||
| jq '{data: .}' \
|
||||
| curl -fsS --cacert "$CA_CERT" -K "$OP_CFG" -X POST \
|
||||
-H 'Content-Type: application/json' --data-binary @- \
|
||||
"${BAO_ADDR}/v1/secret/data/${path}" \
|
||||
| jq -r '.data.version'
|
||||
}
|
||||
|
||||
rotate_pg_role() {
|
||||
local role="$1"
|
||||
local new_pass="$2"
|
||||
{
|
||||
printf "SET password_encryption = 'scram-sha-256';\n"
|
||||
printf "ALTER ROLE %s WITH LOGIN PASSWORD '%s';\n" "$role" "$new_pass"
|
||||
} | "${COMPOSE[@]}" exec -T postgres psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" -v ON_ERROR_STOP=1 >/dev/null
|
||||
}
|
||||
|
||||
rotate_redis_api() {
|
||||
local new_pass="$1"
|
||||
printf 'ACL SETUSER messenger_api reset on >%s ~session:sha256:* ~messages:* ~lock:messages:* ~rl:* ~fault:* -@all +ping +hello +client|setinfo +quit +get +set +del +incr +expire +pexpire +ttl +pttl +@scripting +multi +exec +discard\nACL SAVE\n' \
|
||||
"$new_pass" \
|
||||
| "${COMPOSE[@]}" exec -T redis sh -c \
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/redis_admin_password)" redis-cli --tls --cacert /run/certs/ca.crt --cert /run/certs/health.crt --key /run/certs/health.key --user redis_admin -h localhost -p 6379 >/dev/null'
|
||||
}
|
||||
|
||||
minio_exec() {
|
||||
local s3_cid app_data_net
|
||||
s3_cid="$("${COMPOSE[@]}" ps -q s3 | head -n 1)"
|
||||
app_data_net="$(docker inspect --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$s3_cid" \
|
||||
| tr ' ' '\n' | grep '_app_data$' | head -n 1)"
|
||||
docker run --rm -i \
|
||||
--network "$app_data_net" \
|
||||
--user 1000:1000 \
|
||||
--read-only \
|
||||
--cap-drop ALL \
|
||||
--security-opt no-new-privileges:true \
|
||||
--tmpfs /tmp:size=16m,noexec,nosuid,nodev \
|
||||
-v "$(pwd)/secrets/pki/ca.crt:/run/certs/ca.crt:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_user:/run/secrets/minio_root_user:ro" \
|
||||
-v "$(pwd)/secrets/infra/minio_root_password:/run/secrets/minio_root_password:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
"$MC_IMAGE" -c "$1"
|
||||
}
|
||||
|
||||
add_minio_user() {
|
||||
local policy="$1"
|
||||
local user="$2"
|
||||
local secret="$3"
|
||||
printf '%s\n%s\n%s\n' "$policy" "$user" "$secret" | minio_exec '
|
||||
set -eu
|
||||
IFS= read -r ru < /run/secrets/minio_root_user || [ -n "$ru" ]
|
||||
IFS= read -r rp < /run/secrets/minio_root_password || [ -n "$rp" ]
|
||||
IFS= read -r pol; IFS= read -r u; IFS= read -r s
|
||||
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
export MC_HOST_stand="https://${ru}:${rp}@s3:9000"
|
||||
mc admin user add stand "$u" "$s" >/dev/null
|
||||
mc admin policy attach stand "$pol" --user "$u" >/dev/null
|
||||
'
|
||||
}
|
||||
|
||||
remove_minio_user() {
|
||||
local old_user="$1"
|
||||
[ -n "$old_user" ] || return 0
|
||||
printf '%s\n' "$old_user" | minio_exec '
|
||||
set -eu
|
||||
IFS= read -r ru < /run/secrets/minio_root_user || [ -n "$ru" ]
|
||||
IFS= read -r rp < /run/secrets/minio_root_password || [ -n "$rp" ]
|
||||
IFS= read -r u
|
||||
export HOME=/tmp MC_CONFIG_DIR=/tmp/.mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /run/certs/ca.crt "$MC_CONFIG_DIR/certs/CAs/ca.crt"
|
||||
export MC_HOST_stand="https://${ru}:${rp}@s3:9000"
|
||||
mc admin user remove stand "$u" >/dev/null 2>&1 || true
|
||||
'
|
||||
}
|
||||
|
||||
signal_service() {
|
||||
local svc="$1"
|
||||
if [ -n "$("${COMPOSE[@]}" ps -q --status running "$svc" 2>/dev/null)" ]; then
|
||||
"${COMPOSE[@]}" kill -s HUP "$svc" >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
kv_ver=""
|
||||
case "$TARGET" in
|
||||
api-db)
|
||||
cur="$(read_kv messenger/api)"
|
||||
new_pass="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_api "$new_pass"
|
||||
updated="$(printf '%s' "$cur" | jq --arg p "$new_pass" '.db_password = $p')"
|
||||
kv_ver="$(write_kv messenger/api "$updated")"
|
||||
signal_service api
|
||||
;;
|
||||
api-redis)
|
||||
cur="$(read_kv messenger/api)"
|
||||
new_pass="$(openssl rand -hex 24)"
|
||||
rotate_redis_api "$new_pass"
|
||||
updated="$(printf '%s' "$cur" | jq --arg p "$new_pass" '.redis_password = $p')"
|
||||
kv_ver="$(write_kv messenger/api "$updated")"
|
||||
signal_service api
|
||||
;;
|
||||
api-s3)
|
||||
cur="$(read_kv messenger/api)"
|
||||
old_key="$(printf '%s' "$cur" | jq -r '.s3_access_key_id')"
|
||||
new_key="api-$(openssl rand -hex 8)"
|
||||
new_sec="$(openssl rand -hex 24)"
|
||||
add_minio_user messenger-api "$new_key" "$new_sec"
|
||||
updated="$(printf '%s' "$cur" | jq --arg k "$new_key" --arg s "$new_sec" '.s3_access_key_id = $k | .s3_secret_access_key = $s')"
|
||||
kv_ver="$(write_kv messenger/api "$updated")"
|
||||
signal_service api
|
||||
sleep 2
|
||||
remove_minio_user "$old_key"
|
||||
;;
|
||||
api)
|
||||
cur="$(read_kv messenger/api)"
|
||||
old_key="$(printf '%s' "$cur" | jq -r '.s3_access_key_id')"
|
||||
new_db="$(openssl rand -hex 24)"
|
||||
new_redis="$(openssl rand -hex 24)"
|
||||
new_key="api-$(openssl rand -hex 8)"
|
||||
new_sec="$(openssl rand -hex 24)"
|
||||
new_metrics="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_api "$new_db"
|
||||
rotate_redis_api "$new_redis"
|
||||
add_minio_user messenger-api "$new_key" "$new_sec"
|
||||
updated="$(printf '%s' "$cur" | jq \
|
||||
--arg db "$new_db" --arg rd "$new_redis" \
|
||||
--arg k "$new_key" --arg s "$new_sec" --arg m "$new_metrics" \
|
||||
'.db_password=$db | .redis_password=$rd | .s3_access_key_id=$k | .s3_secret_access_key=$s | .metrics_token=$m')"
|
||||
kv_ver="$(write_kv messenger/api "$updated")"
|
||||
signal_service api
|
||||
sleep 2
|
||||
remove_minio_user "$old_key"
|
||||
;;
|
||||
worker-db)
|
||||
cur="$(read_kv messenger/worker)"
|
||||
new_pass="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_worker "$new_pass"
|
||||
updated="$(printf '%s' "$cur" | jq --arg p "$new_pass" '.db_password = $p')"
|
||||
kv_ver="$(write_kv messenger/worker "$updated")"
|
||||
signal_service worker
|
||||
;;
|
||||
worker-s3)
|
||||
cur="$(read_kv messenger/worker)"
|
||||
old_key="$(printf '%s' "$cur" | jq -r '.s3_access_key_id')"
|
||||
new_key="worker-$(openssl rand -hex 8)"
|
||||
new_sec="$(openssl rand -hex 24)"
|
||||
add_minio_user messenger-worker "$new_key" "$new_sec"
|
||||
updated="$(printf '%s' "$cur" | jq --arg k "$new_key" --arg s "$new_sec" '.s3_access_key_id = $k | .s3_secret_access_key = $s')"
|
||||
kv_ver="$(write_kv messenger/worker "$updated")"
|
||||
signal_service worker
|
||||
sleep 2
|
||||
remove_minio_user "$old_key"
|
||||
;;
|
||||
worker)
|
||||
cur="$(read_kv messenger/worker)"
|
||||
old_key="$(printf '%s' "$cur" | jq -r '.s3_access_key_id')"
|
||||
new_db="$(openssl rand -hex 24)"
|
||||
new_key="worker-$(openssl rand -hex 8)"
|
||||
new_sec="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_worker "$new_db"
|
||||
add_minio_user messenger-worker "$new_key" "$new_sec"
|
||||
updated="$(printf '%s' "$cur" | jq \
|
||||
--arg db "$new_db" --arg k "$new_key" --arg s "$new_sec" \
|
||||
'.db_password=$db | .s3_access_key_id=$k | .s3_secret_access_key=$s')"
|
||||
kv_ver="$(write_kv messenger/worker "$updated")"
|
||||
signal_service worker
|
||||
sleep 2
|
||||
remove_minio_user "$old_key"
|
||||
;;
|
||||
migrator-db)
|
||||
cur="$(read_kv messenger/migrator)"
|
||||
new_pass="$(openssl rand -hex 24)"
|
||||
rotate_pg_role messenger_migrator "$new_pass"
|
||||
updated="$(printf '%s' "$cur" | jq --arg p "$new_pass" '.db_password = $p')"
|
||||
kv_ver="$(write_kv messenger/migrator "$updated")"
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "rotate-secret ok: target=${TARGET} kv_version=${kv_ver}"
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Восстанавливает недостающую API-реплику до объявленного числа реплик.
|
||||
# Восстанавливает недостающую API-реплику до объявленного числа реплик без пересборки образа.
|
||||
set -eu
|
||||
|
||||
env_file="${COMPOSE_ENV_FILE:-.env}"
|
||||
@@ -8,4 +8,4 @@ if [ -z "$replicas" ] && [ -f "$env_file" ]; then
|
||||
replicas=$(sed -n 's/^API_REPLICAS=//p' "$env_file" | tail -n 1)
|
||||
fi
|
||||
replicas="${replicas:-2}"
|
||||
exec docker compose --env-file "$env_file" up -d --no-deps --scale "api=${replicas}" api
|
||||
exec docker compose --env-file "$env_file" up -d --no-build --no-deps --wait --scale "api=${replicas}" api
|
||||
|
||||
+11
-8
@@ -1,10 +1,8 @@
|
||||
#!/bin/sh
|
||||
# Останавливает ровно одну API-реплику стенда — ту, которую обслужила текущая
|
||||
# сессия. TARGET_INSTANCE_ID приходит из теста (значение X-Instance-Id ответа),
|
||||
# а в Docker hostname контейнера равен его короткому ID, поэтому сопоставление
|
||||
# однозначно. Ничего, кроме этой реплики, скрипт не трогает: ни LB, ни БД, ни
|
||||
# тома. Возврат управления — быстрый (SIGTERM -> дрейн DRAIN_DELAY_MS=3s ->
|
||||
# выход), останавливать реплику "навсегда" не требуется.
|
||||
# Останавливает ровно одну API-реплику стенда — ту, которая обслужила текущую
|
||||
# сессию. В lab7 X-Instance-Id — непрозрачный случайный алиас (без hostname/IP),
|
||||
# который API записывает в /tmp/instance-id внутри tmpfs контейнера.
|
||||
# Ничего, кроме целевой реплики, скрипт не трогает.
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
@@ -17,6 +15,11 @@ for container in $(
|
||||
--filter 'label=com.docker.compose.service=api' \
|
||||
--format '{{.ID}}'
|
||||
); do
|
||||
alias_val="$(docker exec "$container" cat /tmp/instance-id 2>/dev/null || true)"
|
||||
if [ -n "$alias_val" ] && [ "$alias_val" = "$TARGET_INSTANCE_ID" ]; then
|
||||
target="$container"
|
||||
break
|
||||
fi
|
||||
case "$container" in
|
||||
"$TARGET_INSTANCE_ID"*)
|
||||
target="$container"
|
||||
@@ -26,10 +29,10 @@ for container in $(
|
||||
done
|
||||
|
||||
if [ -z "$target" ]; then
|
||||
printf 'stop-one: no running api replica of project %s whose id starts with %s\n' \
|
||||
printf 'stop-one: no running api replica of project %s matching instance alias %s\n' \
|
||||
"$project" "$TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf 'stop-one: stopping api replica %s\n' "$target" >&2
|
||||
printf 'stop-one: stopping api replica %s (alias=%s)\n' "$target" "$TARGET_INSTANCE_ID" >&2
|
||||
docker stop --time 10 "$target" >/dev/null
|
||||
|
||||
Reference in New Issue
Block a user