#!/usr/bin/env bash set -Eeuo pipefail repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N5 -tx1 /dev/urandom | tr -d ' \\n')" project="heimdall-optional-services-${suffix}" temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX") install_root="$temp_dir/install-root" secret_dir="$install_root/optional/secrets" backup_scripts_dir="$install_root/optional/scripts" env_file="$temp_dir/acceptance.env" override_file="$temp_dir/compose.override.yml" turn_log="$temp_dir/turn-client.log" rustfs_compose="$repo_root/docker/docker-compose.rustfs.yml" coturn_compose="$repo_root/docker/docker-compose.coturn.yml" backup_compose="$repo_root/docker/docker-compose.backup.yml" backup_scripts=(backup.sh backup-protected-data.sh backup-rustfs.sh restore.sh restore-protected-data.sh) local_image_tags=() mkdir -p "$secret_dir" "$backup_scripts_dir" compose() { docker compose --project-directory "$install_root" --env-file "$env_file" \ -f "$rustfs_compose" -f "$coturn_compose" -f "$override_file" \ -p "$project" "$@" } cleanup() { status=$? trap - EXIT cleanup_failed=0 compose down --volumes --remove-orphans || cleanup_failed=1 containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 if [[ -n "$containers" ]]; then # `compose run --rm` may leave a one-off test container behind if the # client exits during shutdown; remove only containers carrying this # recipe's unique Compose project label. while IFS= read -r container; do [[ -z "$container" ]] || docker rm -f "$container" >/dev/null || cleanup_failed=1 done <<< "$containers" fi containers=$(docker ps -aq --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 volumes=$(docker volume ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 networks=$(docker network ls -q --filter "label=com.docker.compose.project=$project") || cleanup_failed=1 if [[ -n "$containers" || -n "$volumes" || -n "$networks" ]]; then printf 'Project resources remain: containers=%s volumes=%s networks=%s\n' \ "${containers:-}" "${volumes:-}" "${networks:-}" >&2 cleanup_failed=1 else printf 'Verified no project containers, volumes, or networks remain: %s\n' "$project" fi if ((${#local_image_tags[@]} == 0)); then printf 'No local images built; upstream service images retained.\n' fi for tag in "${local_image_tags[@]}"; do docker image rm "$tag" >/dev/null 2>&1 || true if docker image inspect "$tag" >/dev/null 2>&1; then printf 'Recipe image remains: %s\n' "$tag" >&2 cleanup_failed=1 else printf 'Verified recipe image absent: %s\n' "$tag" fi done rm -f -- "$env_file" "$override_file" "$turn_log" \ "$secret_dir/rustfs_access_key" "$secret_dir/rustfs_secret_key" \ "$secret_dir/coturn_secret" "$secret_dir/db_password" || cleanup_failed=1 for name in "${backup_scripts[@]}"; do rm -f -- "$backup_scripts_dir/$name" || cleanup_failed=1 done rmdir -- "$backup_scripts_dir" "$secret_dir" "$install_root/optional" "$install_root" || cleanup_failed=1 rmdir -- "$temp_dir" || cleanup_failed=1 if ((cleanup_failed)); then printf 'Disposable optional-service cleanup failed for %s\n' "$project" >&2 status=1 fi exit "$status" } trap cleanup EXIT read -r rustfs_api_port rustfs_console_port coturn_port relay_min relay_max < <(python3 - <<'PY' import random, socket used=set() def free_port(protocols): for port in random.sample(range(20000, 60000), 2000): if port in used: continue sockets=[] try: for kind in protocols: sock=socket.socket(socket.AF_INET,kind) sock.bind(('127.0.0.1',port)) sockets.append(sock) used.add(port) return port except OSError: pass finally: for sock in sockets: sock.close() raise SystemExit('No free loopback ports found') def free_udp_range(width): for start in random.sample(range(25000, 55000-width), 2000): if any(port in used for port in range(start,start+width)): continue sockets=[] try: for port in range(start,start+width): sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(('127.0.0.1',port)) sockets.append(sock) used.update(range(start,start+width)) return start,start+width-1 except OSError: pass finally: for sock in sockets: sock.close() raise SystemExit('No free contiguous UDP relay ports found') print(free_port((socket.SOCK_STREAM,)), free_port((socket.SOCK_STREAM,)), free_port((socket.SOCK_STREAM,socket.SOCK_DGRAM)), *free_udp_range(20)) PY ) rustfs_access_key="acceptance$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')" rustfs_secret_key=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n') coturn_secret=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \\n') coturn_username=acceptance printf '%s' "$rustfs_access_key" > "$secret_dir/rustfs_access_key" printf '%s' "$rustfs_secret_key" > "$secret_dir/rustfs_secret_key" printf '%s' "$coturn_secret" > "$secret_dir/coturn_secret" printf 'acceptance-db-password-%s' "$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')" > "$secret_dir/db_password" for name in "${backup_scripts[@]}"; do cp "$repo_root/docker/scripts/$name" "$backup_scripts_dir/$name" done chmod 600 "$secret_dir"/* cat > "$env_file" < "$override_file" <<'EOF' services: turn-test: image: coturn/coturn:4.6 pull_policy: always profiles: [acceptance] entrypoint: ["/bin/sh", "-c"] command: - >- exec turnutils_uclient -v -y -X -m 1 -n 1 -p 3478 -W "$$COTURN_SECRET" -u "$$COTURN_USERNAME" coturn environment: COTURN_SECRET: ${COTURN_SECRET} COTURN_USERNAME: ${COTURN_USERNAME} depends_on: - coturn networks: heimdall-net: name: ${ACCEPTANCE_NETWORK} external: false EOF printf 'Disposable project: %s\nLocal images built: none\n' "$project" compose config --quiet compose config --format json | INSTALL_ROOT="$install_root" python3 -c ' import json, os, sys config = json.load(sys.stdin) root = os.environ["INSTALL_ROOT"] expected = { "rustfs_access_key": os.path.join(root, "optional/secrets/rustfs_access_key"), "rustfs_secret_key": os.path.join(root, "optional/secrets/rustfs_secret_key"), "coturn_secret": os.path.join(root, "optional/secrets/coturn_secret"), } actual = {name: config["secrets"][name]["file"] for name in expected} if actual != expected: raise SystemExit("Compose secret bind mounts do not resolve under the installer root") print("Verified RustFS and coturn secret bind mounts resolve under the installer root.") ' docker compose --project-directory "$install_root/optional" --env-file "$env_file" \ -f "$backup_compose" --project-name "${project}-backup" config --format json | BACKUP_PROJECT_DIRECTORY="$install_root/optional" python3 -c ' import json, os, sys config = json.load(sys.stdin) project_directory = os.environ["BACKUP_PROJECT_DIRECTORY"] expected_secret = os.path.join(project_directory, "secrets/db_password") expected_scripts = os.path.join(project_directory, "scripts") actual_secret = config["secrets"]["db_password"]["file"] scripts_mount = next((mount for mount in config["services"]["backup"]["volumes"] if mount.get("target") == "/scripts"), None) if actual_secret != expected_secret or scripts_mount is None or scripts_mount.get("source") != expected_scripts: raise SystemExit("Backup secret or script bind mounts do not resolve under optional/") print("Verified backup secret and scripts resolve under the installer optional directory.") ' compose up -d rustfs coturn base_url="http://127.0.0.1:$rustfs_api_port" deadline=$((SECONDS + 180)) until curl -fsS "$base_url/health" >/dev/null 2>&1; do if ((SECONDS >= deadline)); then echo 'RustFS health check timed out' >&2; exit 1; fi sleep 2 done printf 'RustFS /health: HTTP 200; API port %s and console port %s published.\n' \ "$rustfs_api_port" "$rustfs_console_port" RUSTFS_ACCESS_KEY="$rustfs_access_key" RUSTFS_SECRET_KEY="$rustfs_secret_key" \ RUSTFS_API_PORT="$rustfs_api_port" python3 - <<'PY' import datetime, hashlib, hmac, os, urllib.error, urllib.request access = os.environ['RUSTFS_ACCESS_KEY'] secret = os.environ['RUSTFS_SECRET_KEY'] host = '127.0.0.1:' + os.environ['RUSTFS_API_PORT'] path = '/acceptance' payload_hash = hashlib.sha256(b'').hexdigest() now = datetime.datetime.now(datetime.timezone.utc) amz_date = now.strftime('%Y%m%dT%H%M%SZ') date = now.strftime('%Y%m%d') canonical_headers = f'host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n' signed_headers = 'host;x-amz-content-sha256;x-amz-date' canonical_request = f'PUT\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}' scope = f'{date}/us-east-1/s3/aws4_request' to_sign = 'AWS4-HMAC-SHA256\n' + amz_date + '\n' + scope + '\n' + hashlib.sha256(canonical_request.encode()).hexdigest() def sign(key, value): return hmac.new(key, value.encode(), hashlib.sha256).digest() key = sign(('AWS4' + secret).encode(), date) key = sign(key, 'us-east-1') key = sign(key, 's3') key = sign(key, 'aws4_request') signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest() authorization = f'AWS4-HMAC-SHA256 Credential={access}/{scope}, SignedHeaders={signed_headers}, Signature={signature}' request = urllib.request.Request( f'http://{host}{path}', data=b'', method='PUT', headers={'Host': host, 'x-amz-content-sha256': payload_hash, 'x-amz-date': amz_date, 'Authorization': authorization}) try: with urllib.request.urlopen(request, timeout=15) as response: if response.status not in (200, 204): raise SystemExit('RustFS S3 bucket creation returned an unexpected status') except urllib.error.HTTPError as error: from xml.etree import ElementTree body = error.read() try: code = ElementTree.fromstring(body).findtext('{*}Code') except ElementTree.ParseError: code = None raise SystemExit(f'RustFS S3 authenticated bucket creation failed with HTTP {error.code} ({code or "unknown"})') PY printf 'RustFS S3 authenticated bucket creation: passed.\n' if ! compose --profile acceptance run --rm --no-deps turn-test > "$turn_log" 2>&1; then echo 'coturn authenticated TURN REST allocation did not succeed; sanitized client output:' >&2 sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=/Ig' "$turn_log" | tail -30 >&2 || true echo 'sanitized coturn server diagnostics:' >&2 compose logs --no-color coturn 2>&1 | rg -i 'error|fail|allocate|success|resolve|connect|auth|port|socket' | \ sed -E 's/(secret|password|token)[=: ]+[^ ]+/\1=/Ig' | tail -40 >&2 || true exit 1 fi printf 'coturn TURN REST authenticated allocation: passed via Compose network at listener port %s (relay UDP %s-%s).\n' \ "$coturn_port" "$relay_min" "$relay_max" for secret_value in "$rustfs_access_key" "$rustfs_secret_key" "$coturn_secret"; do if compose logs --no-color 2>/dev/null | grep -Fq -- "$secret_value"; then echo 'A generated service secret appeared in container logs.' >&2 exit 1 fi done printf 'Verified generated service secrets are absent from container logs.\n'