Skip to content

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

Go

MUL-7607 fix(auth): restore invitation-based signup (#8706)

Francisco Guimarães (chico)540308342019
diff --git a/.env.example b/.env.example
index beef7cf9c1..b30e72bc27 100644
--- a/.env.example
+++ b/.env.example
@@ -653,16 +653,18 @@ NEXT_PUBLIC_WS_URL=
# REMOTE_API_URL=https://multica-api.copilothub.ai
# ==================== Self-hosting: Control Signups (fixes #930) ====================
-# Set to "false" to completely disable new user signups (recommended for private instances)
+# Set to "false" to restrict new accounts to allowlisted or invited users.
+# A pending, unexpired workspace invitation also permits emails outside either
+# allowlist when ALLOW_SIGNUP=true. Revocation does not remove existing accounts.
ALLOW_SIGNUP=true
# The web UI reads ALLOW_SIGNUP from /api/config at runtime, so toggling this
# only requires restarting the backend / compose stack — not rebuilding web.
# It is not hot-reloaded.
-# Optional: Only allow emails from these domains (comma-separated)
+# Optional: Allow emails from these domains without an invitation (comma-separated)
ALLOWED_EMAIL_DOMAINS=
-# Optional: Only allow these exact email addresses (comma-separated)
+# Optional: Allow these exact email addresses without an invitation (comma-separated)
ALLOWED_EMAILS=
# Set to "true" to disable workspace creation for every caller on this
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index 4e6258760b..441b6f9567 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -71,7 +71,7 @@ Changes take effect after restarting the backend / compose stack. The web UI rea
| Variable | Description |
|----------|-------------|
-| `ALLOW_SIGNUP` | Set to `false` to disable new user signups on a private instance |
+| `ALLOW_SIGNUP` | Set to `false` to restrict new accounts to allowlisted or invited users |
| `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 |
@@ -80,14 +80,14 @@ Changes take effect after restarting the backend / compose stack. The web UI rea
#### Locking down workspace creation
-`ALLOW_SIGNUP=false` blocks new accounts from being created, but it does **not** block an already-signed-in user from creating another workspace via `POST /api/workspaces`. On a self-hosted instance where every issue/repo/agent must be visible to the platform admin, set `DISABLE_WORKSPACE_CREATION=true` to close that gap. The recommended bootstrap sequence is:
+`ALLOW_SIGNUP=false` restricts new accounts to allowlisted or invited users, but it does **not** block an already-signed-in user from creating another workspace via `POST /api/workspaces`. On a self-hosted instance where every issue/repo/agent must be visible to the platform admin, set `DISABLE_WORKSPACE_CREATION=true` to close that gap. The recommended bootstrap sequence is:
1. Start the instance with `DISABLE_WORKSPACE_CREATION=false` (the default).
2. Sign in as the admin and create the shared workspace.
-3. Set `DISABLE_WORKSPACE_CREATION=true` and restart the backend. Optionally set `ALLOW_SIGNUP=false` at the same time if you also want to block new account creation.
+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.
-> Note: setting `ALLOW_SIGNUP=false` blocks **all** new account creation, including users who already have a pending invitation. If you need invited users to be able to sign up but not create their own workspaces, keep `ALLOW_SIGNUP=true` (optionally combined with `ALLOWED_EMAIL_DOMAINS` / `ALLOWED_EMAILS`) and only flip `DISABLE_WORKSPACE_CREATION=true`.
+> 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/auth-setup.ja.mdx b/apps/docs/content/docs/auth-setup.ja.mdx
index 97dfbea0c9..01f41c3e74 100644
--- a/apps/docs/content/docs/auth-setup.ja.mdx
+++ b/apps/docs/content/docs/auth-setup.ja.mdx
@@ -111,14 +111,14 @@ Google Console と `GOOGLE_REDIRECT_URI` のアドレスは、プロトコル、
1. メールアドレスが `ALLOWED_EMAILS` に一致すれば許可。
2. またはドメインが `ALLOWED_EMAIL_DOMAINS` に一致すれば許可。
-3. どちらにも一致せず、`ALLOW_SIGNUP=false` なら拒否。
-4. `ALLOW_SIGNUP=true` でも、いずれかの allowlist が設定されていて一致しなければ、やはり拒否。
-5. allowlist が一つも設定されておらず、`ALLOW_SIGNUP=true` なら許可。
+3. allowlist が一つも設定されておらず、`ALLOW_SIGNUP=true` なら許可。
+4. それ以外でも、そのメールアドレスに保留中かつ有効期限内のワークスペース招待があれば許可。
+5. それ以外は拒否。
よくある設定:
```dotenv
-# 会社ドメインのみ許可
+# 会社ドメインと招待ユーザーを許可
ALLOW_SIGNUP=false
ALLOWED_EMAIL_DOMAINS=company.com
@@ -132,12 +132,13 @@ [email protected]
## 招待とサインアップ制限
-招待はサインアップ制限を自動的には迂回しません:
+保留中かつ有効期限内のワークスペース招待があれば、`ALLOW_SIGNUP=false` の場合や、メールアドレスが `ALLOWED_EMAILS` または `ALLOWED_EMAIL_DOMAINS` に一致しない場合でもアカウントを作成できます。この例外は `ALLOW_SIGNUP=true` で allowlist が設定されている場合にも適用されます。allowlist は有効な招待を持つユーザーを拒否する境界ではありません。
-- 相手がすでに Multica アカウントを持っている場合は、ログインして招待を受諾できます。
-- まだアカウントがない場合は、そのメールアドレスが上記のサインアップルールを満たす必要があります。
+既存ユーザーは引き続きログインできます。新規ユーザーが allowlist に一致せず、自由な登録も許可されていない場合、保留中かつ有効期限内の招待が必要です。招待が存在しない場合や、期限切れ、受諾済み、辞退済み、取り消し済みの場合は登録を許可しません。招待はログインコードの要求時とアカウント作成時に確認され、Google ログインによるアカウント作成にも適用されます。
-オープンなサインアップを無効にしたインスタンスで新しいメンバーを招待するときは、先に相手のメールアドレスを `ALLOWED_EMAILS` に追加してください。アカウントが作成され、招待が受諾されたら、エントリを削除して構いません。
+通常の招待ユーザーを `ALLOWED_EMAILS` に追加したり、サーバーを再起動したりする必要はありません。ワークスペースに参加するには、アカウント作成後も通常の招待フローで招待を受諾する必要があります。
+
+招待を取り消しても、その招待を使って作成済みのアカウントは削除されず、そのアカウントのログインも禁止されません。
## セッション有効期間
diff --git a/apps/docs/content/docs/auth-setup.ko.mdx b/apps/docs/content/docs/auth-setup.ko.mdx
index 1f69c3250e..85e18474c8 100644
--- a/apps/docs/content/docs/auth-setup.ko.mdx
+++ b/apps/docs/content/docs/auth-setup.ko.mdx
@@ -111,14 +111,14 @@ Google Console과 `GOOGLE_REDIRECT_URI`의 주소는 프로토콜, 포트, 마
1. 이메일이 `ALLOWED_EMAILS`와 일치하면 허용합니다.
2. 또는 도메인이 `ALLOWED_EMAIL_DOMAINS`와 일치하면 허용합니다.
-3. 어느 것과도 일치하지 않고 `ALLOW_SIGNUP=false`이면 거부합니다.
-4. `ALLOW_SIGNUP=true`여도 하나 이상의 allowlist가 설정되어 있고 일치하지 않으면 거부합니다.
-5. allowlist가 없고 `ALLOW_SIGNUP=true`이면 허용합니다.
+3. allowlist가 없고 `ALLOW_SIGNUP=true`이면 허용합니다.
+4. 그 외에도 해당 이메일에 대기 중이며 만료되지 않은 워크스페이스 초대가 있으면 허용합니다.
+5. 나머지는 거부합니다.
일반적인 설정:
```dotenv
-# 회사 도메인만 허용
+# 회사 도메인과 초대받은 사용자 허용
ALLOW_SIGNUP=false
ALLOWED_EMAIL_DOMAINS=company.com
@@ -132,12 +132,13 @@ [email protected]
## 초대와 가입 제한
-초대는 가입 제한을 자동으로 우회하지 않습니다.
+대기 중이며 만료되지 않은 워크스페이스 초대가 있으면 `ALLOW_SIGNUP=false`이거나 이메일이 `ALLOWED_EMAILS` 또는 `ALLOWED_EMAIL_DOMAINS`와 일치하지 않아도 계정을 만들 수 있습니다. 이 예외는 `ALLOW_SIGNUP=true`이고 allowlist가 설정된 경우에도 적용됩니다. allowlist는 유효한 초대를 받은 사용자를 차단하는 절대적인 경계가 아닙니다.
-- 상대방에게 이미 Multica 계정이 있으면 로그인하고 초대를 수락할 수 있습니다.
-- 상대방에게 계정이 없으면 이메일이 위의 가입 규칙을 만족해야 합니다.
+기존 사용자는 계속 로그인할 수 있습니다. 새 사용자가 allowlist와 일치하지 않고 공개 가입도 허용되지 않으면 대기 중이며 만료되지 않은 초대가 필요합니다. 없거나 만료, 수락, 거절, 취소된 초대는 가입 권한을 부여하지 않습니다. 로그인 코드를 요청할 때와 계정을 만들 때 초대를 확인하며, Google 로그인으로 계정을 만드는 경우에도 적용됩니다.
-공개 가입을 닫은 인스턴스에서 새 멤버를 초대할 때는 먼저 상대방 이메일을 `ALLOWED_EMAILS`에 추가하세요. 계정을 만들고 초대를 수락한 뒤 목록에서 다시 제거할 수 있습니다.
+일반 초대 사용자를 `ALLOWED_EMAILS`에 추가하거나 서버를 다시 시작할 필요가 없습니다. 워크스페이스에 참여하려면 계정을 만든 뒤에도 정상 초대 흐름에서 초대를 수락해야 합니다.
+
+초대를 취소해도 해당 초대로 이미 만든 계정은 삭제되지 않으며 기존 계정의 로그인도 차단되지 않습니다.
## 로그인 유효 기간
diff --git a/apps/docs/content/docs/auth-setup.mdx b/apps/docs/content/docs/auth-setup.mdx
index 7bed76984f..52fe3e2178 100644
--- a/apps/docs/content/docs/auth-setup.mdx
+++ b/apps/docs/content/docs/auth-setup.mdx
@@ -111,14 +111,14 @@ The evaluation order is:
1. The email matches `ALLOWED_EMAILS` — allow.
2. Or its domain matches `ALLOWED_EMAIL_DOMAINS` — allow.
-3. With no match, if `ALLOW_SIGNUP=false` — reject.
-4. With `ALLOW_SIGNUP=true` but any allowlist configured and no match — still reject.
-5. With no allowlist configured and `ALLOW_SIGNUP=true` — allow.
+3. With no allowlist configured and `ALLOW_SIGNUP=true` — allow.
+4. Otherwise, if the email has a pending, unexpired workspace invitation — allow.
+5. Otherwise — reject.
Common configurations:
```dotenv
-# Company domain only
+# Company domain and invited users
ALLOW_SIGNUP=false
ALLOWED_EMAIL_DOMAINS=company.com
@@ -132,12 +132,13 @@ Both allowlists also work as an explicit exception list when `ALLOW_SIGNUP=false
## Invitations and signup restrictions
-Invitations do not automatically bypass signup restrictions:
+A pending, unexpired workspace invitation allows its email address to create an account even when `ALLOW_SIGNUP=false` or the address does not match `ALLOWED_EMAILS` or `ALLOWED_EMAIL_DOMAINS`. This exception also applies when `ALLOW_SIGNUP=true` with an allowlist configured: allowlists are not a hard boundary against invited users.
-- If the invitee already has a Multica account, they can sign in and accept the invitation.
-- If they do not, their email must satisfy the signup rules above.
+Existing users can continue to sign in. New users without a matching allowlist entry or open signup need a pending, unexpired invitation; missing, expired, accepted, declined, and revoked invitations do not grant signup permission. The invitation is checked when requesting a login code and again when creating the account, including Google sign-in.
-To invite a new member on an instance with open signup disabled, add their email to `ALLOWED_EMAILS` first. Once the account is created and the invitation accepted, you can remove the entry again.
+You do not need to add ordinary invitees to `ALLOWED_EMAILS` or restart the server. The invitation must still be accepted through the normal invitation flow to join the workspace.
+
+Revoking an invitation does not delete an account already created using it or prevent that existing account from signing in.
## Session lifetime
diff --git a/apps/docs/content/docs/auth-setup.zh.mdx b/apps/docs/content/docs/auth-setup.zh.mdx
index 2efeb51a57..bf1f5d30d4 100644
--- a/apps/docs/content/docs/auth-setup.zh.mdx
+++ b/apps/docs/content/docs/auth-setup.zh.mdx
@@ -111,14 +111,14 @@ Google Console 与 `GOOGLE_REDIRECT_URI` 中的地址必须完全一致,包括
1. 邮箱命中 `ALLOWED_EMAILS`,允许;
2. 或域名命中 `ALLOWED_EMAIL_DOMAINS`,允许;
-3. 未命中时,如果 `ALLOW_SIGNUP=false`,拒绝;
-4. `ALLOW_SIGNUP=true` 但设置了任意白名单且未命中,仍然拒绝;
-5. 没有设置白名单且 `ALLOW_SIGNUP=true`,允许。
+3. 没有设置白名单且 `ALLOW_SIGNUP=true`,允许;
+4. 否则,如果该邮箱有待接受且未过期的工作区邀请,允许;
+5. 其他情况均拒绝。
常见配置:
```dotenv
-# 只允许公司域名
+# 允许公司域名和受邀用户
ALLOW_SIGNUP=false
ALLOWED_EMAIL_DOMAINS=company.com
@@ -132,12 +132,13 @@ [email protected]
## 邀请与注册限制
-邀请不会自动绕过注册限制:
+待接受且未过期的工作区邀请允许该邮箱创建账号,即使 `ALLOW_SIGNUP=false`,或邮箱未命中 `ALLOWED_EMAILS` 和 `ALLOWED_EMAIL_DOMAINS`。此例外也适用于 `ALLOW_SIGNUP=true` 且配置了白名单的情况:白名单不会拦截持有有效邀请的用户。
-- 对方已经有 Multica 账号时,可以登录并接受邀请;
-- 对方还没有账号时,邮箱必须符合上面的注册规则。
+已有用户仍可登录。新用户如果未命中白名单且未开放注册,就需要待接受且未过期的邀请;缺失、已过期、已接受、已拒绝或已撤销的邀请不能授予注册许可。申请登录码时会检查邀请,创建账号时会再次检查,包括通过 Google 登录创建账号。
-在关闭开放注册的实例中邀请新成员时,先把对方邮箱加入 `ALLOWED_EMAILS`。账号创建并接受邀请后,可以再从名单中移除。
+普通受邀人无需再加入 `ALLOWED_EMAILS`,也无需重启服务器。账号创建后,仍需通过正常邀请流程接受邀请才能加入工作区。
+
+撤销邀请不会删除通过该邀请创建的账号,也不会阻止该已有账号登录。
## 登录有效期
diff --git a/apps/docs/content/docs/members-roles.ja.mdx b/apps/docs/content/docs/members-roles.ja.mdx
index a7352be116..58f8c4176e 100644
--- a/apps/docs/content/docs/members-roles.ja.mdx
+++ b/apps/docs/content/docs/members-roles.ja.mdx
@@ -30,7 +30,7 @@ import { Callout } from "fumadocs-ui/components/callout";
![メンバー管理:招待フォームとロール付きのメンバー一覧](/images/docs/members-roster.webp)
-招待された人はそのメールアドレスでログインすれば承諾でき、事前のサインアップは不要です。招待の有効期間は 7 日間で、期限切れ後は再送してください。サインアップを制限しているセルフホストのインスタンスでは、まだアカウントを持たない招待者のサインアップにも引き続きサインアップルールが適用されます。[ログインとサインアップ設定](/auth-setup#招待とサインアップ制限)を参照してください。
+招待された人はそのメールアドレスでログインすれば承諾でき、事前のサインアップは不要です。招待の有効期間は 7 日間で、期限切れ後は再送してください。サインアップを制限しているセルフホストのインスタンスでは、保留中かつ有効期限内の招待があれば、allowlist に追加せずにそのメールアドレスでアカウントを作成できます。[ログインとサインアップ設定](/auth-setup#招待とサインアップ制限)を参照してください。
招待リンクはメールにのみ含まれ、プロダクトの画面にはそれを表示・コピーする場所がありません。メールの送信に失敗しても招待レコードは残るため、取り消してから送り直せます。
diff --git a/apps/docs/content/docs/members-roles.ko.mdx b/apps/docs/content/docs/members-roles.ko.mdx
index 562e67f10c..c9a5eca0f0 100644
--- a/apps/docs/content/docs/members-roles.ko.mdx
+++ b/apps/docs/content/docs/members-roles.ko.mdx
@@ -30,7 +30,7 @@ import { Callout } from "fumadocs-ui/components/callout";
![멤버 관리: 초대 양식과 역할이 표시된 멤버 명단](/images/docs/members-roster.webp)
-초대받은 사람은 해당 이메일로 로그인해 초대를 수락할 수 있으며 미리 가입할 필요는 없습니다. 초대는 7일 동안 유효하고, 만료되면 다시 보내야 합니다. 가입이 제한된 자체 배포 인스턴스에서는 아직 계정이 없는 초대 대상도 가입 규칙의 적용을 받습니다. [로그인과 가입](/auth-setup#초대와-가입-제한)을 참고하세요.
+초대받은 사람은 해당 이메일로 로그인해 초대를 수락할 수 있으며 미리 가입할 필요는 없습니다. 초대는 7일 동안 유효하고, 만료되면 다시 보내야 합니다. 가입이 제한된 자체 배포 인스턴스에서는 대기 중이며 만료되지 않은 초대가 있으면 allowlist에 별도로 추가하지 않아도 해당 이메일로 계정을 만들 수 있습니다. [로그인과 가입](/auth-setup#초대와-가입-제한)을 참고하세요.
초대 링크는 이메일에만 표시되며 제품 화면에서 확인하거나 복사할 수 없습니다. 이메일 전송에 실패해도 초대 기록은 남으므로 취소한 뒤 다시 보낼 수 있습니다.
diff --git a/apps/docs/content/docs/members-roles.mdx b/apps/docs/content/docs/members-roles.mdx
index 6c0477a24a..3bac902e09 100644
--- a/apps/docs/content/docs/members-roles.mdx
+++ b/apps/docs/content/docs/members-roles.mdx
@@ -30,7 +30,7 @@ Roles do not decide who can run an agent. Each agent has its own Access scope, a
![Member management: the invite form and the roster with roles](/images/docs/members-roster.webp)
-The invitee accepts by logging in with that email — no prior signup is needed. Invitations are valid for 7 days; resend after they expire. On self-hosted instances that restrict signup, invitees who do not yet have an account are still subject to the signup rules when registering — see [Auth setup](/auth-setup#invitations-and-signup-restrictions).
+The invitee accepts by logging in with that email — no prior signup is needed. Invitations are valid for 7 days; resend after they expire. On self-hosted instances that restrict signup, a live pending invitation allows that email to create an account without a separate allowlist entry — see [Auth setup](/auth-setup#invitations-and-signup-restrictions).
The invitation link appears only in the email; there is no place in the product to view or copy it. If the email fails to send, the invitation record still exists — revoke it and send a new one.
diff --git a/apps/docs/content/docs/members-roles.zh.mdx b/apps/docs/content/docs/members-roles.zh.mdx
index 7fc9d5627c..be1cc4b25d 100644
--- a/apps/docs/content/docs/members-roles.zh.mdx
+++ b/apps/docs/content/docs/members-roles.zh.mdx
@@ -30,7 +30,7 @@ import { Callout } from "fumadocs-ui/components/callout";
![成员管理:邀请表单与带角色的成员名册](/images/docs/members-roster.webp)
-受邀者用该邮箱登录即可接受,无需提前注册。邀请有效期 7 天,过期后重新发送。在限制注册的自部署实例中,还没有账号的受邀者注册时仍受注册规则约束,见[登录与注册](/auth-setup#邀请与注册限制)。
+受邀者用该邮箱登录即可接受,无需提前注册。邀请有效期 7 天,过期后重新发送。在限制注册的自部署实例中,待接受且未过期的邀请允许该邮箱创建账号,无需另外加入白名单,见[登录与注册](/auth-setup#邀请与注册限制)。
邀请链接只出现在邮件里,产品界面中没有查看或复制它的入口。邮件发送失败时邀请记录仍然存在,可以撤销后重新发送。
diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.go
index 17bf517ee2..6f4cfbe7b6 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -201,7 +201,7 @@ func (h *Handler) findOrCreateUser(ctx context.Context, email string) (user db.U
return db.User{}, false, auth.ErrTemporarilyDisabledUser
}
- if err := h.checkSignupAllowed(email, isNew); err != nil {
+ if err := h.checkSignupAllowed(ctx, email, isNew); err != nil {
return db.User{}, false, err
}
@@ -252,7 +252,7 @@ func signupSourceFromRequest(r *http.Request) string {
return decoded
}
-func (h *Handler) checkSignupAllowed(email string, isNewUser bool) error {
+func (h *Handler) checkSignupAllowed(ctx context.Context, email string, isNewUser bool) error {
if !isNewUser {
return nil // existing users always allowed to log in
}
@@ -263,27 +263,36 @@ func (h *Handler) checkSignupAllowed(email string, isNewUser bool) error {
domain = email[at+1:]
}
- // 1. explicit email whitelist always wins
+ // 1. explicit email allowlist always wins
if len(h.cfg.AllowedEmails) > 0 && contains(h.cfg.AllowedEmails, email) {
return nil
}
- // 2. domain whitelist always wins
+ // 2. domain allowlist always wins
if len(h.cfg.AllowedEmailDomains) > 0 && contains(h.cfg.AllowedEmailDomains, domain) {
return nil
}
- // 3. general signup flag
- if !h.cfg.AllowSignup {
- return ErrSignupProhibited
+ // 3. unrestricted signup needs no invitation lookup.
+ if h.cfg.AllowSignup && len(h.cfg.AllowedEmailDomains) == 0 && len(h.cfg.AllowedEmails) == 0 {
+ return nil
}
- // 4. if allowlists are set but didn't match, block
- if len(h.cfg.AllowedEmailDomains) > 0 || len(h.cfg.AllowedEmails) > 0 {
- return ErrEmailNotAllowed
+ // 4. A live invitation is an implicit per-email signup allowance. This
+ // also permits invited emails outside configured allowlists, regardless
+ // of ALLOW_SIGNUP. Recheck at account creation in findOrCreateUser.
+ invited, err := h.Queries.HasPendingInvitationForEmail(ctx, email)
+ if err != nil {
+ return fmt.Errorf("check pending invitation for signup: %w", err)
+ }
+ if invited {
+ return nil
}
- return nil
+ if !h.cfg.AllowSignup {
+ return ErrSignupProhibited
+ }
+ return ErrEmailNotAllowed
}
func contains(slice []string, s string) bool {
@@ -322,12 +331,13 @@ func (h *Handler) SendCode(w http.ResponseWriter, r *http.Request) {
}
// User does not exist → treat as new user
isNewUser := true
- if err := h.checkSignupAllowed(email, isNewUser); err != nil {
+ if err := h.checkSignupAllowed(r.Context(), email, isNewUser); err != nil {
var signupErr SignupError
if errors.As(err, &signupErr) {
writeError(w, http.StatusForbidden, signupErr.Error())
} else {
- writeError(w, http.StatusForbidden, "user registration is disabled")
+ slog.Warn("signup eligibility check failed", append(logger.RequestAttrs(r), "error", err, "email", email)...)
+ writeError(w, http.StatusInternalServerError, "failed to check signup eligibility")
}
return
}
@@ -338,13 +348,14 @@ func (h *Handler) SendCode(w http.ResponseWriter, r *http.Request) {
return
}
isNewUser := false
- if err := h.checkSignupAllowed(email, isNewUser); err != nil {
+ if err := h.checkSignupAllowed(r.Context(), email, isNewUser); err != nil {
// This should rarely happen, but handle it anyway
var signupErr SignupError
if errors.As(err, &signupErr) {
writeError(w, http.StatusForbidden, signupErr.Error())
} else {
- writeError(w, http.StatusForbidden, "user registration is disabled")
+ slog.Warn("signup eligibility check failed", append(logger.RequestAttrs(r), "error", err, "email", email)...)
+ writeError(w, http.StatusInternalServerError, "failed to check signup eligibility")
}
return
}
@@ -433,6 +444,7 @@ func (h *Handler) VerifyCode(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, signupErr.Error())
return
}
+ slog.Warn("login user lookup or creation failed", append(logger.RequestAttrs(r), "error", err, "email", email)...)
writeError(w, http.StatusInternalServerError, "failed to create user")
return
}
@@ -669,6 +681,7 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
if writeGoogleLoginActionableError(w, err) {
return
}
+ slog.Warn("login user lookup or creation failed", append(logger.RequestAttrs(r), "error", err, "email", email)...)
writeError(w, http.StatusInternalServerError, "failed to create user")
return
}
diff --git a/server/internal/handler/auth_invitation_signup_test.go b/server/internal/handler/auth_invitation_signup_test.go
new file mode 100644
index 0000000000..60321f6f5c
--- /dev/null
+++ b/server/internal/handler/auth_invitation_signup_test.go
@@ -0,0 +1,209 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func signupInvitation(t *testing.T, email string) string {
+ t.Helper()
+ return dbfx.Insert(t, "workspace_invitation", testutil.Cols{
+ "workspace_id": parseUUID(testWorkspaceID),
+ "inviter_id": parseUUID(testUserID),
+ "invitee_email": email,
+ "role": "member",
+ "status": "pending",
+ "expires_at": testutil.Raw("now() + interval '1 hour'"),
+ })
+}
+
+func restrictSignupHandler(t *testing.T) *Handler {
+ t.Helper()
+ // Keep email delivery local even when the developer has configured a provider.
+ t.Setenv("RESEND_API_KEY", "")
+ t.Setenv("SMTP_HOST", "")
+ h := *testHandler
+ h.cfg = Config{AllowSignup: false}
+ h.EmailService = service.NewEmailService()
+ return &h
+}
+
+func changeSignupInvitation(t *testing.T, id, state string) {
+ t.Helper()
+ switch state {
+ case "pending":
+ case "revoked":
+ if _, err := testHandler.Queries.RevokeInvitation(context.Background(), parseUUID(id)); err != nil {
+ t.Fatal(err)
+ }
+ case "expired":
+ // Leave status pending to exercise expiry without relying on cleanup jobs.
+ dbfx.Exec(t, `UPDATE workspace_invitation SET expires_at = now() - interval '1 hour' WHERE id = $1`, id)
+ default:
+ dbfx.Exec(t, `UPDATE workspace_invitation SET status = $2 WHERE id = $1`, id, state)
+ }
+}
+
+func TestSendCodeInvitationSignupGate(t *testing.T) {
+ for _, state := range []string{"pending", "expired", "accepted", "declined", "revoked", "missing"} {
+ t.Run(state, func(t *testing.T) {
+ email := "invite-signup-" + state + "@example.com"
+ if state != "missing" {
+ id := signupInvitation(t, email)
+ changeSignupInvitation(t, id, state)
+ }
+ dbfx.Cleanup(t, `DELETE FROM verification_code WHERE email = $1`, email)
+ h := restrictSignupHandler(t)
+ want := http.StatusForbidden
+ if state == "pending" {
+ want = http.StatusOK
+ }
+ req := testutil.JSONRequest(http.MethodPost, "/auth/send-code", map[string]string{"email": " " + strings.ToUpper(email) + " "})
+ testutil.Call(t, h.SendCode, req).Want(want)
+ })
+ }
+}
+
+func TestVerifyCodeRechecksSignupInvitation(t *testing.T) {
+ for _, state := range []string{"pending", "expired", "revoked", "declined", "accepted"} {
+ t.Run(state, func(t *testing.T) {
+ email := "invite-recheck-" + state + "@example.com"
+ id := signupInvitation(t, email)
+ dbfx.Cleanup(t, `DELETE FROM "user" WHERE email = $1`, email)
+ dbfx.Cleanup(t, `DELETE FROM verification_code WHERE email = $1`, email)
+ h := restrictSignupHandler(t)
+ testutil.Call(t, h.SendCode, testutil.JSONRequest(http.MethodPost, "/auth/send-code", map[string]string{"email": email})).Want(http.StatusOK)
+ code, err := h.Queries.GetLatestVerificationCode(context.Background(), email)
+ if err != nil {
+ t.Fatal(err)
+ }
+ changeSignupInvitation(t, id, state)
+ want := http.StatusForbidden
+ if state == "pending" {
+ want = http.StatusOK
+ }
+ resp := testutil.Call(t, h.VerifyCode, testutil.JSONRequest(http.MethodPost, "/auth/verify-code", map[string]string{"email": email, "code": code.Code})).Want(want)
+ count := dbfx.Count(t, `SELECT count(*) FROM "user" WHERE email = $1`, email)
+ if state != "pending" {
+ if count != 0 || len(resp.Result().Cookies()) != 0 {
+ t.Fatal("invalidated invitation created an account or authenticated session")
+ }
+ return
+ }
+ if count != 1 {
+ t.Fatalf("expected one new account, got %d", count)
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM member WHERE user_id = (SELECT id FROM "user" WHERE email = $1)`, email); n != 0 {
+ t.Fatal("signup must not accept the invitation or grant workspace membership")
+ }
+ changeSignupInvitation(t, id, "revoked")
+ _, isNew, err := h.findOrCreateUser(context.Background(), email)
+ if err != nil || isNew {
+ t.Fatalf("revocation must not block the existing account: isNew=%t, err=%v", isNew, err)
+ }
+ })
+ }
+}
+
+func TestGoogleLoginInvitationSignup(t *testing.T) {
+ t.Setenv("GOOGLE_CLIENT_ID", "test-client")
+ t.Setenv("GOOGLE_CLIENT_SECRET", "test-secret")
+ for _, invited := range []bool{false, true} {
+ t.Run(fmt.Sprintf("invited=%t", invited), func(t *testing.T) {
+ email := fmt.Sprintf("google-invited-%[email protected]", invited)
+ if invited {
+ signupInvitation(t, email)
+ }
+ dbfx.Cleanup(t, `DELETE FROM "user" WHERE email = $1`, email)
+ h := *testHandler
+ h.cfg = Config{AllowSignup: true, AllowedEmailDomains: []string{"company.com"}}
+ h.googleOAuthHTTPClient = &http.Client{Transport: googleRoundTripper(func(req *http.Request) (*http.Response, error) {
+ switch req.URL.Host {
+ case "oauth2.googleapis.com":
+ return googleResponse(req, http.StatusOK, `{"access_token":"test-token"}`), nil
+ case "www.googleapis.com":
+ return googleResponse(req, http.StatusOK, fmt.Sprintf(`{"email":%q}`, " "+strings.ToUpper(email)+" ")), nil
+ default:
+ t.Fatalf("unexpected Google request: %s", req.URL)
+ return nil, nil
+ }
+ })}
+ want := http.StatusForbidden
+ if invited {
+ want = http.StatusOK
+ }
+ resp := testutil.Call(t, h.GoogleLogin, testutil.JSONRequest(http.MethodPost, "/auth/google", map[string]string{"code": "test-code", "redirect_uri": "http://localhost/auth/callback"})).Want(want)
+ if invited {
+ var login LoginResponse
+ resp.JSON(&login)
+ if login.Token == "" || login.User.Email != email {
+ t.Fatalf("expected authenticated invited account, got %+v", login.User)
+ }
+ } else if len(resp.Result().Cookies()) != 0 || dbfx.Count(t, `SELECT count(*) FROM "user" WHERE email = $1`, email) != 0 {
+ t.Fatal("uninvited user must not get an account or session")
+ }
+ })
+ }
+}
+
+// Delegate every real query except the failing invitation lookup. This pins
+// HTTP error handling and proves no account or session is created on failure.
+type failingSignupInvitationDB struct{ db.DBTX }
+
+func (m failingSignupInvitationDB) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
+ if strings.HasPrefix(sql, "-- name: HasPendingInvitationForEmail :one\n") {
+ return &mockRow{err: context.Canceled}
+ }
+ return m.DBTX.QueryRow(ctx, sql, args...)
+}
+
+func TestSignupInvitationLookupFailure(t *testing.T) {
+ t.Setenv("GOOGLE_CLIENT_ID", "test-client")
+ t.Setenv("GOOGLE_CLIENT_SECRET", "test-secret")
+ for _, path := range []string{"send-code", "verify-code", "google"} {
+ t.Run(path, func(t *testing.T) {
+ email := "invite-lookup-error-" + path + "@example.com"
+ signupInvitation(t, email)
+ h := *testHandler
+ h.cfg = Config{AllowSignup: false}
+ h.Queries = db.New(failingSignupInvitationDB{testPool})
+ handler := h.SendCode
+ body := map[string]string{"email": email}
+ switch path {
+ case "verify-code":
+ handler = h.VerifyCode
+ body["code"] = "123456"
+ dbfx.Insert(t, "verification_code", testutil.Cols{
+ "email": email, "code": body["code"], "expires_at": testutil.Raw("now() + interval '10 minutes'"),
+ })
+ case "google":
+ handler = h.GoogleLogin
+ body = map[string]string{"code": "test-code", "redirect_uri": "http://localhost/auth/callback"}
+ h.googleOAuthHTTPClient = &http.Client{Transport: googleRoundTripper(func(req *http.Request) (*http.Response, error) {
+ switch req.URL.Host {
+ case "oauth2.googleapis.com":
+ return googleResponse(req, http.StatusOK, `{"access_token":"test-token"}`), nil
+ case "www.googleapis.com":
+ return googleResponse(req, http.StatusOK, fmt.Sprintf(`{"email":%q}`, email)), nil
+ default:
+ t.Fatalf("unexpected Google request: %s", req.URL)
+ return nil, nil
+ }
+ })}
+ }
+ dbfx.Cleanup(t, `DELETE FROM "user" WHERE email = $1`, email)
+ resp := testutil.Call(t, handler, testutil.JSONRequest(http.MethodPost, "/auth/"+path, body)).Want(http.StatusInternalServerError)
+ if len(resp.Result().Cookies()) != 0 || dbfx.Count(t, `SELECT count(*) FROM "user" WHERE email = $1`, email) != 0 {
+ t.Fatal("invitation lookup failure must not create an account or session")
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/auth_signup_test.go b/server/internal/handler/auth_signup_test.go
index 587445caf1..9185a9c8f6 100644
--- a/server/internal/handler/auth_signup_test.go
+++ b/server/internal/handler/auth_signup_test.go
@@ -3,6 +3,7 @@ package handler
import (
"context"
"errors"
+ "fmt"
"net/http"
"strings"
"testing"
@@ -40,7 +41,8 @@ func TestSignupGating(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := newTestHandler(tt.cfg)
- err := h.checkSignupAllowed(tt.email, tt.isNew)
+ h.Queries = db.New(&mockDB{})
+ err := h.checkSignupAllowed(context.Background(), tt.email, tt.isNew)
if !errors.Is(err, tt.want) {
t.Fatalf("got err=%v want=%v", err, tt.want)
}
@@ -86,12 +88,31 @@ func TestEmailCodeAllowlistErrors(t *testing.T) {
}
}
+func TestSignupGatingReturnsPendingInvitationLookupError(t *testing.T) {
+ h := newTestHandler(Config{AllowSignup: false})
+ h.Queries = db.New(&mockDB{pendingInvitationErr: context.Canceled})
+
+ err := h.checkSignupAllowed(context.Background(), "[email protected]", true)
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("got err=%v, want context canceled", err)
+ }
+}
+
type mockDB struct {
db.DBTX
- getUserErr error
+ invitationLookups int
+ invitationEmail string
+ getUserErr error
+ pendingInvitation bool
+ pendingInvitationErr error
}
func (m *mockDB) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
+ if strings.HasPrefix(sql, "-- name: HasPendingInvitationForEmail :one\n") {
+ m.invitationLookups++
+ m.invitationEmail = args[0].(string)
+ return &mockRow{err: m.pendingInvitationErr, boolValue: &m.pendingInvitation}
+ }
return &mockRow{err: m.getUserErr}
}
@@ -101,10 +122,21 @@ func (m *mockDB) Exec(ctx context.Context, sql string, args ...interface{}) (pgc
type mockRow struct {
pgx.Row
- err error
+ err error
+ boolValue *bool
}
func (m *mockRow) Scan(dest ...interface{}) error {
+ if m.err != nil {
+ return m.err
+ }
+ if m.boolValue != nil {
+ value, ok := dest[0].(*bool)
+ if !ok {
+ return fmt.Errorf("expected *bool destination, got %T", dest[0])
+ }
+ *value = *m.boolValue
+ }
return m.err
}
@@ -155,3 +187,65 @@ func TestFindOrCreateUserGating(t *testing.T) {
}
})
}
+
+// Invitations are explicit per-email exceptions for both signup flag values.
+func TestSignupInvitationAllowlistInteraction(t *testing.T) {
+ for _, allowSignup := range []bool{false, true} {
+ for _, allowlist := range []string{"none", "email", "domain", "both"} {
+ for _, invited := range []bool{false, true} {
+ t.Run(fmt.Sprintf("signup=%t/allowlist=%s/invited=%t", allowSignup, allowlist, invited), func(t *testing.T) {
+ cfg := Config{AllowSignup: allowSignup}
+ if allowlist == "email" || allowlist == "both" {
+ cfg.AllowedEmails = []string{"[email protected]"}
+ }
+ if allowlist == "domain" || allowlist == "both" {
+ cfg.AllowedEmailDomains = []string{"company.com"}
+ }
+ mock := &mockDB{pendingInvitation: invited}
+ h := newTestHandler(cfg)
+ h.Queries = db.New(mock)
+ err := h.checkSignupAllowed(context.Background(), "[email protected]", true)
+ var want error
+ openSignup := allowSignup && allowlist == "none"
+ if !invited && !openSignup {
+ want = ErrSignupProhibited
+ if allowSignup {
+ want = ErrEmailNotAllowed
+ }
+ }
+ if !errors.Is(err, want) {
+ t.Fatalf("got %v, want %v", err, want)
+ }
+ if !openSignup && (mock.invitationLookups != 1 || mock.invitationEmail != "[email protected]") {
+ t.Fatalf("expected one normalized email lookup, got %d for %q", mock.invitationLookups, mock.invitationEmail)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestSignupSkipsUnnecessaryInvitationLookup(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ cfg Config
+ isNew bool
+ }{
+ {"existing", Config{}, false},
+ {"open", Config{AllowSignup: true}, true},
+ {"email_match", Config{AllowedEmails: []string{"[email protected]"}}, true},
+ {"domain_match", Config{AllowedEmailDomains: []string{"COMPANY.COM"}}, true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ mock := &mockDB{pendingInvitationErr: context.Canceled}
+ h := newTestHandler(tt.cfg)
+ h.Queries = db.New(mock)
+ if err := h.checkSignupAllowed(context.Background(), "[email protected]", tt.isNew); err != nil {
+ t.Fatal(err)
+ }
+ if mock.invitationLookups != 0 {
+ t.Fatalf("unexpected invitation lookups: %d", mock.invitationLookups)
+ }
+ })
+ }
+}
diff --git a/server/pkg/db/generated/invitation.sql.go b/server/pkg/db/generated/invitation.sql.go
index 31f9b5dbd3..a2e45a0c6d 100644
--- a/server/pkg/db/generated/invitation.sql.go
+++ b/server/pkg/db/generated/invitation.sql.go
@@ -204,6 +204,23 @@ func (q *Queries) GetPendingInvitationByEmail(ctx context.Context, arg GetPendin
return i, err
}
+const hasPendingInvitationForEmail = `-- name: HasPendingInvitationForEmail :one
+SELECT EXISTS (
+ SELECT 1
+ FROM workspace_invitation
+ WHERE invitee_email = $1
+ AND status = 'pending'
+ AND expires_at > now()
+)
+`
+
+func (q *Queries) HasPendingInvitationForEmail(ctx context.Context, inviteeEmail string) (bool, error) {
+ row := q.db.QueryRow(ctx, hasPendingInvitationForEmail, inviteeEmail)
+ var exists bool
+ err := row.Scan(&exists)
+ return exists, err
+}
+
const listPendingInvitationsByWorkspace = `-- name: ListPendingInvitationsByWorkspace :many
SELECT wi.id, wi.workspace_id, wi.inviter_id, wi.invitee_email, wi.invitee_user_id, wi.role, wi.status, wi.created_at, wi.updated_at, wi.expires_at,
u.name AS inviter_name,
diff --git a/server/pkg/db/queries/invitation.sql b/server/pkg/db/queries/invitation.sql
index e4672e4280..bfddcd2010 100644
--- a/server/pkg/db/queries/invitation.sql
+++ b/server/pkg/db/queries/invitation.sql
@@ -49,6 +49,15 @@ WHERE id = $1 AND status = 'pending';
SELECT * FROM workspace_invitation
WHERE workspace_id = $1 AND invitee_email = $2 AND status = 'pending' AND expires_at > now();
+-- name: HasPendingInvitationForEmail :one
+SELECT EXISTS (
+ SELECT 1
+ FROM workspace_invitation
+ WHERE invitee_email = $1
+ AND status = 'pending'
+ AND expires_at > now()
+);
+
-- name: ExpireStalePendingInvitations :many
-- Mark any past-due pending invitations for (workspace_id, invitee_email) as expired,
-- so the next CreateInvitation does not collide with the partial unique index