Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8136: feat(server): restrict workspace creation to listed emails (self-host) (#9411)

Multica Eve7ebaf00e7c48
diff --git a/.env.example b/.env.example
index 078267fd00..c28585b20e 100644
--- a/.env.example
+++ b/.env.example
@@ -694,6 +694,16 @@ ALLOWED_EMAILS=
# so toggling requires a backend restart but not a frontend rebuild.
DISABLE_WORKSPACE_CREATION=
+# Optional: only these exact email addresses may create workspaces
+# (comma-separated, case-insensitive) (#9400). Leave empty to let every
+# signed-in user create workspaces. DISABLE_WORKSPACE_CREATION=true still
+# blocks everyone, including listed users. Other users can sign in and join
+# workspaces they are invited to, but POST /api/workspaces returns 403 for
+# them. The UI does not hide the "Create workspace" entry for them; the
+# server error is shown instead. Listing a user grants no access to other
+# workspaces. Requires a backend restart.
+WORKSPACE_CREATION_ALLOWED_EMAILS=
+
# ==================== Anonymous Self-host Telemetry ====================
# The API server sends one first-party, deployment-level anonymous snapshot per
# UTC day to https://telemetry.multica.ai. It contains the release version,
diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md
index 8d666ac846..636d74d307 100644
--- a/SELF_HOSTING.md
+++ b/SELF_HOSTING.md
@@ -102,7 +102,7 @@ Open http://localhost:3000 in your browser. The Docker self-host stack defaults
- **Without email configured:** the verification code is generated server-side and printed to the backend container logs (look for `[DEV] Verification code for ...:`). Useful for one-off testing on a single machine.
- **Deterministic local/private testing:** set `APP_ENV=development` and `MULTICA_DEV_VERIFICATION_CODE=888888` in `.env`, then restart the backend. This fixed code is ignored when `APP_ENV=production`.
-Changes to `ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, and `GOOGLE_CLIENT_ID` also take effect after restarting the backend / compose stack. The web UI reads all three from `/api/config` at runtime, so no web rebuild is needed. See [Advanced Configuration → Signup Controls](SELF_HOSTING_ADVANCED.md#signup-controls-optional) for the recommended sequence to lock down workspace creation.
+Changes to `ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, `WORKSPACE_CREATION_ALLOWED_EMAILS`, and `GOOGLE_CLIENT_ID` also take effect after restarting the backend / compose stack. The web UI reads `ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, and `GOOGLE_CLIENT_ID` from `/api/config` at runtime, so no web rebuild is needed. `WORKSPACE_CREATION_ALLOWED_EMAILS` is read only by the backend and is not exposed through `/api/config`. See [Advanced Configuration → Signup Controls](SELF_HOSTING_ADVANCED.md#signup-controls-optional) for the recommended sequence to lock down workspace creation, or to limit it to selected users.
> **Warning:** do **not** set `MULTICA_DEV_VERIFICATION_CODE` on a publicly reachable instance — anyone who knows an email address can then log in with that fixed code.
@@ -312,7 +312,7 @@ The chart defaults to `APP_ENV=production` (set in `values.yaml` under `backend.
kubectl -n multica rollout restart deploy/multica-backend
```
-`ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, and `GOOGLE_CLIENT_ID` likewise live under `backend.config.*` in `values.yaml` (as `allowSignup`, `disableWorkspaceCreation`, and `googleClientId`). After `helm upgrade`, the backend pod will roll automatically because the ConfigMap hash changes; the web UI reads all three from `/api/config` at runtime, so no web rebuild is needed.
+`ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, `WORKSPACE_CREATION_ALLOWED_EMAILS`, and `GOOGLE_CLIENT_ID` likewise live under `backend.config.*` in `values.yaml` (as `allowSignup`, `disableWorkspaceCreation`, `workspaceCreationAllowedEmails`, and `googleClientId`). After `helm upgrade`, the backend pod will roll automatically because the ConfigMap hash changes; the web UI reads `allowSignup`, `disableWorkspaceCreation`, and `googleClientId` from `/api/config` at runtime, so no web rebuild is needed. `workspaceCreationAllowedEmails` is read only by the backend and is not exposed through `/api/config`.
> **Warning:** do **not** set `MULTICA_DEV_VERIFICATION_CODE` on a publicly reachable instance — anyone who knows an email address can then log in with that fixed code.
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index fdfe72519e..f84f01dbbc 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -75,6 +75,7 @@ Changes take effect after restarting the backend / compose stack. The web UI rea
| `ALLOWED_EMAIL_DOMAINS` | Optional comma-separated allowlist of email domains |
| `ALLOWED_EMAILS` | Optional comma-separated allowlist of exact email addresses |
| `DISABLE_WORKSPACE_CREATION` | Set to `true` to make `POST /api/workspaces` return 403 for every caller — users can only join workspaces they were invited to |
+| `WORKSPACE_CREATION_ALLOWED_EMAILS` | Optional comma-separated list of exact email addresses allowed to create workspaces. When set, everyone else gets 403 from `POST /api/workspaces`. Ignored when `DISABLE_WORKSPACE_CREATION=true` |
Changes take effect after restarting the backend / compose stack. The web UI reads `ALLOW_SIGNUP` and `DISABLE_WORKSPACE_CREATION` from `/api/config` at runtime, so no web rebuild is needed.
@@ -87,6 +88,27 @@ Changes take effect after restarting the backend / compose stack. The web UI rea
3. Set `DISABLE_WORKSPACE_CREATION=true` and restart the backend. Optionally set `ALLOW_SIGNUP=false` at the same time if you also want to restrict new account creation.
4. Going forward, additional users join via invitation only — the "Create workspace" affordance is hidden in the UI and any direct API call returns 403.
+#### Letting only selected users create workspaces
+
+If a few people (for example platform or team leads) need to keep creating workspaces while everyone else only joins by invitation, set `WORKSPACE_CREATION_ALLOWED_EMAILS` instead of toggling `DISABLE_WORKSPACE_CREATION` back and forth:
+
+```dotenv
+```
+
+`POST /api/workspaces` is evaluated in this order:
+
+1. `DISABLE_WORKSPACE_CREATION=true` → 403 for everyone, including listed users.
+2. `WORKSPACE_CREATION_ALLOWED_EMAILS` empty → allowed for every signed-in user (default).
+3. The caller's account email matches an entry (case-insensitive) → allowed.
+4. Otherwise → 403.
+
+Things to know:
+
+- The list only controls who can create a workspace. It is not an instance-admin role: listed users get no visibility into, or management rights over, workspaces they are not a member of. Keeping new workspaces visible to the people who run the instance still depends on inviting them.
+- The UI does not hide the "Create workspace" entry points for unlisted users. They see the server's error message when they try.
+- This list is separate from `ALLOWED_EMAILS` / `ALLOWED_EMAIL_DOMAINS`, which only control who can sign up.
+
> Note: setting `ALLOW_SIGNUP=false` enables invite-only account creation. A new user with a live pending workspace invitation can create an account with the invited email; users without an allowlist match or a valid invitation remain blocked. Invitations also permit emails outside configured allowlists when `ALLOW_SIGNUP=true`. Revocation does not delete accounts already created using an invitation or prevent those accounts from signing in. Combine this with `DISABLE_WORKSPACE_CREATION=true` when invitees must join an existing workspace instead of creating their own.
### File Storage (Optional)
diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdx
index 55e6796ad2..932753ebbb 100644
--- a/apps/docs/content/docs/environment-variables.fr.mdx
+++ b/apps/docs/content/docs/environment-variables.fr.mdx
@@ -113,6 +113,7 @@ SMTP est prioritaire sur Resend dès que `SMTP_HOST` n'est pas vide.
| `ALLOWED_EMAILS` | vide | Adresses e-mail complètes autorisées à s'inscrire, séparées par des virgules |
| `ALLOWED_EMAIL_DOMAINS` | vide | Domaines e-mail autorisés à s'inscrire, séparés par des virgules |
| `DISABLE_WORKSPACE_CREATION` | `false` | Empêche tous les utilisateurs de créer des espaces de travail ; aucune exception pour les propriétaires ou les administrateurs |
+| `WORKSPACE_CREATION_ALLOWED_EMAILS` | vide | Adresses e-mail complètes autorisées à créer des espaces de travail, séparées par des virgules. Si défini, les autres utilisateurs reçoivent une 403. `DISABLE_WORKSPACE_CREATION=true` est prioritaire. N'accorde aucun accès aux autres espaces de travail |
| `MULTICA_DEV_VERIFICATION_CODE` | vide | Code de test fixe à 6 chiffres pour les environnements hors production |
Pour l'ordre exact d'évaluation des listes d'autorisation, consultez [Connexion et inscription](/auth-setup#restrictions-dinscription).
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 612e4cddf2..dd214b58a8 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -113,6 +113,7 @@ primary とレプリカの接続上限は独立しています。全 API プロ
| `ALLOWED_EMAILS` | 空 | 登録を許可する完全なメールアドレス。カンマ区切り |
| `ALLOWED_EMAIL_DOMAINS` | 空 | 登録を許可するメールドメイン。カンマ区切り |
| `DISABLE_WORKSPACE_CREATION` | `false` | すべてのユーザーのワークスペース新規作成を禁止。owner/admin の例外はありません |
+| `WORKSPACE_CREATION_ALLOWED_EMAILS` | 空 | ワークスペースの新規作成を許可するメールアドレス(完全一致、カンマ区切り)。設定すると、それ以外のユーザーには 403 を返します。`DISABLE_WORKSPACE_CREATION=true` が優先されます。他のワークスペースへのアクセス権は付与しません |
| `MULTICA_DEV_VERIFICATION_CODE` | 空 | 非 production 環境で使う固定 6 桁のテスト認証コード |
allowlist の正確な判定順序は[ログインとサインアップ](/auth-setup#サインアップ制限)を参照してください。
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index cd74f01dbb..5c7cc7f718 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -113,6 +113,7 @@ primary와 복제본의 연결 한도는 서로 독립적입니다. 모든 API
| `ALLOWED_EMAILS` | 비어 있음 | 가입을 허용할 전체 이메일 주소, 쉼표로 구분 |
| `ALLOWED_EMAIL_DOMAINS` | 비어 있음 | 가입을 허용할 이메일 도메인, 쉼표로 구분 |
| `DISABLE_WORKSPACE_CREATION` | `false` | 모든 사용자의 새 워크스페이스 생성을 금지. owner/admin 예외 없음 |
+| `WORKSPACE_CREATION_ALLOWED_EMAILS` | 비어 있음 | 워크스페이스 생성을 허용할 전체 이메일 주소, 쉼표로 구분. 설정하면 그 외 사용자는 403을 받습니다. `DISABLE_WORKSPACE_CREATION=true`가 우선합니다. 다른 워크스페이스에 대한 접근 권한은 부여하지 않습니다 |
| `MULTICA_DEV_VERIFICATION_CODE` | 비어 있음 | production이 아닌 환경에서 사용하는 고정 6자리 테스트 인증 코드 |
allowlist의 정확한 판단 순서는 [로그인과 가입](/auth-setup#가입-범위-제어)을 참고하세요.
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 12b28e6fdb..9e21828617 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -113,6 +113,7 @@ SMTP takes priority over Resend whenever `SMTP_HOST` is non-empty.
| `ALLOWED_EMAILS` | empty | Full email addresses allowed to sign up, comma-separated |
| `ALLOWED_EMAIL_DOMAINS` | empty | Email domains allowed to sign up, comma-separated |
| `DISABLE_WORKSPACE_CREATION` | `false` | Blocks all users from creating workspaces; no owner/admin exception |
+| `WORKSPACE_CREATION_ALLOWED_EMAILS` | empty | Full email addresses allowed to create workspaces, comma-separated. When set, all other users get 403. `DISABLE_WORKSPACE_CREATION=true` takes precedence. Grants no access to other workspaces |
| `MULTICA_DEV_VERIFICATION_CODE` | empty | Fixed 6-digit test code for non-production environments |
For the exact allowlist evaluation order, see [Sign-in and signup](/auth-setup#signup-restrictions).
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 961966948e..d8428acb1b 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -113,6 +113,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `ALLOWED_EMAILS` | 空 | 允许注册的完整邮箱,逗号分隔 |
| `ALLOWED_EMAIL_DOMAINS` | 空 | 允许注册的邮箱域名,逗号分隔 |
| `DISABLE_WORKSPACE_CREATION` | `false` | 禁止所有用户新建工作区;没有 owner/admin 例外 |
+| `WORKSPACE_CREATION_ALLOWED_EMAILS` | 空 | 允许新建工作区的完整邮箱地址,逗号分隔。设置后其他用户新建会返回 403。`DISABLE_WORKSPACE_CREATION=true` 优先。不授予访问其他工作区的权限 |
| `MULTICA_DEV_VERIFICATION_CODE` | 空 | 非 production 环境使用的固定 6 位测试验证码 |
白名单的准确判断顺序见[登录与注册](/auth-setup#注册范围控制)。
diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yaml
index a37a49c63a..9912863cb0 100644
--- a/deploy/helm/multica/templates/configmap.yaml
+++ b/deploy/helm/multica/templates/configmap.yaml
@@ -21,6 +21,7 @@ data:
ALLOWED_EMAILS: {{ .Values.backend.config.allowedEmails | quote }}
ALLOWED_EMAIL_DOMAINS: {{ .Values.backend.config.allowedEmailDomains | quote }}
DISABLE_WORKSPACE_CREATION: {{ .Values.backend.config.disableWorkspaceCreation | quote }}
+ WORKSPACE_CREATION_ALLOWED_EMAILS: {{ .Values.backend.config.workspaceCreationAllowedEmails | quote }}
DO_NOT_TRACK: {{ .Values.backend.config.doNotTrack | quote }}
MULTICA_VCS_INTEGRATION_ENABLED: {{ .Values.backend.config.vcsIntegrationEnabled | quote }}
MULTICA_CLOUD_URL: {{ .Values.backend.config.cloud.url | quote }}
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index 4043489dab..2e6c387154 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -148,6 +148,10 @@ backend:
# every caller. Bootstrap the workspace with this false, then flip to
# true so users can only join via invitation.
disableWorkspaceCreation: false
+ # Self-host allowlist (#9400): comma-separated exact emails allowed to
+ # create workspaces. Empty = every signed-in user may create one.
+ # disableWorkspaceCreation=true still blocks everyone.
+ workspaceCreationAllowedEmails: ""
# Set to "1" or "true" to disable first-party anonymous self-host
# telemetry collection and delivery.
doNotTrack: ""
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index c0b3db2880..cedd8d6aff 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -111,6 +111,7 @@ services:
ALLOWED_EMAILS: ${ALLOWED_EMAILS:-}
ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}
DISABLE_WORKSPACE_CREATION: ${DISABLE_WORKSPACE_CREATION:-}
+ WORKSPACE_CREATION_ALLOWED_EMAILS: ${WORKSPACE_CREATION_ALLOWED_EMAILS:-}
DO_NOT_TRACK: ${DO_NOT_TRACK:-}
# Managed Cloud stays off for self-hosting. All managed Cloud clients use
# this single URL when it is configured.
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index d28ec1e56c..812103a599 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -427,27 +427,28 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
origins := allowedOrigins()
signupConfig := handler.Config{
- AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",
- AllowedEmails: splitAndTrim(os.Getenv("ALLOWED_EMAILS")),
- AllowedEmailDomains: splitAndTrim(os.Getenv("ALLOWED_EMAIL_DOMAINS")),
- DisableWorkspaceCreation: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",
- VCSIntegrationEnabled: os.Getenv("MULTICA_VCS_INTEGRATION_ENABLED") == "true",
- PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),
- AppURL: appURLFromEnv(),
- TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),
- CloudURL: strings.TrimSpace(os.Getenv("MULTICA_CLOUD_URL")),
- CloudTimeout: 35 * time.Second,
- AttachmentDownloadMode: os.Getenv("ATTACHMENT_DOWNLOAD_MODE"),
- AttachmentDownloadURLTTL: envDuration("ATTACHMENT_DOWNLOAD_URL_TTL", 30*time.Minute),
- AttachmentFrameAncestors: origins,
- PluginSurfaceOrigin: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PLUGIN_SURFACE_ORIGIN")), "/"),
- LLMAPIKey: strings.TrimSpace(os.Getenv("MULTICA_LLM_API_KEY")),
- LLMBaseURL: strings.TrimSpace(os.Getenv("MULTICA_LLM_BASE_URL")),
- LLMDefaultModel: strings.TrimSpace(os.Getenv("MULTICA_LLM_DEFAULT_MODEL")),
- LLMMaxRetries: opts.LLMMaxRetries,
- LLMDisableThinking: opts.LLMDisableThinking,
- ServerVersion: normalizeServerVersion(version),
- GitExtraCACerts: gitca.Load(slog.Default()),
+ AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",
+ AllowedEmails: splitAndTrim(os.Getenv("ALLOWED_EMAILS")),
+ AllowedEmailDomains: splitAndTrim(os.Getenv("ALLOWED_EMAIL_DOMAINS")),
+ DisableWorkspaceCreation: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",
+ WorkspaceCreationAllowedEmails: splitAndTrim(os.Getenv("WORKSPACE_CREATION_ALLOWED_EMAILS")),
+ VCSIntegrationEnabled: os.Getenv("MULTICA_VCS_INTEGRATION_ENABLED") == "true",
+ PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),
+ AppURL: appURLFromEnv(),
+ TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),
+ CloudURL: strings.TrimSpace(os.Getenv("MULTICA_CLOUD_URL")),
+ CloudTimeout: 35 * time.Second,
+ AttachmentDownloadMode: os.Getenv("ATTACHMENT_DOWNLOAD_MODE"),
+ AttachmentDownloadURLTTL: envDuration("ATTACHMENT_DOWNLOAD_URL_TTL", 30*time.Minute),
+ AttachmentFrameAncestors: origins,
+ PluginSurfaceOrigin: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PLUGIN_SURFACE_ORIGIN")), "/"),
+ LLMAPIKey: strings.TrimSpace(os.Getenv("MULTICA_LLM_API_KEY")),
+ LLMBaseURL: strings.TrimSpace(os.Getenv("MULTICA_LLM_BASE_URL")),
+ LLMDefaultModel: strings.TrimSpace(os.Getenv("MULTICA_LLM_DEFAULT_MODEL")),
+ LLMMaxRetries: opts.LLMMaxRetries,
+ LLMDisableThinking: opts.LLMDisableThinking,
+ ServerVersion: normalizeServerVersion(version),
+ GitExtraCACerts: gitca.Load(slog.Default()),
}
h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)
invitationRateLimits := handler.DefaultInvitationRateLimits()
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 1987866ad9..308ef074d5 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -76,6 +76,13 @@ type Config struct {
// invitation only. The public /api/config endpoint mirrors this flag so
// the UI can hide every "Create workspace" affordance — see #3433.
DisableWorkspaceCreation bool
+ // WorkspaceCreationAllowedEmails, when non-empty, restricts
+ // POST /api/workspaces to callers whose account email matches one of
+ // the entries (case-insensitive). Empty means every signed-in user may
+ // create workspaces. DisableWorkspaceCreation takes precedence. This only
+ // decides who may create a workspace; it grants no cross-workspace
+ // visibility or admin rights (#9400).
+ WorkspaceCreationAllowedEmails []string
// VCSIntegrationEnabled gates the self-hosted Git provider integration
// (Forgejo / Gitea / GitLab) at the deployment level, independent of whether
// MULTICA_VCS_SECRET_KEY is set. It is the product boundary: the feature is
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index ff5db1cdf8..d0098e7b14 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -13,6 +13,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
@@ -215,6 +216,25 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
return
}
+ // Self-host allowlist (#9400): when WORKSPACE_CREATION_ALLOWED_EMAILS is
+ // set, only those accounts may create workspaces. The UI does not hide
+ // the entry points for other users; this 403 is the enforcement point.
+ if len(h.cfg.WorkspaceCreationAllowedEmails) > 0 {
+ user, err := h.Queries.GetUser(r.Context(), parseUUID(userID))
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusUnauthorized, "user not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load user")
+ return
+ }
+ if !contains(h.cfg.WorkspaceCreationAllowedEmails, strings.TrimSpace(user.Email)) {
+ writeError(w, http.StatusForbidden, "workspace creation is restricted to selected users on this instance")
+ return
+ }
+ }
+
var req CreateWorkspaceRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.go
index 748b68c1dd..54f0dbb747 100644
--- a/server/internal/handler/workspace_test.go
+++ b/server/internal/handler/workspace_test.go
@@ -113,6 +113,71 @@ func TestCreateWorkspace_DisabledByConfig(t *testing.T) {
}
}
+// TestCreateWorkspace_AllowedEmails guards the self-host allowlist added by
+// #9400: when WorkspaceCreationAllowedEmails is set, only matching accounts
+// (case-insensitive) may create workspaces; everyone else gets 403 and no row
+// is written. DisableWorkspaceCreation still wins over the allowlist.
+func TestCreateWorkspace_AllowedEmails(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ cases := []struct {
+ name string
+ cfg Config
+ wantCode int
+ }{
+ {
+ name: "caller not in allowlist",
+ cfg: Config{WorkspaceCreationAllowedEmails: []string{"[email protected]"}},
+ wantCode: http.StatusForbidden,
+ },
+ {
+ name: "caller in allowlist (case-insensitive)",
+ cfg: Config{WorkspaceCreationAllowedEmails: []string{"[email protected]", strings.ToUpper(handlerTestEmail)}},
+ wantCode: http.StatusCreated,
+ },
+ {
+ name: "global disable overrides allowlist",
+ cfg: Config{
+ DisableWorkspaceCreation: true,
+ WorkspaceCreationAllowedEmails: []string{handlerTestEmail},
+ },
+ wantCode: http.StatusForbidden,
+ },
+ }
+
+ for i, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ slug := fmt.Sprintf("handler-tests-create-allowlist-%d", i)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)
+ dbfx.Cleanup(t, `DELETE FROM workspace WHERE slug = $1`, slug)
+
+ prev := testHandler.cfg
+ cfg := tc.cfg
+ cfg.AllowSignup = prev.AllowSignup
+ testHandler.cfg = cfg
+ t.Cleanup(func() { testHandler.cfg = prev })
+
+ req := newRequest("POST", "/api/workspaces", map[string]any{
+ "name": "Allowlist Create",
+ "slug": slug,
+ })
+ testutil.Call(t, testHandler.CreateWorkspace, req).Want(tc.wantCode)
+
+ var count int
+ dbfx.QueryRow(t, `SELECT count(*) FROM workspace WHERE slug = $1`, slug).Scan(&count)
+ wantCount := 0
+ if tc.wantCode == http.StatusCreated {
+ wantCount = 1
+ }
+ if count != wantCount {
+ t.Fatalf("expected %d workspace rows, found %d", wantCount, count)
+ }
+ })
+ }
+}
+
// TestDeleteWorkspace_RequiresOwner exercises the in-handler authorization
// added to DeleteWorkspace by calling the handler directly (bypassing the
// router-level RequireWorkspaceRoleFromURL middleware). Without the handler