Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6406: fix(auth): fail fast in production on insecure JWT secret defaults (#7212)
BuXiuDN658b0b7d9f8b
diff --git a/.env.example b/.env.exampleindex 4aaca750a8..0a22624f90 100644--- a/.env.example+++ b/.env.example@@ -43,7 +43,15 @@ FRONTEND_ORIGIN=http://localhost:${FRONTEND_PORT}# proxy auth. Do not expose this endpoint through the public app/API ingress.# HTTP request metrics start accumulating only when this listener is enabled.# METRICS_ADDR=127.0.0.1:9090-JWT_SECRET=change-me-in-production+# REQUIRED. Signing key for auth JWTs, daemon JWTs, and avatar/attachment+# URL capability HMACs. Generate a strong random value:+# macOS/Linux: openssl rand -hex 32+# Windows (PowerShell): $b = New-Object byte[] 32; $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create(); $rng.GetBytes($b); $rng.Dispose(); -join ($b | ForEach-Object { $_.ToString('x2') })+# Leave empty ONLY for local non-Docker development (APP_ENV unset) — the+# server then uses a dev-only default and logs a warning. docker-compose+# refuses to start without a value, and production refuses to boot on the+# dev default or any known placeholder.+JWT_SECRET=# Derived by Makefile / local scripts from the backend port.# Set explicitly only when the daemon reaches the API through a different URL.# MULTICA_SERVER_URL=ws://localhost:8080/wsdiff --git a/SELF_HOSTING.md b/SELF_HOSTING.mdindex 6310c97d74..f8a3a61bab 100644--- a/SELF_HOSTING.md+++ b/SELF_HOSTING.md@@ -473,7 +473,9 @@ cd multicacp .env.example .env```-Edit `.env` — at minimum, change `JWT_SECRET`:+Edit `.env` — set `JWT_SECRET` (required): docker compose refuses to start without+it, and a production backend refuses to boot on the dev default or any known+placeholder.```bashJWT_SECRET=$(openssl rand -hex 32)diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex 57b4289f91..c9e94a342d 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -11,7 +11,7 @@ All configuration is done via environment variables. Copy `.env.example` as a st| Variable | Description | Example ||----------|-------------|---------|| `DATABASE_URL` | PostgreSQL connection string | `postgres://multica:multica@localhost:5432/multica?sslmode=disable` |-| `JWT_SECRET` | **Must change from default.** Secret key for signing JWT tokens. Use a long random string. | `openssl rand -hex 32` |+| `JWT_SECRET` | **Required — no safe default.** Secret key for signing JWT tokens. A production backend refuses to boot if this is empty or a known placeholder. Generate with `openssl rand -hex 32`. | `openssl rand -hex 32` || `FRONTEND_ORIGIN` | URL where the frontend is served (used for CORS) | `https://app.example.com` |### Database Pool Tuning (Optional)diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex ce6748019f..14356fe80d 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -23,7 +23,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.comさらにメールサービスを 1 つ選ぶ必要があります。選ばない場合、認証コードと招待はサーバーログに書き込まれるだけです。<Callout type="warning">-プロダクションでデフォルトの `JWT_SECRET` を使わないでください。`MULTICA_DEV_VERIFICATION_CODE` も設定しないでください。+`JWT_SECRET` は本番環境で必須です。`APP_ENV=production` の場合、値が空または既知のプレースホルダーだとバックエンドが起動を拒否します(`openssl rand -hex 32` で生成)。`MULTICA_DEV_VERIFICATION_CODE` も設定しないでください。</Callout>## API とデータベース@@ -34,7 +34,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `DATABASE_MAX_CONNS` | `25` | API プロセスあたりの最大データベース接続数 || `DATABASE_MIN_CONNS` | `5` | API プロセスが保持する最小接続数 || `PORT` | `8080` | API のリッスンポート |-| `JWT_SECRET` | 開発用の固定値 | ログイン JWT と一部の署名フローに使うシークレット |+| `JWT_SECRET` | 本番環境で必須 | ログイン JWT と一部の署名フローに使うシークレット。本番では空または既知のプレースホルダーだと起動を拒否 || `APP_ENV` | 空 | プロダクションでは `production` を設定 || `AUTH_TOKEN_TTL` | `720h`(30 日) | ブラウザ JWT と cookie の有効期間。Go duration または正の整数秒を受け付けます || `LOG_LEVEL` | アプリのデフォルト | ログレベル |diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex ab03ea5a98..c7d409b626 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -23,7 +23,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com이메일 서비스도 하나 선택해야 합니다. 설정하지 않으면 인증 코드와 초대가 서버 로그에만 기록됩니다.<Callout type="warning">-프로덕션 환경에서 기본 `JWT_SECRET`을 사용하거나 `MULTICA_DEV_VERIFICATION_CODE`를 설정하지 마세요.+`JWT_SECRET`은 프로덕션에서 필수입니다. `APP_ENV=production`일 때 비어 있거나 알려진 자리표시자 값이면 백엔드가 부팅을 거부합니다(`openssl rand -hex 32`로 생성). `MULTICA_DEV_VERIFICATION_CODE`도 설정하지 마세요.</Callout>## API와 데이터베이스@@ -34,7 +34,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `DATABASE_MAX_CONNS` | `25` | API 프로세스 하나의 최대 데이터베이스 연결 수 || `DATABASE_MIN_CONNS` | `5` | API 프로세스 하나가 유지하는 최소 연결 수 || `PORT` | `8080` | API listen port |-| `JWT_SECRET` | 개발용 고정값 | 로그인 JWT와 일부 서명 절차에서 사용하는 키 |+| `JWT_SECRET` | 프로덕션에서 필수 | 로그인 JWT와 일부 서명 절차에서 사용하는 키. 프로덕션에서는 비어 있거나 알려진 자리표시자 값으로 부팅 거부 || `APP_ENV` | 비어 있음 | 프로덕션 환경에서는 `production`으로 설정 || `AUTH_TOKEN_TTL` | `720h`(30일) | 브라우저 JWT와 cookie 유효 기간. Go duration 또는 양의 정수 초 허용 || `LOG_LEVEL` | 앱 기본값 | 로그 수준 |diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 8bd840ce56..561aca00d6 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -23,7 +23,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.comYou also need to pick an email service, otherwise verification codes and invitations are only written to the server log.<Callout type="warning">-Do not use the default `JWT_SECRET` in production, and do not set `MULTICA_DEV_VERIFICATION_CODE`.+`JWT_SECRET` is required in production: with `APP_ENV=production` the backend refuses to boot if it is empty or a known placeholder (generate one with `openssl rand -hex 32`). Do not set `MULTICA_DEV_VERIFICATION_CODE`.</Callout>## API and database@@ -34,7 +34,7 @@ Do not use the default `JWT_SECRET` in production, and do not set `MULTICA_DEV_V| `DATABASE_MAX_CONNS` | `25` | Maximum database connections per API process || `DATABASE_MIN_CONNS` | `5` | Minimum connections each API process keeps || `PORT` | `8080` | API listen port |-| `JWT_SECRET` | fixed development value | Secret for sign-in JWTs and some signing flows |+| `JWT_SECRET` | required in production | Secret for sign-in JWTs and some signing flows; production refuses to boot on empty or known placeholders || `APP_ENV` | empty | Set to `production` in production || `AUTH_TOKEN_TTL` | `720h` (30 days) | Lifetime of browser JWTs and cookies; accepts a Go duration or a positive integer of seconds || `LOG_LEVEL` | application default | Log level |diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex e961f8b608..f178d2aa76 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -23,7 +23,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com还需要选择一种邮件服务,否则验证码和邀请只会写入服务端日志。<Callout type="warning">-不要在生产环境使用默认的 `JWT_SECRET`,也不要设置 `MULTICA_DEV_VERIFICATION_CODE`。+`JWT_SECRET` 在生产环境为必填:当 `APP_ENV=production` 时,后端会在密钥为空或等于已知占位值时拒绝启动(用 `openssl rand -hex 32` 生成)。也不要在生产环境设置 `MULTICA_DEV_VERIFICATION_CODE`。</Callout>## API 与数据库@@ -34,7 +34,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `DATABASE_MAX_CONNS` | `25` | 单个 API 进程的最大数据库连接数 || `DATABASE_MIN_CONNS` | `5` | 单个 API 进程保留的最小连接数 || `PORT` | `8080` | API 监听端口 |-| `JWT_SECRET` | 开发用固定值 | 登录 JWT、部分签名流程使用的密钥 |+| `JWT_SECRET` | 生产环境必填 | 登录 JWT、部分签名流程使用的密钥;生产环境对空值或已知占位值拒绝启动 || `APP_ENV` | 空 | 生产环境设为 `production` || `AUTH_TOKEN_TTL` | `720h`(30 天) | 浏览器 JWT 与 cookie 有效期;接受 Go duration 或正整数秒数 || `LOG_LEVEL` | 应用默认 | 日志级别 |diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 99cd7b03d5..2f216c905c 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -5,12 +5,12 @@# TLS and forwards to 127.0.0.1:8080 (backend) and 127.0.0.1:3000 (frontend).# Do NOT change these bindings to 0.0.0.0 — Docker bypasses host firewalls# (UFW/iptables) by default, so the raw ports would be exposed to the internet-# with the default JWT_SECRET and Postgres credentials. See:+# while any deployment credentials remain weak. See:# apps/docs/content/docs/self-host-quickstart.mdx## Usage:# cp .env.example .env-# # Edit .env — change JWT_SECRET at minimum+# # Edit .env — generate JWT_SECRET with `openssl rand -hex 32` (required)# docker compose -f docker-compose.selfhost.yml up -d## Frontend: http://localhost:${FRONTEND_PORT:-3000}@@ -65,7 +65,7 @@ services:DATABASE_URL: postgres://${POSTGRES_USER:-multica}:${POSTGRES_PASSWORD:-multica}@postgres:5432/${POSTGRES_DB:-multica}?sslmode=disablePORT: "8080"METRICS_ADDR: ${METRICS_ADDR:-}- JWT_SECRET: ${JWT_SECRET:-change-me-in-production}+ JWT_SECRET: ${JWT_SECRET:?JWT_SECRET must be set to a strong random value — generate one with 'openssl rand -hex 32'}FRONTEND_ORIGIN: ${FRONTEND_ORIGIN:-http://localhost:3000}CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}RESEND_API_KEY: ${RESEND_API_KEY:-}diff --git a/scripts/selfhost-config.test.sh b/scripts/selfhost-config.test.shindex 7b4fe7159f..74e4f0458a 100755--- a/scripts/selfhost-config.test.sh+++ b/scripts/selfhost-config.test.sh@@ -4,6 +4,14 @@ set -euo pipefailROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"cd "$ROOT_DIR"+# docker-compose.selfhost.yml requires JWT_SECRET (${JWT_SECRET:?...}) and+# .env.example ships an empty value. Direct `docker compose config` calls in+# this script let the calling environment outrank the env file, so one+# throwaway export covers them. The make-driven recipes below additionally+# include .env and bare-`export` it to the recipe environment, clobbering+# this value, so run_recipe seeds it into the recipe .env as well.+export JWT_SECRET=test-secret-for-config-test+require_config() {local config=$1local expected=$2@@ -258,6 +266,13 @@ run_recipe() {local target=$1 env_mutation=$2 shell_env=$3 make_args=$4cp "$recipe_dir/.env.example" "$recipe_dir/.env"+ # The Makefile includes .env and bare-`export`s every variable to the+ # recipe environment, which clobbers this script's JWT_SECRET with the+ # empty value .env.example ships; docker-compose.selfhost.yml now refuses+ # to interpolate an empty JWT_SECRET. Seed the throwaway value into the+ # recipe .env so make, the stub, and Compose all see a usable secret.+ sed "s/^JWT_SECRET=.*/JWT_SECRET=$JWT_SECRET/" "$recipe_dir/.env" >"$recipe_dir/.env.tmp"+ mv "$recipe_dir/.env.tmp" "$recipe_dir/.env"if [ -n "$env_mutation" ]; thensed "$env_mutation" "$recipe_dir/.env" >"$recipe_dir/.env.tmp"mv "$recipe_dir/.env.tmp" "$recipe_dir/.env"diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex ef2b4e7854..731022d2bb 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -14,6 +14,7 @@ import ("github.com/jackc/pgx/v5/pgxpool""github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler"@@ -239,12 +240,33 @@ func backgroundServices(h *handler.Handler) (*service.TaskService, *service.Autoreturn h.TaskService, h.AutopilotService}+// jwtSecretBootError returns a non-nil error when the combination of+// JWT_SECRET and APP_ENV is unsafe to boot with: production must never run+// on an empty or publicly-known default secret (auth.ValidateJWTSecret).+// Non-production keeps the historical dev fallback (see auth.JWTSecret)+// and only warns.+func jwtSecretBootError(jwtSecret, appEnv string) error {+ isProduction := strings.EqualFold(strings.TrimSpace(appEnv), "production")+ if !isProduction {+ return nil+ }+ return auth.ValidateJWTSecret(jwtSecret)+}+func main() {logger.Init()// Warn about missing configuration+ if err := jwtSecretBootError(os.Getenv("JWT_SECRET"), os.Getenv("APP_ENV")); err != nil {+ slog.Error(+ "refusing to start: "+err.Error()++ "; generate a strong secret with `openssl rand -hex 32` and set JWT_SECRET (see .env.example)",+ "app_env", os.Getenv("APP_ENV"),+ )+ os.Exit(1)+ }if os.Getenv("JWT_SECRET") == "" {- slog.Warn("JWT_SECRET is not set — using insecure default. Set JWT_SECRET for production use.")+ slog.Warn("JWT_SECRET is not set — using insecure dev default (allowed only because APP_ENV is not production).")}if os.Getenv("RESEND_API_KEY") == "" && strings.TrimSpace(os.Getenv("SMTP_HOST")) == "" {slog.Warn("no email backend configured (RESEND_API_KEY and SMTP_HOST both empty) — verification codes will be printed to the log instead of emailed.")diff --git a/server/cmd/server/main_test.go b/server/cmd/server/main_test.goindex 0ca254994b..f1829506de 100644--- a/server/cmd/server/main_test.go+++ b/server/cmd/server/main_test.go@@ -413,3 +413,33 @@ func TestHoldBeforeShutdownDisabled(t *testing.T) {t.Fatal("disabled hold should not consume another signal")}}++func TestJWTSecretBootError(t *testing.T) {+ strong := "a1b2c3d4e5f60718293a4b5c6d7e8f9012a3b4c5d6e7f8091a2b3c4d5e6f70819"+ tests := []struct {+ name string+ jwtSecret string+ appEnv string+ wantErr bool+ }{+ {"production_with_empty_secret_is_rejected", "", "production", true},+ {"production_with_code_default_is_rejected", "multica-dev-secret-change-in-production", "production", true},+ {"production_with_compose_default_is_rejected", "change-me-in-production", "production", true},+ {"production_with_uppercase_env_is_rejected", "change-me-in-production", "PRODUCTION", true},+ {"production_with_whitespace_env_is_rejected", "change-me-in-production", " production ", true},+ {"production_with_strong_secret_is_accepted", strong, "production", false},+ {"non_production_with_empty_secret_is_allowed", "", "", false},+ {"non_production_with_weak_secret_is_allowed", "change-me-in-production", "development", false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := jwtSecretBootError(tt.jwtSecret, tt.appEnv)+ if tt.wantErr && err == nil {+ t.Fatalf("jwtSecretBootError(%q, %q) = nil, want error", tt.jwtSecret, tt.appEnv)+ }+ if !tt.wantErr && err != nil {+ t.Fatalf("jwtSecretBootError(%q, %q) = %v, want nil", tt.jwtSecret, tt.appEnv, err)+ }+ })+ }+}diff --git a/server/internal/auth/jwt.go b/server/internal/auth/jwt.goindex 9f02bc7f6b..c77f033e99 100644--- a/server/internal/auth/jwt.go+++ b/server/internal/auth/jwt.go@@ -4,8 +4,10 @@ import ("crypto/rand""crypto/sha256""encoding/hex"+ "errors""fmt""os"+ "strings""sync")@@ -28,6 +30,33 @@ func JWTSecret() []byte {return jwtSecret}+// ErrInsecureJWTSecret is returned by ValidateJWTSecret when the configured+// secret is empty or one of the publicly known defaults shipped in the+// repo/config templates. Anyone can forge HS256 signatures with these+// values, so a production server must refuse to boot on them.+var ErrInsecureJWTSecret = errors.New("JWT_SECRET is empty or a known insecure default")++// insecureJWTSecrets is the denylist of values that must never reach a+// production deployment. The empty string is covered by JWTSecret()'s+// dev-only fallback; "change-me-in-production" was historically shipped by+// docker-compose.selfhost.yml and .env.example. Add any placeholder a template+// ships with to this list before publishing it.+var insecureJWTSecrets = map[string]struct{}{+ "": {},+ defaultJWTSecret: {},+ "change-me-in-production": {},+}++// ValidateJWTSecret reports whether secret is safe to sign production+// tokens with. It is deliberately cheap and side-effect free so the boot+// path and tests can call it directly.+func ValidateJWTSecret(secret string) error {+ if _, weak := insecureJWTSecrets[strings.TrimSpace(secret)]; weak {+ return ErrInsecureJWTSecret+ }+ return nil+}+// GeneratePATToken creates a new personal access token: "mul_" + 40 random hex chars.func GeneratePATToken() (string, error) {b := make([]byte, 20) // 20 bytes = 40 hex charsdiff --git a/server/internal/auth/jwt_secret_test.go b/server/internal/auth/jwt_secret_test.gonew file mode 100644index 0000000000..5580d69460--- /dev/null+++ b/server/internal/auth/jwt_secret_test.go@@ -0,0 +1,36 @@+package auth++import (+ "strings"+ "testing"+)++func TestValidateJWTSecret(t *testing.T) {+ strong := "a1b2c3d4e5f60718293a4b5c6d7e8f9012a3b4c5d6e7f8091a2b3c4d5e6f70819"+ tests := []struct {+ name string+ secret string+ wantErr bool+ }{+ {"empty_is_rejected", "", true},+ {"code_default_is_rejected", defaultJWTSecret, true},+ {"compose_template_default_is_rejected", "change-me-in-production", true},+ {"whitespace_wrapped_weak_value_is_rejected", " change-me-in-production \n", true},+ {"strong_random_value_is_accepted", strong, false},+ {"short_weak_value_not_in_denylist_is_accepted", "abc", false},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := ValidateJWTSecret(tt.secret)+ if tt.wantErr && err == nil {+ t.Fatalf("ValidateJWTSecret(%q) = nil, want error", tt.secret)+ }+ if !tt.wantErr && err != nil {+ t.Fatalf("ValidateJWTSecret(%q) = %v, want nil", tt.secret, err)+ }+ if tt.wantErr && !strings.Contains(err.Error(), "JWT_SECRET") {+ t.Fatalf("ValidateJWTSecret(%q) error = %q, want actionable JWT_SECRET message", tt.secret, err)+ }+ })+ }+}