From c347d70ec9d856499578fdf059fcf44b189b254d Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 12 Nov 2026 06:02:33 +0100 Subject: [PATCH] fix(install): lire les secrets des services optionnels (#319) --- docker/docker-compose.coturn.yml | 31 ++- docker/docker-compose.rustfs.yml | 32 ++- skills/optional-server-services/SKILL.md | 8 +- skills/optional-server-services/acceptance.sh | 226 ++++++++++++++++++ 4 files changed, 285 insertions(+), 12 deletions(-) create mode 100755 skills/optional-server-services/acceptance.sh diff --git a/docker/docker-compose.coturn.yml b/docker/docker-compose.coturn.yml index c78bc09..a802070 100644 --- a/docker/docker-compose.coturn.yml +++ b/docker/docker-compose.coturn.yml @@ -3,6 +3,16 @@ services: coturn: image: coturn/coturn:4.6 pull_policy: always + # Local Compose secrets are read-only bind mounts and preserve the + # installer's 0600 owner-only permissions. Read the mounted file as a + # short-lived root initializer, write a private config into tmpfs, then + # run turnserver as nobody. The upstream binary does not exec with a + # reduced capability set; no-new-privileges still prevents elevation. + user: "0:0" + security_opt: + - no-new-privileges:true + tmpfs: + - /run/coturn:rw,noexec,nosuid,nodev,size=1m,mode=0700 ports: - "${COTURN_PORT:-3478}:3478/tcp" - "${COTURN_PORT:-3478}:3478/udp" @@ -10,13 +20,20 @@ services: entrypoint: ["/bin/sh", "-c"] command: - >- - exec turnserver -n --use-auth-secret - --static-auth-secret="$$(cat /run/secrets/coturn_secret)" - --realm=${COTURN_REALM:-heimdall.local} - --fingerprint --no-tlsv1 --no-tlsv1_1 --log-file=stdout - --no-cli --listening-port=3478 - --min-port=${COTURN_RELAY_PORT_MIN:-49160} - --max-port=${COTURN_RELAY_PORT_MAX:-49200} + set -eu; + umask 077; + printf 'use-auth-secret\nstatic-auth-secret=%s\nrealm=%s\nfingerprint\nno-tlsv1\nno-tlsv1_1\nlog-file=stdout\nno-cli\nlistening-port=3478\nmin-port=%s\nmax-port=%s\n' + "$$(cat /run/secrets/coturn_secret)" "${COTURN_REALM:-heimdall.local}" + "${COTURN_RELAY_PORT_MIN:-49160}" "${COTURN_RELAY_PORT_MAX:-49200}" + > /run/coturn/turnserver.conf; + printf 'pidfile=/run/coturn/turnserver.pid\n' >> /run/coturn/turnserver.conf; + if [ -n "$$COTURN_EXTERNAL_IP" ]; then + printf 'external-ip=%s\n' "$$COTURN_EXTERNAL_IP" >> /run/coturn/turnserver.conf; + fi; + chown 65534:65534 /run/coturn /run/coturn/turnserver.conf; + exec su -s /bin/sh -c 'exec /usr/bin/turnserver -c /run/coturn/turnserver.conf' nobody + environment: + COTURN_EXTERNAL_IP: ${COTURN_EXTERNAL_IP:-} secrets: - coturn_secret restart: unless-stopped diff --git a/docker/docker-compose.rustfs.yml b/docker/docker-compose.rustfs.yml index 20a860d..21c32fd 100644 --- a/docker/docker-compose.rustfs.yml +++ b/docker/docker-compose.rustfs.yml @@ -5,6 +5,34 @@ services: image: rustfs/rustfs:latest pull_policy: always restart: unless-stopped + # Compose file secrets are read-only bind mounts locally. The installer + # deliberately creates them mode 0600, owned by root; RustFS runs as UID + # 10001 and cannot read that source directly. A small root init copies the + # files into tmpfs, then drops privileges before starting the server. + user: "0:0" + read_only: true + cap_drop: + - ALL + cap_add: + - CHOWN + - DAC_OVERRIDE + - SETGID + - SETUID + security_opt: + - no-new-privileges:true + tmpfs: + - /run/rustfs-secrets:rw,noexec,nosuid,nodev,size=1m,mode=0700 + - /logs:rw,noexec,nosuid,nodev,size=16m,mode=1777 + - /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777 + entrypoint: ["/bin/sh", "-c"] + command: + - >- + set -eu; + umask 077; + cp /run/secrets/rustfs_access_key /run/rustfs-secrets/access_key; + cp /run/secrets/rustfs_secret_key /run/rustfs-secrets/secret_key; + chown 10001:10001 /run/rustfs-secrets /run/rustfs-secrets/access_key /run/rustfs-secrets/secret_key; + exec su -s /bin/sh -c 'exec /etc/rustfs/entrypoint.sh rustfs' rustfs ports: - "${RUSTFS_API_PORT:-9000}:9000" - "${RUSTFS_CONSOLE_PORT:-9001}:9001" @@ -13,8 +41,8 @@ services: RUSTFS_ADDRESS: 0.0.0.0:9000 RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001 RUSTFS_CONSOLE_ENABLE: "true" - RUSTFS_ACCESS_KEY_FILE: /run/secrets/rustfs_access_key - RUSTFS_SECRET_KEY_FILE: /run/secrets/rustfs_secret_key + RUSTFS_ACCESS_KEY_FILE: /run/rustfs-secrets/access_key + RUSTFS_SECRET_KEY_FILE: /run/rustfs-secrets/secret_key secrets: - rustfs_access_key - rustfs_secret_key diff --git a/skills/optional-server-services/SKILL.md b/skills/optional-server-services/SKILL.md index eca65ab..14b8a04 100644 --- a/skills/optional-server-services/SKILL.md +++ b/skills/optional-server-services/SKILL.md @@ -10,18 +10,20 @@ The Linux and Windows server installers run optional Compose files with the inst ## RustFS - Keep `rustfs_access_key` and `rustfs_secret_key` file paths aligned with the generated files from both installers. +- Installers create these bind-mounted secret files as owner-only (`0600`), which the official RustFS process (`10001:10001`) cannot read directly. Keep a short root initializer, copy the files into the service's private tmpfs, `chown` the copies to UID/GID 10001, then drop to the `rustfs` account before executing the upstream entrypoint. Keep the root filesystem read-only and provide tmpfs only for runtime paths that RustFS writes (`/logs`, `/tmp`, and its secret copies). - Verify Compose config from the install-root working directory and ensure Docker secrets are sourced from those files. - Keep the named data volume and shared `heimdall-net` behavior intact. ## coturn - Keep `coturn_secret` sourced from `./optional/secrets/coturn_secret`. -- coturn 4.6 does not support `--static-auth-secret-file`; read the mounted Docker secret in a shell entrypoint and pass it to `--static-auth-secret`. Do not print the value. +- coturn 4.6 does not support `--static-auth-secret-file`; read the mounted Docker secret in a short root initializer and write its configuration into private tmpfs. Do not print the value or pass it in the server process arguments. +- Local Compose secrets are owner-only bind mounts too. Start the initializer as root, make the temporary config readable by the image's `nobody` account, then `exec` `turnserver` as `nobody` with `no-new-privileges` enabled. Keep the root init transient; do not run the TURN daemon as root. - Use a shell entrypoint that executes `turnserver`, bridge networking, and explicit TCP/UDP listener and UDP relay port publications; the upstream image has a `turnadmin` entrypoint, and host networking cannot be combined with useful Compose port mappings. - Keep the published relay range identical to coturn's `--min-port`/`--max-port` options. Make listener and relay settings configurable with documented defaults. -- Set `COTURN_EXTERNAL_IP` only when NAT requires coturn to advertise an explicit public address. The operator must forward the listener and relay range through firewalls/NAT. +- Keep `COTURN_EXTERNAL_IP` optional; when set in the installer root `.env`, add Coturn's `external-ip` directive so it advertises the public address across NAT. The operator must forward the listener and relay range through firewalls/NAT. Do not set a guessed public address. - Do not claim public TURN reachability from a local container startup. It requires an external ICE/TURN client on a real network. ## Acceptance -Run both services in one uniquely named disposable Compose project using generated secrets and unique loopback listener ports. Use `docker compose --project-directory --env-file -f -p config` to prove the installer root resolves `optional/secrets/` correctly. Start RustFS and coturn; verify RustFS `/health` and S3 authentication and coturn startup plus a TURN REST authenticated allocation from a test client if available. State separately whether the real TURN allocation succeeded. Tear down only that project, verify its containers/volumes/networks are absent, and keep upstream images. No local images should be built by this recipe. +Run `skills/optional-server-services/acceptance.sh`. It creates a uniquely named disposable Compose project, generated owner-only secrets, an isolated install root, unique listener and relay ports, then validates Compose using that root. It verifies RustFS `/health`, signs a real S3 bucket-creation request with the generated keys, and runs `turnutils_uclient` inside the Compose network with TURN REST credentials. This proves local container-network allocation only; it does not prove external firewall/NAT reachability. The trap tears down only that project and verifies its containers, volumes, and networks are absent. The recipe builds no local images and retains upstream images. diff --git a/skills/optional-server-services/acceptance.sh b/skills/optional-server-services/acceptance.sh new file mode 100755 index 0000000..bf6a1ba --- /dev/null +++ b/skills/optional-server-services/acceptance.sh @@ -0,0 +1,226 @@ +#!/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" +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" +local_image_tags=() +mkdir -p "$secret_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" || cleanup_failed=1 + rmdir -- "$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" +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 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'