forked from mtusi2026/mtusi2026lab7
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
+98
-184
@@ -1,200 +1,114 @@
|
||||
#!/bin/sh
|
||||
# Проверка критерия «LB исключает неготовую реплику» (lab5).
|
||||
#
|
||||
# Рядом с рабочими репликами поднимается третья с тем же сетевым alias, но её
|
||||
# доступ к БД идёт через временный TCP-прокси. Пока прокси жив, реплика готова и
|
||||
# получает трафик через LB. После остановки прокси реплика остаётся доступной по
|
||||
# сети (процесс жив, порт открыт), но /health/ready отвечает 503 — и балансировщик
|
||||
# обязан убрать её из ротации и не отправлять ей ни одного запроса.
|
||||
#
|
||||
# scripts/lb_readiness_check.sh # стенд поднят (make up)
|
||||
# OUT=evidence/lb-readiness.txt scripts/lb_readiness_check.sh
|
||||
# Verify LB exclusion of a live API whose native TLS PostgreSQL path has failed.
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec "${PYTHON:-python3}" - "$@" <<'PY'
|
||||
from collections import Counter
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
# .env определяет, на каком порту публикуется LB (compose.yaml) и какие креды у
|
||||
# хранилищ, поэтому значения берём оттуда же, а не из окружения вызывающего.
|
||||
if [ -f .env ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
. ./.env
|
||||
set +a
|
||||
fi
|
||||
sys.path.insert(0, str(Path.cwd() / 'scripts'))
|
||||
sys.path.insert(0, str(Path.cwd() / 'tests'))
|
||||
from lab7_environment import Environment, ROOT
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url
|
||||
from client import Client
|
||||
|
||||
OUT=${OUT:-evidence/lab5/lb-readiness-detail.txt}
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab6}
|
||||
NET=${PROJECT}_default
|
||||
IMAGE=${IMAGE:-mtusi-messenger:lab6}
|
||||
STATS=${STATS:-http://127.0.0.1:${LB_STATS_PORT:-8404}/stats;csv}
|
||||
BASE_URL=${BASE_URL:-http://localhost:${SERVER_PORT:-8080}}
|
||||
CANDIDATE=lb-readiness-candidate
|
||||
PROXY=lb-readiness-pgproxy
|
||||
REQUESTS=${REQUESTS:-40}
|
||||
environment = Environment()
|
||||
client = Client(BASE_URL, CA_FILE, timeout=5)
|
||||
output = Path(os.environ.get('OUT', 'evidence/lab5/lb-readiness-detail.txt'))
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
replicas = environment.compose('ps', '-q', 'api').stdout.split()
|
||||
if len(replicas) < 2:
|
||||
raise SystemExit('readiness exclusion needs two healthy Compose API replicas')
|
||||
networks = json.loads(environment.run(['docker', 'inspect', '--format',
|
||||
'{{json .NetworkSettings.Networks}}', replicas[0]]).stdout)
|
||||
if len(networks) != 1:
|
||||
raise SystemExit('expected exactly one API network for the isolated TLS tunnel')
|
||||
network = next(iter(networks))
|
||||
prefix = environment.project + '-readiness-' + uuid.uuid4().hex[:8]
|
||||
proxy, candidate = prefix + '-tunnel', prefix + '-api'
|
||||
stats_url = os.environ.get('STATS', 'https://localhost:' + environment.value('LB_STATS_PORT', '8404') + '/stats;csv')
|
||||
log = []
|
||||
|
||||
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
|
||||
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
|
||||
|
||||
cleanup() {
|
||||
docker rm -f "$CANDIDATE" "$PROXY" >/dev/null 2>&1 || true
|
||||
}
|
||||
def stats():
|
||||
with open_url(stats_url, operator=True) as response:
|
||||
rows = csv.DictReader(io.StringIO(response.read().decode().replace('# ', '', 1)))
|
||||
return {row['svname']: row['status'] for row in rows
|
||||
if row['pxname'].startswith('api') and row['svname'] not in ('BACKEND', 'FRONTEND')}
|
||||
|
||||
trap cleanup EXIT INT TERM
|
||||
cleanup
|
||||
|
||||
instances() {
|
||||
tries=${1:-$REQUESTS}
|
||||
i=0
|
||||
def local_status():
|
||||
result = environment.run(['docker', 'exec', candidate, 'wget', '-qO-', '-S', '-T', '3',
|
||||
'http://127.0.0.1:8084/health/ready'], check=False)
|
||||
matches = re.findall(r'HTTP/\S+\s+(\d{3})', result.stderr)
|
||||
return int(matches[-1]) if matches else None
|
||||
|
||||
while [ "$i" -lt "$tries" ]; do
|
||||
curl -fsS --noproxy '*' -D - -o /dev/null "$BASE_URL/health/live" 2>/dev/null \
|
||||
| awk 'tolower($1) == "x-instance-id:" { print $2 }'
|
||||
i=$((i + 1))
|
||||
done | sort | uniq -c
|
||||
}
|
||||
|
||||
stats() {
|
||||
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ { printf "%s=%s ", $2, $18 }'
|
||||
}
|
||||
def wait(predicate, description, seconds=60):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(description)
|
||||
|
||||
readiness() {
|
||||
docker exec "$CANDIDATE" wget -qO- -S -T 3 http://127.0.0.1:8080/health/ready 2>&1 \
|
||||
| awk '/^ HTTP\//{print $2; exit}'
|
||||
}
|
||||
|
||||
wait_readiness() {
|
||||
want=$1
|
||||
attempt=0
|
||||
def observed():
|
||||
return Counter(client.call('GET', '/health/live', schema='Health')['headers']['X-Instance-Id']
|
||||
for _ in range(int(os.environ.get('REQUESTS', '40'))))
|
||||
|
||||
while [ "$attempt" -lt 30 ]; do
|
||||
[ "$(readiness)" = "$want" ] && return 0
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
up_slots() {
|
||||
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ && $18 ~ /^UP/ && $2 != "BACKEND" { printf "%s ", $2 }'
|
||||
}
|
||||
|
||||
wait_new_up_slot() {
|
||||
before=$1
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 30 ]; do
|
||||
for slot in $(up_slots); do
|
||||
case " $before " in
|
||||
*" $slot "*) ;;
|
||||
*) echo "$slot"; return 0 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
wait_slot_status() {
|
||||
slot=$1
|
||||
want=$2
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
status=$(curl -s --noproxy '*' "$STATS" | awk -F, -v s="$slot" '$1 ~ /^api/ && $2 == s { print $18; exit }')
|
||||
|
||||
if [ "$status" = "$want" ]; then
|
||||
SWAIT_SECONDS=$((attempt / 2))
|
||||
return 0
|
||||
fi
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 0.5
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
{
|
||||
echo "# LB excludes a not-ready but reachable replica (lab5)"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# lb: $(docker inspect -f '{{.Config.Image}}' "$(docker ps -q --filter label=com.docker.compose.service=lb)" 2>/dev/null)"
|
||||
echo
|
||||
echo "## 1. baseline: requests through LB by replica"
|
||||
instances
|
||||
baseline_slots=$(up_slots)
|
||||
echo " stats: $(stats)"
|
||||
echo
|
||||
echo "## 2. start a temporary TCP proxy to postgres and a candidate replica behind the same network alias"
|
||||
docker run -d --name "$PROXY" --network "$NET" alpine/socat@sha256:fb3862c949af7c79996d0e514ee96128644d840835ed5368eeecb14a869de361 \
|
||||
tcp-listen:5432,fork,reuseaddr tcp-connect:postgres:5432 >/dev/null
|
||||
docker run -d --name "$CANDIDATE" --network "$NET" --network-alias api-replica \
|
||||
-e APP_CONFIG=/etc/messenger/dev/config.yaml \
|
||||
-e POSTGRES_HOST="$PROXY" -e POSTGRES_PORT=5432 \
|
||||
-e POSTGRES_DATABASE="${POSTGRES_DATABASE:-messenger}" \
|
||||
-e POSTGRES_USER="${POSTGRES_USER:-messenger}" \
|
||||
-e POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-messenger}" -e POSTGRES_SSL_MODE=disable \
|
||||
-e REDIS_ENABLED=true -e REDIS_HOST=redis -e CACHE_ENABLED=true \
|
||||
-e S3_ENDPOINT=http://seaweedfs:8333 -e S3_REGION="${S3_REGION:-us-east-1}" \
|
||||
-e S3_BUCKET="${S3_BUCKET:-messenger-attachments}" \
|
||||
-e S3_ACCESS_KEY_ID="${S3_ACCESS_KEY_ID:-lab4app}" \
|
||||
-e S3_SECRET_ACCESS_KEY="${S3_SECRET_ACCESS_KEY:-lab4app-secret}" \
|
||||
-e S3_USE_PATH_STYLE=true \
|
||||
"$IMAGE" >/dev/null
|
||||
|
||||
if ! wait_readiness 200; then
|
||||
echo " candidate did not become ready" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " instance-id: $(docker inspect -f '{{.Config.Hostname}}' "$CANDIDATE"), readiness while its database is reachable: 200"
|
||||
|
||||
slot=$(wait_new_up_slot "$baseline_slots" || true)
|
||||
if [ -z "$slot" ]; then
|
||||
echo " candidate did not appear UP in the load balancer" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " load balancer slot for the candidate: $slot, stats: $(stats)"
|
||||
echo
|
||||
echo "## 3. cut the candidate's database access (stop only the TCP proxy)"
|
||||
docker stop "$PROXY" >/dev/null
|
||||
|
||||
if ! wait_readiness 503; then
|
||||
echo " candidate readiness did not become 503" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " candidate is still running: $(docker inspect -f '{{.State.Status}}' "$CANDIDATE"), readiness: 503"
|
||||
echo " waiting for the load balancer to mark $slot DOWN"
|
||||
|
||||
if wait_slot_status "$slot" DOWN; then
|
||||
echo " $slot went DOWN ${SWAIT_SECONDS}s after its database was cut (check: inter 2s fall 2)"
|
||||
else
|
||||
echo " FAIL: $slot is still not DOWN" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " stats after failure: $(stats)"
|
||||
echo
|
||||
echo "## 4. ${REQUESTS} requests through LB while the candidate is not ready"
|
||||
instances
|
||||
echo " (the candidate must not appear above)"
|
||||
echo
|
||||
echo "## 5. business writes through LB during the exclusion"
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV python3 tests/load.py --base-url "$BASE_URL" --duration 5 --concurrency 2 \
|
||||
| grep -E '"successful_rps"|"failed_requests"|"error_ratio"'
|
||||
echo
|
||||
echo "## 6. cleanup"
|
||||
cleanup
|
||||
sleep 5
|
||||
echo " stats after cleanup: $(stats)"
|
||||
} > "$OUT" 2>&1
|
||||
|
||||
cat "$OUT"
|
||||
printf 'lb_readiness_check.sh: evidence in %s\n' "$OUT"
|
||||
with tempfile.TemporaryDirectory(prefix='lab7-readiness-') as temporary:
|
||||
try:
|
||||
baseline = stats()
|
||||
log.append('baseline instances: ' + json.dumps(observed()))
|
||||
# This network-only tunnel forwards encrypted PostgreSQL bytes unchanged.
|
||||
# It has no credentials, TLS termination, API listener or host-published ports.
|
||||
environment.run(['docker', 'run', '-d', '--name', proxy, '--network', network,
|
||||
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges:true', '--read-only',
|
||||
'alpine/socat@sha256:fb3862c949af7c79996d0e514ee96128644d840835ed5368eeecb14a869de361',
|
||||
'tcp-listen:5432,fork,reuseaddr', 'tcp-connect:postgres:5432'])
|
||||
proxy_networks = json.loads(environment.run(['docker', 'inspect', '--format',
|
||||
'{{json .NetworkSettings.Networks}}', proxy]).stdout)
|
||||
proxy_ip = proxy_networks[network]['IPAddress']
|
||||
override = Path(temporary) / 'compose.json'
|
||||
# Preserve the real postgres hostname/SAN and Bao-supplied role credentials.
|
||||
override.write_text(json.dumps({'services': {'api': {'extra_hosts': ['postgres:' + proxy_ip]}}}))
|
||||
environment.compose('-f', str(override), 'run', '-d', '--no-deps', '--use-aliases',
|
||||
'--name', candidate, 'api')
|
||||
wait(lambda: local_status() == 200, 'candidate did not become ready')
|
||||
slot = wait(lambda: next((name for name, status in stats().items()
|
||||
if status.startswith('UP') and not baseline.get(name, '').startswith('UP')), None),
|
||||
'candidate did not enter the LB rotation')
|
||||
hostname = environment.run(['docker', 'inspect', '--format', '{{.Config.Hostname}}', candidate]).stdout.strip()
|
||||
log.append('candidate ready: instance=' + hostname + ' slot=' + slot)
|
||||
environment.run(['docker', 'stop', proxy])
|
||||
wait(lambda: local_status() == 503, 'candidate did not become not-ready')
|
||||
state = environment.run(['docker', 'inspect', '--format', '{{.State.Status}}', candidate]).stdout.strip()
|
||||
if state != 'running':
|
||||
raise RuntimeError('candidate stopped instead of reporting not-ready')
|
||||
wait(lambda: stats().get(slot, '').startswith('DOWN'), 'LB did not exclude the not-ready candidate')
|
||||
after = observed()
|
||||
if hostname in after:
|
||||
raise RuntimeError('LB routed a request to the not-ready candidate')
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
for index in range(10):
|
||||
client.message(alice, chat, 'readiness-exclusion-' + str(index))
|
||||
log += ['candidate alive/readiness503; LB slot DOWN', 'during outage instances: ' + json.dumps(after),
|
||||
'business writes through remaining replicas: 10']
|
||||
finally:
|
||||
environment.run(['docker', 'rm', '-f', candidate, proxy], check=False)
|
||||
output.write_text('\n'.join(log) + '\n')
|
||||
print('\n'.join(log))
|
||||
PY
|
||||
|
||||
Reference in New Issue
Block a user