generate-jwt-secret.sh 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env bash
  2. # generate-jwt-secret.sh — Generate a BA_AUTHD_JWT_SECRET and append
  3. # it to .env (or print to stdout if --print).
  4. #
  5. # Usage:
  6. # scripts/generate-jwt-secret.sh # appends/writes .env
  7. # scripts/generate-jwt-secret.sh --print # prints to stdout only
  8. #
  9. # In docker-compose the secret is read via ${BA_AUTHD_JWT_SECRET:?}
  10. # (required), so a fresh checkout won't start until you run this.
  11. # The generated secret is 48 random bytes encoded as base64 (= 64
  12. # chars, well above the 32-byte minimum).
  13. #
  14. # Idempotent: if .env already has a non-empty value, the script
  15. # does nothing (use --force to overwrite).
  16. set -euo pipefail
  17. ENV_FILE="$(dirname "$0")/../.env"
  18. PRINT_ONLY=0
  19. FORCE=0
  20. for arg in "$@"; do
  21. case "$arg" in
  22. --print) PRINT_ONLY=1 ;;
  23. --force) FORCE=1 ;;
  24. -h|--help)
  25. echo "usage: $0 [--print] [--force]" >&2
  26. exit 0
  27. ;;
  28. esac
  29. done
  30. # Read existing value if .env exists
  31. existing=""
  32. if [[ -f "$ENV_FILE" ]]; then
  33. existing=$(grep -E '^BA_AUTHD_JWT_SECRET=' "$ENV_FILE" | tail -1 | cut -d= -f2- || true)
  34. fi
  35. if [[ -n "$existing" && $FORCE -eq 0 ]]; then
  36. if [[ $PRINT_ONLY -eq 1 ]]; then
  37. echo "$existing"
  38. else
  39. echo "BA_AUTHD_JWT_SECRET already set in $ENV_FILE (use --force to overwrite)"
  40. fi
  41. exit 0
  42. fi
  43. # 48 random bytes = 64 base64 chars. Plenty for HS256.
  44. new_secret=$(openssl rand -base64 48)
  45. if [[ $PRINT_ONLY -eq 1 ]]; then
  46. echo "$new_secret"
  47. exit 0
  48. fi
  49. # Write/append to .env
  50. if [[ ! -f "$ENV_FILE" ]]; then
  51. # Start from .env.example if present
  52. if [[ -f "${ENV_FILE}.example" ]]; then
  53. cp "${ENV_FILE}.example" "$ENV_FILE"
  54. else
  55. touch "$ENV_FILE"
  56. fi
  57. fi
  58. if grep -qE '^BA_AUTHD_JWT_SECRET=' "$ENV_FILE"; then
  59. # Replace existing line
  60. tmp=$(mktemp)
  61. grep -vE '^BA_AUTHD_JWT_SECRET=' "$ENV_FILE" > "$tmp"
  62. echo "BA_AUTHD_JWT_SECRET=$new_secret" >> "$tmp"
  63. mv "$tmp" "$ENV_FILE"
  64. echo "updated BA_AUTHD_JWT_SECRET in $ENV_FILE"
  65. else
  66. # Append
  67. echo "" >> "$ENV_FILE"
  68. echo "# Generated by scripts/generate-jwt-secret.sh on $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$ENV_FILE"
  69. echo "BA_AUTHD_JWT_SECRET=$new_secret" >> "$ENV_FILE"
  70. echo "appended BA_AUTHD_JWT_SECRET to $ENV_FILE"
  71. fi
  72. echo ""
  73. echo "next steps:"
  74. echo " 1. docker compose up -d authd # starts the IdP"
  75. echo " 2. bash scripts/m13a_smoke.sh # end-to-end smoke"