Files
matrix/scripts/rotate-secrets.sh
T
2026-04-05 23:30:22 -04:00

79 lines
2.4 KiB
Bash

#!/usr/bin/env bash
# =============================================================
# rotate-secrets.sh
# Regenerates TURN and LiveKit secrets in .env and restarts
# only the affected containers.
#
# Usage:
# bash scripts/rotate-secrets.sh # rotate all
# bash scripts/rotate-secrets.sh --turn # rotate TURN secret only
# bash scripts/rotate-secrets.sh --livekit # rotate LiveKit keys only
#
# ⚠️ Active calls and sessions WILL be dropped on rotation.
# Run during a maintenance window or when the server is idle.
# =============================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$SCRIPT_DIR/../.env"
if [ ! -f "$ENV_FILE" ]; then
echo "❌ .env not found at $ENV_FILE"
exit 1
fi
rotate_turn() {
echo "🔄 Rotating TURN secret..."
NEW_SECRET=$(openssl rand -hex 32)
sed -i "s|^STATIC_AUTH_SECRET=.*|STATIC_AUTH_SECRET=$NEW_SECRET|" "$ENV_FILE"
echo "✅ STATIC_AUTH_SECRET updated"
echo "🔁 Restarting coturn and tuwunel..."
docker compose --env-file "$ENV_FILE" -f "$SCRIPT_DIR/../docker-compose.yml" \
up -d --force-recreate coturn tuwunel
echo "✅ coturn and tuwunel restarted"
}
rotate_livekit() {
echo "🔄 Rotating LiveKit API credentials..."
NEW_KEY=$(openssl rand -hex 16)
NEW_SECRET=$(openssl rand -hex 32)
sed -i "s|^API_KEY=.*|API_KEY=$NEW_KEY|" "$ENV_FILE"
sed -i "s|^API_SECRET=.*|API_SECRET=$NEW_SECRET|" "$ENV_FILE"
echo "✅ API_KEY and API_SECRET updated"
echo "🔁 Restarting livekit and lk-jwt-service..."
docker compose --env-file "$ENV_FILE" -f "$SCRIPT_DIR/../docker-compose.yml" \
up -d --force-recreate livekit lk-jwt-service
echo "✅ livekit and lk-jwt-service restarted"
}
log_rotation() {
echo "📝 Logging rotation event..."
echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] $1" >> "$SCRIPT_DIR/../scripts/rotation.log"
}
case "${1:-all}" in
--turn)
rotate_turn
log_rotation "TURN secret rotated"
;;
--livekit)
rotate_livekit
log_rotation "LiveKit credentials rotated"
;;
all|--all)
rotate_turn
rotate_livekit
log_rotation "All secrets rotated"
;;
*)
echo "Usage: $0 [--turn | --livekit | --all]"
exit 1
;;
esac
echo ""
echo "🎉 Rotation complete. Previous secrets are gone — update any external clients if needed."