Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(server): restrict sign-in and API access to listed accounts (MUL-10310) (#11724)
LinYushenad746a6aacb2
diff --git a/.env.example b/.env.exampleindex 62870f3f21..f87872f768 100644--- a/.env.example+++ b/.env.example@@ -802,6 +802,14 @@ DISABLE_WORKSPACE_CREATION=# workspaces. Requires a backend restart.WORKSPACE_CREATION_ALLOWED_EMAILS=+# Optional: only these accounts may sign in or call any API (comma-separated,+# case-insensitive). Entries are exact addresses ([email protected]) or whole+# domains (*@example.com). Leave empty to allow everyone. Unlike+# ALLOWED_EMAILS, this also blocks existing accounts and invited users, and+# applies to PATs, daemon tokens and agent task tokens of unlisted users.+# An invalid entry stops the backend from starting. Requires a backend restart.+ACCESS_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.mdindex 5d7d01e05e..9b02bc5005 100644--- a/SELF_HOSTING.md+++ b/SELF_HOSTING.md@@ -105,7 +105,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`, `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.+Changes to `ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, `WORKSPACE_CREATION_ALLOWED_EMAILS`, `ACCESS_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` and `ACCESS_ALLOWED_EMAILS` are read only by the backend and are 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.@@ -335,7 +335,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`, `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`.+`ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, `WORKSPACE_CREATION_ALLOWED_EMAILS`, `ACCESS_ALLOWED_EMAILS`, and `GOOGLE_CLIENT_ID` likewise live under `backend.config.*` in `values.yaml` (as `allowSignup`, `disableWorkspaceCreation`, `workspaceCreationAllowedEmails`, `accessAllowedEmails`, 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` and `accessAllowedEmails` are read only by the backend and are 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.mdindex e041ed9e0e..34c2acdf3e 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -76,6 +76,7 @@ Changes take effect after restarting the backend / compose stack. The web UI rea| `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` |+| `ACCESS_ALLOWED_EMAILS` | Optional comma-separated list of accounts allowed to sign in and call the API: exact addresses or `*@domain` wildcards. When set, everyone else gets 403 on every API call |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.@@ -103,6 +104,22 @@ [email protected],[email protected]3. The caller's account email matches an entry (case-insensitive) → allowed.4. Otherwise → 403.+#### Restricting the whole instance to selected accounts++To let only certain people use the instance at all, set `ACCESS_ALLOWED_EMAILS`. Each entry is either an exact address or `*@domain` for every address on that domain:++```dotenv+ACCESS_ALLOWED_EMAILS=*@example.com,[email protected]+```++- Empty (the default) → no restriction.+- Otherwise, sign-in (verification code and Google) is refused for any other email, and every authenticated API request from any other account returns 403 with code `access_not_allowed`. This covers browser sessions, personal access tokens, daemon tokens, agent task tokens, Connected Apps calls from agent runs started by that account, and plugin callbacks acting for that account. A browser that is already signed in is signed out and told the account is not allowed.+- Bound IM channel messages and Slack slash commands from excluded accounts are refused before creating chats, issues, or agent runs. Queued tasks originated by an excluded account are failed before a daemon claims them.+- WebSocket connections are refused too: a handshake authenticated by the session cookie gets 403, and a client that authenticates in its first message gets an error message and the connection is closed.+- Unlike `ALLOWED_EMAILS` / `ALLOWED_EMAIL_DOMAINS`, it applies to existing accounts too, and an invitation does not bypass it. Removing someone from the list cuts off their API access after a restart. File-download cookies (CloudFront signed cookies, when configured) that were already issued stay valid until they expire.+- `*@example.com` does not match subdomains such as `dev.example.com`; list them separately. Internationalized domains must be written in their ASCII form (`xn--...`).+- A malformed entry (for example `example.com` without `*@`, or a domain containing a space) stops the backend from starting.+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.diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdxindex 3d595f5e8f..f82dd2c4f1 100644--- a/apps/docs/content/docs/environment-variables.fr.mdx+++ b/apps/docs/content/docs/environment-variables.fr.mdx@@ -117,6 +117,7 @@ SMTP est prioritaire sur Resend dès que `SMTP_HOST` n'est pas vide.| `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 |+| `ACCESS_ALLOWED_EMAILS` | vide | Comptes autorisés à se connecter et à appeler l'API, séparés par des virgules : adresses exactes (`[email protected]`) ou domaines entiers (`*@example.com`). Une fois défini, tous les autres reçoivent une 403, y compris les comptes existants et les invités. Une entrée invalide empêche le backend de démarrer || `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.mdxindex 51c9cd28a8..0743f0f61e 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -117,6 +117,7 @@ primary とレプリカの接続上限は独立しています。全 API プロ| `ALLOWED_EMAIL_DOMAINS` | 空 | 登録を許可するメールドメイン。カンマ区切り || `DISABLE_WORKSPACE_CREATION` | `false` | すべてのユーザーのワークスペース新規作成を禁止。owner/admin の例外はありません || `WORKSPACE_CREATION_ALLOWED_EMAILS` | 空 | ワークスペースの新規作成を許可するメールアドレス(完全一致、カンマ区切り)。設定すると、それ以外のユーザーには 403 を返します。`DISABLE_WORKSPACE_CREATION=true` が優先されます。他のワークスペースへのアクセス権は付与しません |+| `ACCESS_ALLOWED_EMAILS` | 空 | サインインと API 呼び出しを許可するアカウント(カンマ区切り)。完全一致のアドレス(`[email protected]`)またはドメイン全体(`*@example.com`)。設定すると、既存アカウントや招待されたユーザーを含め、それ以外のすべてのリクエストに 403 を返します。不正なエントリがあるとバックエンドは起動しません || `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.mdxindex 49a601ea44..709952fa43 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -117,6 +117,7 @@ primary와 복제본의 연결 한도는 서로 독립적입니다. 모든 API| `ALLOWED_EMAIL_DOMAINS` | 비어 있음 | 가입을 허용할 이메일 도메인, 쉼표로 구분 || `DISABLE_WORKSPACE_CREATION` | `false` | 모든 사용자의 새 워크스페이스 생성을 금지. owner/admin 예외 없음 || `WORKSPACE_CREATION_ALLOWED_EMAILS` | 비어 있음 | 워크스페이스 생성을 허용할 전체 이메일 주소, 쉼표로 구분. 설정하면 그 외 사용자는 403을 받습니다. `DISABLE_WORKSPACE_CREATION=true`가 우선합니다. 다른 워크스페이스에 대한 접근 권한은 부여하지 않습니다 |+| `ACCESS_ALLOWED_EMAILS` | 비어 있음 | 로그인과 API 호출을 허용할 계정, 쉼표로 구분: 전체 이메일 주소(`[email protected]`) 또는 도메인 전체(`*@example.com`). 설정하면 기존 계정과 초대받은 사용자를 포함해 그 외 모든 요청은 403을 받습니다. 잘못된 항목이 있으면 백엔드가 시작되지 않습니다 || `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.mdxindex 5025d107ad..c3b5908216 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -117,6 +117,7 @@ SMTP takes priority over Resend whenever `SMTP_HOST` is non-empty.| `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 |+| `ACCESS_ALLOWED_EMAILS` | empty | Accounts allowed to sign in and call the API, comma-separated: exact addresses (`[email protected]`) or whole domains (`*@example.com`). When set, everyone else gets 403, including existing accounts and invited users. An invalid entry stops the backend from starting || `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-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdxindex 295139bc2f..9611ce9aa5 100644--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx@@ -117,6 +117,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `ALLOWED_EMAIL_DOMAINS` | 空 | 允許註冊的信箱網域,逗號分隔 || `DISABLE_WORKSPACE_CREATION` | `false` | 禁止所有使用者新建工作區;沒有 owner/admin 例外 || `WORKSPACE_CREATION_ALLOWED_EMAILS` | 空 | 允許新建工作區的完整信箱地址,逗號分隔。設定後其他使用者新建會返回 403。`DISABLE_WORKSPACE_CREATION=true` 優先。不授予訪問其他工作區的權限 |+| `ACCESS_ALLOWED_EMAILS` | 空 | 允許登入和呼叫 API 的帳號,逗號分隔:完整信箱(`[email protected]`)或整個網域(`*@example.com`)。設定後其他帳號的所有請求返回 403,既有帳號和受邀使用者也不例外。條目格式錯誤時後端無法啟動 || `MULTICA_DEV_VERIFICATION_CODE` | 空 | 非 production 環境使用的固定 6 位測試驗證碼 |白名單的準確判斷順序見[登入與註冊](/auth-setup#註冊範圍控制)。diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex e40cce7123..779a27964e 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -117,6 +117,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| `ALLOWED_EMAIL_DOMAINS` | 空 | 允许注册的邮箱域名,逗号分隔 || `DISABLE_WORKSPACE_CREATION` | `false` | 禁止所有用户新建工作区;没有 owner/admin 例外 || `WORKSPACE_CREATION_ALLOWED_EMAILS` | 空 | 允许新建工作区的完整邮箱地址,逗号分隔。设置后其他用户新建会返回 403。`DISABLE_WORKSPACE_CREATION=true` 优先。不授予访问其他工作区的权限 |+| `ACCESS_ALLOWED_EMAILS` | 空 | 允许登录和调用 API 的账号,逗号分隔:完整邮箱(`[email protected]`)或整个域名(`*@example.com`)。设置后其他账号的所有请求返回 403,已有账号和受邀用户也不例外。条目格式错误时后端无法启动 || `MULTICA_DEV_VERIFICATION_CODE` | 空 | 非 production 环境使用的固定 6 位测试验证码 |白名单的准确判断顺序见[登录与注册](/auth-setup#注册范围控制)。diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yamlindex c623a02a06..50cea6df1b 100644--- a/deploy/helm/multica/templates/configmap.yaml+++ b/deploy/helm/multica/templates/configmap.yaml@@ -22,6 +22,7 @@ data: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 }}+ ACCESS_ALLOWED_EMAILS: {{ .Values.backend.config.accessAllowedEmails | quote }}DO_NOT_TRACK: {{ .Values.backend.config.doNotTrack | quote }}MULTICA_VCS_INTEGRATION_ENABLED: {{ .Values.backend.config.vcsIntegrationEnabled | quote }}MULTICA_THEME_REGISTRY_URL: {{ .Values.backend.config.themeStore.registryUrl | quote }}diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex 640d1584aa..05b2f4f4e3 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -158,6 +158,10 @@ backend:# create workspaces. Empty = every signed-in user may create one.# disableWorkspaceCreation=true still blocks everyone.workspaceCreationAllowedEmails: ""+ # Comma-separated accounts allowed to sign in and call the API: exact+ # addresses ([email protected]) or whole domains (*@example.com).+ # Empty = no restriction. Anyone else gets 403 on every API call.+ accessAllowedEmails: ""# 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.ymlindex 2d11afe7db..954c539baa 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -123,6 +123,7 @@ services:ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}DISABLE_WORKSPACE_CREATION: ${DISABLE_WORKSPACE_CREATION:-}WORKSPACE_CREATION_ALLOWED_EMAILS: ${WORKSPACE_CREATION_ALLOWED_EMAILS:-}+ ACCESS_ALLOWED_EMAILS: ${ACCESS_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/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex c103da0ce6..713c214ef1 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -3517,6 +3517,31 @@ describe("ApiClient shared credential across windows", () => {expect(onUnauthorized).toHaveBeenCalledTimes(1);});++ // The access allowlist refuses a valid credential on every request, so it+ // ends the session like a 401 would instead of leaving the shell up.+ it("ends the session on a 403 for an account outside the access allowlist", async () => {+ const onUnauthorized = vi.fn();+ const client = new ApiClient("https://api.example.test", { onUnauthorized });+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({+ error: "this account is not allowed to access this instance",+ code: "access_not_allowed",+ }, 403)));++ await expect(client.markOnboardingComplete()).rejects.toBeInstanceOf(ApiError);++ expect(onUnauthorized).toHaveBeenCalledExactlyOnceWith("access_not_allowed");+ });++ it("keeps the session on any other 403", async () => {+ const onUnauthorized = vi.fn();+ const client = new ApiClient("https://api.example.test", { onUnauthorized });+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ error: "not a member", code: "forbidden" }, 403)));++ await expect(client.markOnboardingComplete()).rejects.toBeInstanceOf(ApiError);++ expect(onUnauthorized).not.toHaveBeenCalled();+ });});describe("ApiClient complete issue deliverables", () => {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 2c0d9343e9..4f11ed6d80 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -664,9 +664,19 @@ export interface ApiClientIdentity {os?: string;}+/**+ * `code` the server sends with a 403 when the instance's access allowlist+ * excludes the signed-in account. The credential is valid but will be+ * refused on every request, so the session ends as it does on a 401.+ */+export const ACCESS_NOT_ALLOWED_CODE = "access_not_allowed";++/** Why the server ended a session, when it is more than a dead credential. */+export type SessionEndReason = typeof ACCESS_NOT_ALLOWED_CODE;+export interface ApiClientOptions {logger?: Logger;- onUnauthorized?: () => void;+ onUnauthorized?: (reason?: SessionEndReason) => void;/** Identifies the client to the server. Sent as X-Client-* headers. */identity?: ApiClientIdentity;/**@@ -820,6 +830,15 @@ export class BatchOpsUnsupportedError extends Error {}}+function isAccessNotAllowedBody(body: unknown): boolean {+ return !!body && typeof body === "object" && (body as { code?: unknown }).code === ACCESS_NOT_ALLOWED_CODE;+}++/** The server refused this account under the instance's access allowlist. */+export function isAccessNotAllowedError(err: unknown): boolean {+ return err instanceof ApiError && err.status === 403 && errorCode(err) === ACCESS_NOT_ALLOWED_CODE;+}+export function errorCode(err: unknown): string | undefined {if (err instanceof ApiError && err.body && typeof err.body === "object") {const code = (err.body as { code?: unknown }).code;@@ -1285,7 +1304,7 @@ export class ApiClient {* 401 may land after the user has signed in again (#10190). Cookie mode is* null on both sides, so its expiries still end the session.*/- private handleUnauthorized(credentialUsed: string | null) {+ private handleUnauthorized(credentialUsed: string | null, reason?: SessionEndReason) {if (this.getToken() !== credentialUsed) {this.logger.info("ignoring 401 for a credential that has since been replaced");return;@@ -1295,7 +1314,7 @@ export class ApiClient {// (set by [workspaceSlug]/layout.tsx). On 401, the auth flow navigates// to /login which leaves the workspace route, and the next workspace// entry will overwrite the id. No clear needed here.- this.options.onUnauthorized?.();+ this.options.onUnauthorized?.(reason);}private async parseErrorMessage(res: Response, fallback: string): Promise<string> {@@ -1403,8 +1422,11 @@ export class ApiClient {}if (!res.ok) {- if (res.status === 401) this.handleUnauthorized(credentialUsed);const { message, body } = await this.parseErrorBody(res, `API error: ${res.status} ${res.statusText}`);+ if (res.status === 401) this.handleUnauthorized(credentialUsed);+ else if (res.status === 403 && isAccessNotAllowedBody(body)) {+ this.handleUnauthorized(credentialUsed, ACCESS_NOT_ALLOWED_CODE);+ }const logLevel = res.status === 404 ? "warn" : "error";this.logger[logLevel](`← ${res.status} ${path}`, { rid, duration: `${Date.now() - start}ms`, error: message });observer?.onEnd({ requestId: rid, status: res.status, error: message });diff --git a/packages/core/api/index.ts b/packages/core/api/index.tsindex d91fa9de42..b8e9e29734 100644--- a/packages/core/api/index.ts+++ b/packages/core/api/index.ts@@ -1,15 +1,18 @@export {+ ACCESS_NOT_ALLOWED_CODE,ApiClient,ApiError,BatchOpsUnsupportedError,clientErrorMessage,dispatchReasonCode,errorCode,+ isAccessNotAllowedError,PreviewTooLargeError,PreviewUnsupportedError,} from "./client";export type {ApiClientOptions,+ SessionEndReason,ClientRuntimeSnapshot,ClientUsageRequest,} from "./client";diff --git a/packages/core/auth/store.test.ts b/packages/core/auth/store.test.tsindex ae79dc5546..2835c8fa5d 100644--- a/packages/core/auth/store.test.ts+++ b/packages/core/auth/store.test.ts@@ -127,6 +127,37 @@ describe("authStore", () => {expect(storage.snapshot().multica_token).toBeUndefined();});+ // Cookie mode at boot has nothing stored client-side, yet a 403 from the+ // access allowlist is about a credential the server accepted, so the login+ // page must still say why, and the refused cookie is cleared.+ it("says the account is not allowed when the access allowlist ends a cookie session at boot", () => {+ const storage = makeStorage();+ const api = {+ setToken: vi.fn(),+ logout: vi.fn().mockResolvedValue(undefined),+ } as unknown as ApiClient;+ const store = createAuthStore({ api, storage, cookieAuth: true });++ store.getState().sessionExpired("access_not_allowed");++ expect(store.getState().status).toBe("unauthenticated");+ expect(store.getState().expired).toBe(true);+ expect(store.getState().accessNotAllowed).toBe(true);+ expect(api.logout).toHaveBeenCalledOnce();+ });++ it("does not flag an ordinary expiry as an access refusal", () => {+ const storage = makeStorage({ multica_token: "t" });+ const api = makeApi();+ const store = createAuthStore({ api, storage });+ store.setState({ user: fakeUser, status: "authenticated", isLoading: false });++ store.getState().sessionExpired();++ expect(store.getState().expired).toBe(true);+ expect(store.getState().accessNotAllowed).toBe(false);+ });+it("runs the expiry handler instead of the logout one when given both", () => {const storage = makeStorage({ multica_token: "t" });const api = makeApi();diff --git a/packages/core/auth/store.ts b/packages/core/auth/store.tsindex 73917c9283..f2af9ccc7a 100644--- a/packages/core/auth/store.ts+++ b/packages/core/auth/store.ts@@ -1,7 +1,7 @@import { create } from "zustand";import type { User, StorageAdapter } from "../types";import { identify as identifyAnalytics, resetAnalytics } from "../analytics";-import type { ApiClient } from "../api/client";+import type { ApiClient, SessionEndReason } from "../api/client";import { setCurrentWorkspace } from "../platform/workspace-storage";export interface AuthStoreOptions {@@ -37,6 +37,13 @@ export interface AuthState {* successful login and by an explicit logout.*/expired: boolean;+ /**+ * The server ended the session because the instance's access allowlist+ * excludes this account. Presentational like `expired`, which it refines:+ * the login page says the account is not allowed rather than that the+ * session expired. Cleared together with `expired`.+ */+ accessNotAllowed: boolean;retryAuthentication: () => void;sendCode: (email: string) => Promise<void>;@@ -44,7 +51,7 @@ export interface AuthState {loginWithGoogle: (code: string, redirectUri: string) => Promise<User>;loginWithToken: (token: string) => Promise<User>;logout: () => void;- sessionExpired: () => void;+ sessionExpired: (reason?: SessionEndReason) => void;setUser: (user: User) => void;refreshMe: () => Promise<void>;}@@ -59,6 +66,7 @@ export function createAuthStore(options: AuthStoreOptions) {status: "authenticating",retryGeneration: 0,expired: false,+ accessNotAllowed: false,retryAuthentication: () => {set((state) => ({@@ -81,7 +89,7 @@ export function createAuthStore(options: AuthStoreOptions) {}onLogin?.();identifyAnalytics(user.id, { email: user.email, name: user.name });- set({ user, isLoading: false, status: "authenticated", expired: false });+ set({ user, isLoading: false, status: "authenticated", expired: false, accessNotAllowed: false });return user;},@@ -93,7 +101,7 @@ export function createAuthStore(options: AuthStoreOptions) {}onLogin?.();identifyAnalytics(user.id, { email: user.email, name: user.name });- set({ user, isLoading: false, status: "authenticated", expired: false });+ set({ user, isLoading: false, status: "authenticated", expired: false, accessNotAllowed: false });return user;},@@ -103,7 +111,7 @@ export function createAuthStore(options: AuthStoreOptions) {const user = await api.getMe();onLogin?.();identifyAnalytics(user.id, { email: user.email, name: user.name });- set({ user, isLoading: false, status: "authenticated", expired: false });+ set({ user, isLoading: false, status: "authenticated", expired: false, accessNotAllowed: false });return user;},@@ -122,6 +130,7 @@ export function createAuthStore(options: AuthStoreOptions) {isLoading: false,status: "unauthenticated",expired: false,+ accessNotAllowed: false,});},@@ -137,7 +146,7 @@ export function createAuthStore(options: AuthStoreOptions) {* session dies once but a screen full of in-flight requests all learn* about it separately.*/- sessionExpired: () => {+ sessionExpired: (reason?: SessionEndReason) => {// "Expired" is a claim about the user's own history, so only make it// when this client really did present a credential the server then// rejected: a live session, or a stored token left by an earlier one.@@ -162,6 +171,13 @@ export function createAuthStore(options: AuthStoreOptions) {// happen at all when there was no session to end.if (get().status === "unauthenticated") return;+ const accessNotAllowed = reason === "access_not_allowed";+ // The refused cookie is still a valid credential, so a reload would+ // present it again only to be refused again. Clearing it is safe here+ // where it would not be for an expiry: the server answered, and+ // `/auth/logout` needs no authentication.+ if (cookieAuth && accessNotAllowed) api.logout().catch(() => {});+// Cookie mode leaves the workspace singleton alone: there the URL owns// workspace identity and the login route overwrites it on the next// entry. Mirrors AuthInitializer's boot-time rejection.@@ -172,17 +188,21 @@ export function createAuthStore(options: AuthStoreOptions) {user: null,isLoading: false,status: "unauthenticated",- expired: hadCredential,+ // The server only says "not allowed" about a credential it accepted,+ // so that answer is about this user even when nothing was stored+ // client-side (a cookie session at boot).+ expired: hadCredential || accessNotAllowed,+ accessNotAllowed,});},setUser: (user: User) => {- set({ user, isLoading: false, status: "authenticated", expired: false });+ set({ user, isLoading: false, status: "authenticated", expired: false, accessNotAllowed: false });},refreshMe: async () => {const user = await api.getMe();- set({ user, isLoading: false, status: "authenticated", expired: false });+ set({ user, isLoading: false, status: "authenticated", expired: false, accessNotAllowed: false });},}));}diff --git a/packages/core/platform/auth-initializer.test.tsx b/packages/core/platform/auth-initializer.test.tsxindex e5075bbc89..dbc4e51e4f 100644--- a/packages/core/platform/auth-initializer.test.tsx+++ b/packages/core/platform/auth-initializer.test.tsx@@ -564,4 +564,23 @@ describe("AuthInitializer recovery", () => {expect(storage.snapshot().multica_token).toBeUndefined();expect(onLogout).toHaveBeenCalledOnce();});++ // The access allowlist refuses a valid session on every attempt; recovering+ // would retry /api/me forever behind a loading screen.+ it("ends a session the access allowlist refuses instead of retrying it", async () => {+ const getMe = vi.fn().mockRejectedValue(new ApiError(+ "this account is not allowed to access this instance",+ 403,+ "Forbidden",+ { error: "this account is not allowed to access this instance", code: "access_not_allowed" },+ ));+ const api = makeApi({ getMe, logout: vi.fn().mockResolvedValue(undefined) });+ renderInitializer({ api, storage: makeStorage(), cookieAuth: true, platform: "web" });++ await waitFor(() => {+ expect(useAuthStore.getState().status).toBe("unauthenticated");+ });+ expect(useAuthStore.getState().accessNotAllowed).toBe(true);+ expect(getMe).toHaveBeenCalledOnce();+ });});diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex feec330b73..92bb1cdc6a 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -3,7 +3,12 @@import { useCallback, useEffect, useRef, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";import { getApi } from "../api";-import { ApiError } from "../api/client";+import {+ ACCESS_NOT_ALLOWED_CODE,+ ApiError,+ isAccessNotAllowedError,+ type SessionEndReason,+} from "../api/client";import { useAuthStore } from "../auth";import {captureSignupSource,@@ -238,6 +243,7 @@ export function AuthInitializer({isLoading: false,status: "authenticated",expired: false,+ accessNotAllowed: false,});identifyAnalytics(user.id, { email: user.email, name: user.name });if (authRecoveryPendingRef.current) {@@ -248,14 +254,14 @@ export function AuthInitializer({}};- const rejectSession = () => {+ const rejectSession = (reason?: SessionEndReason) => {settled = true;window.removeEventListener("online", retryNow);if (retryTimer !== undefined) clearTimeout(retryTimer);// One teardown for every dead session, whether it died at boot or// under a running shell. The api client's 401 hook has normally run// this already by the time we get here; the action is idempotent.- useAuthStore.getState().sessionExpired();+ useAuthStore.getState().sessionExpired(reason);};const scheduleRetry = (attempt: () => Promise<void>) => {@@ -278,6 +284,12 @@ export function AuthInitializer({rejectSession();return;}+ // A valid credential the instance's access allowlist refuses will be+ // refused on every retry; end the session instead of recovering.+ if (isAccessNotAllowedError(err)) {+ rejectSession(ACCESS_NOT_ALLOWED_CODE);+ return;+ }// Workspace consumers observe this query directly. React Query owns// retries and refetch-on-reconnect independently from identity auth.logger.error("workspace bootstrap failed", err);@@ -309,6 +321,12 @@ export function AuthInitializer({rejectSession();return;}+ // A valid credential the instance's access allowlist refuses will be+ // refused on every retry; end the session instead of recovering.+ if (isAccessNotAllowedError(err)) {+ rejectSession(ACCESS_NOT_ALLOWED_CODE);+ return;+ }if (!loggedTransientFailure) {logger.error("auth init temporarily unavailable", err);diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsxindex 92dd9b5747..edef9672e0 100644--- a/packages/core/platform/core-provider.tsx+++ b/packages/core/platform/core-provider.tsx@@ -87,8 +87,8 @@ function initCore({//// `authStore` is assigned a few lines below, synchronously, and this// callback can only run from a request — never before boot finishes.- onUnauthorized: () => {- authStore.getState().sessionExpired();+ onUnauthorized: (reason) => {+ authStore.getState().sessionExpired(reason);},// Token mode only. Desktop runs one ApiClient per window over one shared// localStorage, so the credential has to be read through to storage ratherdiff --git a/packages/views/auth/login-page.test.tsx b/packages/views/auth/login-page.test.tsxindex 679e9c2029..faa6cb7d85 100644--- a/packages/views/auth/login-page.test.tsx+++ b/packages/views/auth/login-page.test.tsx@@ -36,7 +36,7 @@ const mockApiGetMe = vi.hoisted(() => vi.fn());const mockApiIssueCliToken = vi.hoisted(() => vi.fn());const mockSetQueryData = vi.hoisted(() => vi.fn());// Mutable slice of auth state the component subscribes to.-const mockAuthState = vi.hoisted(() => ({ expired: false }));+const mockAuthState = vi.hoisted(() => ({ expired: false, accessNotAllowed: false }));vi.mock("@tanstack/react-query", async () => {const actual = await vi.importActual<typeof import("@tanstack/react-query")>(@@ -53,6 +53,7 @@ vi.mock("@multica/core/auth", () => ({sendCode: mockSendCode,verifyCode: mockVerifyCode,expired: mockAuthState.expired,+ accessNotAllowed: mockAuthState.accessNotAllowed,};return selector ? selector(state) : state;},@@ -103,6 +104,7 @@ describe("LoginPage", () => {vi.useFakeTimers({ shouldAdvanceTime: true });vi.clearAllMocks();mockAuthState.expired = false;+ mockAuthState.accessNotAllowed = false;// Default: no existing session (getMe rejects when no auth)mockApiGetMe.mockRejectedValue(new Error("unauthorized"));localStorage.clear();@@ -129,6 +131,14 @@ describe("LoginPage", () => {).toBeInTheDocument();});+ it("says the account is not allowed when the access allowlist ended the session", () => {+ mockAuthState.expired = true;+ mockAuthState.accessNotAllowed = true;+ renderWithI18n(<LoginPage onSuccess={onSuccess} />);+ expect(screen.getByText(/this account is not allowed to use this instance/i)).toBeInTheDocument();+ expect(screen.queryByText(/your session expired/i)).not.toBeInTheDocument();+ });+it("stays quiet on an ordinary visit to the login page", () => {renderWithI18n(<LoginPage onSuccess={onSuccess} />);expect(screen.queryByText(/your session expired/i)).not.toBeInTheDocument();diff --git a/packages/views/auth/login-page.tsx b/packages/views/auth/login-page.tsxindex f6d2b18a66..ccbc09bbc7 100644--- a/packages/views/auth/login-page.tsx+++ b/packages/views/auth/login-page.tsx@@ -118,6 +118,7 @@ export function LoginPage({// because the user asked to leave. Without saying so, landing here reads as// the app having lost their work for no reason.const sessionExpired = useAuthStore((state) => state.expired);+ const accessNotAllowed = useAuthStore((state) => state.accessNotAllowed);// Check for existing session when CLI callback is present.// Prioritises cookie auth (= current browser session) to avoid authorising@@ -423,7 +424,9 @@ export function LoginPage({{sessionExpired && (<Alert><AlertDescription>- {t(($) => $.errors.session_expired)}+ {accessNotAllowed+ ? t(($) => $.errors.access_not_allowed)+ : t(($) => $.errors.session_expired)}</AlertDescription></Alert>)}diff --git a/packages/views/locales/en/auth.json b/packages/views/locales/en/auth.jsonindex 342a9b48c9..02dc44d116 100644--- a/packages/views/locales/en/auth.json+++ b/packages/views/locales/en/auth.json@@ -31,7 +31,8 @@"resend_failed": "Failed to resend code.","code_invalid": "Invalid or expired code","cli_auth_failed": "Failed to authorize CLI. Please sign in again.",- "session_expired": "Your session expired. Sign in again to continue."+ "session_expired": "Your session expired. Sign in again to continue.",+ "access_not_allowed": "This account is not allowed to use this instance. Sign in with a different account."},"web": {"prefer_desktop": "Prefer the desktop app?",diff --git a/packages/views/locales/es/auth.json b/packages/views/locales/es/auth.jsonindex c2ee08dc99..25bb7f38a0 100644--- a/packages/views/locales/es/auth.json+++ b/packages/views/locales/es/auth.json@@ -31,7 +31,8 @@"resend_failed": "No se ha podido reenviar el código","code_invalid": "Código no válido o caducado","cli_auth_failed": "No se ha podido autorizar la CLI. Inicia sesión de nuevo.",- "session_expired": "Tu sesión ha caducado. Inicia sesión de nuevo para continuar."+ "session_expired": "Tu sesión ha caducado. Inicia sesión de nuevo para continuar.",+ "access_not_allowed": "Esta cuenta no tiene permiso para usar esta instancia. Inicia sesión con otra cuenta."},"web": {"prefer_desktop": "¿Prefieres la app de escritorio?",diff --git a/packages/views/locales/fr/auth.json b/packages/views/locales/fr/auth.jsonindex e7dbad1cea..1ab4c9557d 100644--- a/packages/views/locales/fr/auth.json+++ b/packages/views/locales/fr/auth.json@@ -31,7 +31,8 @@"resend_failed": "Échec du renvoi du code","code_invalid": "Code invalide ou expiré","cli_auth_failed": "Échec de l'autorisation du CLI. Veuillez vous reconnecter.",- "session_expired": "Votre session a expiré. Reconnectez-vous pour continuer."+ "session_expired": "Votre session a expiré. Reconnectez-vous pour continuer.",+ "access_not_allowed": "Ce compte n'est pas autorisé sur cette instance. Connectez-vous avec un autre compte."},"web": {"prefer_desktop": "Vous préférez l'application de bureau ?",diff --git a/packages/views/locales/ja/auth.json b/packages/views/locales/ja/auth.jsonindex 380e7a6c88..bac5cb22d6 100644--- a/packages/views/locales/ja/auth.json+++ b/packages/views/locales/ja/auth.json@@ -31,7 +31,8 @@"resend_failed": "コードを再送信できませんでした","code_invalid": "コードが無効または期限切れです","cli_auth_failed": "CLIを承認できませんでした。もう一度ログインしてください。",- "session_expired": "セッションの有効期限が切れました。もう一度サインインしてください。"+ "session_expired": "セッションの有効期限が切れました。もう一度サインインしてください。",+ "access_not_allowed": "このアカウントはこのインスタンスを利用できません。別のアカウントでサインインしてください。"},"web": {"prefer_desktop": "デスクトップアプリをご利用ですか?",diff --git a/packages/views/locales/ko/auth.json b/packages/views/locales/ko/auth.jsonindex 180d111632..bf93b29068 100644--- a/packages/views/locales/ko/auth.json+++ b/packages/views/locales/ko/auth.json@@ -31,7 +31,8 @@"resend_failed": "코드를 다시 보내지 못했습니다","code_invalid": "코드가 잘못되었거나 만료되었습니다","cli_auth_failed": "CLI 승인에 실패했습니다. 다시 로그인하세요.",- "session_expired": "세션이 만료되었습니다. 다시 로그인해 주세요."+ "session_expired": "세션이 만료되었습니다. 다시 로그인해 주세요.",+ "access_not_allowed": "이 계정은 이 인스턴스를 사용할 수 없습니다. 다른 계정으로 로그인해 주세요."},"web": {"prefer_desktop": "데스크톱 앱을 선호하시나요?",diff --git a/packages/views/locales/ru/auth.json b/packages/views/locales/ru/auth.jsonindex e1467151bc..4fdcfbecdc 100644--- a/packages/views/locales/ru/auth.json+++ b/packages/views/locales/ru/auth.json@@ -31,7 +31,8 @@"resend_failed": "Не удалось повторно отправить код","code_invalid": "Неверный или истёкший код","cli_auth_failed": "Не удалось авторизовать CLI. Пожалуйста, войдите снова.",- "session_expired": "Сессия истекла. Войдите снова, чтобы продолжить."+ "session_expired": "Сессия истекла. Войдите снова, чтобы продолжить.",+ "access_not_allowed": "Этой учётной записи запрещён доступ к этому экземпляру. Войдите с другой учётной записью."},"web": {"prefer_desktop": "Предпочитаете десктоп-приложение?",diff --git a/packages/views/locales/zh-Hans/auth.json b/packages/views/locales/zh-Hans/auth.jsonindex 9ebd1a9a8d..92a871b828 100644--- a/packages/views/locales/zh-Hans/auth.json+++ b/packages/views/locales/zh-Hans/auth.json@@ -31,7 +31,8 @@"resend_failed": "重新发送失败","code_invalid": "验证码无效或已过期","cli_auth_failed": "CLI 授权失败,请重新登录。",- "session_expired": "登录已过期,请重新登录。"+ "session_expired": "登录已过期,请重新登录。",+ "access_not_allowed": "此实例不允许该账号访问,请使用其他账号登录。"},"web": {"prefer_desktop": "更喜欢桌面端?",diff --git a/packages/views/locales/zh-Hant/auth.json b/packages/views/locales/zh-Hant/auth.jsonindex fcce5fe0cb..fbfa832e86 100644--- a/packages/views/locales/zh-Hant/auth.json+++ b/packages/views/locales/zh-Hant/auth.json@@ -31,7 +31,8 @@"resend_failed": "重新傳送失敗","code_invalid": "驗證碼無效或已過期","cli_auth_failed": "CLI 授權失敗,請重新登入。",- "session_expired": "登入已過期,請重新登入。"+ "session_expired": "登入已過期,請重新登入。",+ "access_not_allowed": "此例項不允許該帳號存取,請使用其他帳號登入。"},"web": {"prefer_desktop": "想用桌面應用?",diff --git a/server/cmd/server/access_allowlist.go b/server/cmd/server/access_allowlist.gonew file mode 100644index 0000000000..526e6ae89d--- /dev/null+++ b/server/cmd/server/access_allowlist.go@@ -0,0 +1,30 @@+package main++import (+ "context"+ "errors"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// accessAllowlistEmailLookup resolves the account email behind credentials+// that carry only a user ID. A missing user resolves to "" and is denied.+func accessAllowlistEmailLookup(queries *db.Queries) auth.UserEmailLookup {+ return func(ctx context.Context, userID string) (string, error) {+ id, err := util.ParseUUID(userID)+ if err != nil {+ return "", nil+ }+ user, err := queries.GetUser(ctx, id)+ if errors.Is(err, pgx.ErrNoRows) {+ return "", nil+ }+ if err != nil {+ return "", err+ }+ return user.Email, nil+ }+}diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex b8d791d417..7fdb9ad351 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -686,6 +686,13 @@ func main() {os.Exit(1)}+ accessAllowlist, err := auth.ParseAccessAllowlist(os.Getenv("ACCESS_ALLOWED_EMAILS"), accessAllowlistEmailLookup(queries))+ if err != nil {+ slog.Error("invalid ACCESS_ALLOWED_EMAILS", "error", err)+ os.Exit(1)+ }+ auth.SetAccessAllowlist(accessAllowlist)+r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{InboxReadMetrics: inboxReadMetrics,HTTPMetrics: httpMetrics,diff --git a/server/internal/auth/access_allowlist.go b/server/internal/auth/access_allowlist.gonew file mode 100644index 0000000000..4755ba6a0c--- /dev/null+++ b/server/internal/auth/access_allowlist.go@@ -0,0 +1,189 @@+package auth++import (+ "context"+ "errors"+ "fmt"+ "net/mail"+ "strings"+ "sync"+ "sync/atomic"+)++const (+ // AccessNotAllowedError is the client-facing message for a caller whose+ // account email is outside ACCESS_ALLOWED_EMAILS.+ AccessNotAllowedError = "this account is not allowed to access this instance"+ // AccessNotAllowedCode is the machine-readable `code` sent with that+ // message. Clients end the session on it rather than retrying, since the+ // credential is valid but will keep being refused.+ AccessNotAllowedCode = "access_not_allowed"+ // AccessNotAllowedBody is the JSON error body carrying both.+ AccessNotAllowedBody = `{"error":"` + AccessNotAllowedError + `","code":"` + AccessNotAllowedCode + `"}`+)++var ErrAccessNotAllowed = errors.New(AccessNotAllowedError)++// UserEmailLookup resolves a user ID to its account email. It returns+// ("", nil) when the user does not exist, which denies access.+type UserEmailLookup func(ctx context.Context, userID string) (string, error)++// AccessAllowlist restricts every authenticated request to accounts whose+// email matches an exact address ("[email protected]") or a domain wildcard+// ("*@example.com"). It is configured once at boot from ACCESS_ALLOWED_EMAILS.+type AccessAllowlist struct {+ emails map[string]struct{}+ domains map[string]struct{}+ lookup UserEmailLookup++ // Account emails are never updated and the list only changes on restart,+ // so a user's decision is fixed for the life of the process.+ decisions sync.Map // userID -> bool+}++// ParseAccessAllowlist parses a comma-separated list. An empty list returns+// nil, which allows everyone. Any malformed entry is an error so a typo+// cannot silently lock everyone out or leave the instance open. lookup+// resolves emails for credentials that carry only a user ID (PATs, task+// tokens, daemon tokens); without one those credentials are denied.+func ParseAccessAllowlist(raw string, lookup UserEmailLookup) (*AccessAllowlist, error) {+ a := &AccessAllowlist{emails: map[string]struct{}{}, domains: map[string]struct{}{}, lookup: lookup}+ for _, part := range strings.Split(raw, ",") {+ entry := strings.ToLower(strings.TrimSpace(part))+ if entry == "" {+ continue+ }+ local, domain, ok := strings.Cut(entry, "@")+ if !ok || !validAllowlistLocal(entry, local) || !validAllowlistDomain(domain) {+ return nil, fmt.Errorf("invalid entry %q: use [email protected] or *@example.com", strings.TrimSpace(part))+ }+ if local == "*" {+ a.domains[domain] = struct{}{}+ } else {+ a.emails[entry] = struct{}{}+ }+ }+ if len(a.emails) == 0 && len(a.domains) == 0 {+ return nil, nil+ }+ return a, nil+}++// validAllowlistLocal accepts "*" or a plain address local part. The whole+// entry must parse as a bare address and come back unchanged, which rejects+// display names, quoting, comments and embedded spaces.+func validAllowlistLocal(entry, local string) bool {+ if local == "*" {+ return true+ }+ if local == "" || strings.Contains(local, "*") {+ return false+ }+ addr, err := mail.ParseAddress(entry)+ return err == nil && addr.Address == entry+}++// validAllowlistDomain accepts a lowercase DNS name: dot-separated labels of+// letters, digits and inner hyphens. Internationalized domains must be given+// in their ASCII (xn--) form, which is what sign-in providers report.+func validAllowlistDomain(domain string) bool {+ if domain == "" || len(domain) > 253 {+ return false+ }+ for _, label := range strings.Split(domain, ".") {+ if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {+ return false+ }+ for _, c := range label {+ if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-' {+ return false+ }+ }+ }+ return true+}++// AllowsEmail reports whether email matches the list. A nil list allows all.+func (a *AccessAllowlist) AllowsEmail(email string) bool {+ if a == nil {+ return true+ }+ email = strings.ToLower(strings.TrimSpace(email))+ if email == "" {+ return false+ }+ if _, ok := a.emails[email]; ok {+ return true+ }+ if at := strings.LastIndex(email, "@"); at > 0 {+ _, ok := a.domains[email[at+1:]]+ return ok+ }+ return false+}++func (a *AccessAllowlist) checkUser(ctx context.Context, userID, email string) error {+ if a == nil {+ return nil+ }+ if email != "" {+ if a.AllowsEmail(email) {+ return nil+ }+ return ErrAccessNotAllowed+ }+ userID = strings.ToLower(strings.TrimSpace(userID))+ if userID == "" {+ return ErrAccessNotAllowed+ }+ if allowed, ok := a.decisions.Load(userID); ok {+ if allowed.(bool) {+ return nil+ }+ return ErrAccessNotAllowed+ }+ if a.lookup == nil {+ return ErrAccessNotAllowed+ }+ resolved, err := a.lookup(ctx, userID)+ if err != nil {+ return fmt.Errorf("resolve user email for access allowlist: %w", err)+ }+ allowed := a.AllowsEmail(resolved)+ a.decisions.Store(userID, allowed)+ if allowed {+ return nil+ }+ return ErrAccessNotAllowed+}++var activeAccessAllowlist atomic.Pointer[AccessAllowlist]++// SetAccessAllowlist installs the process-wide allowlist. Passing a nil list+// disables the gate.+func SetAccessAllowlist(a *AccessAllowlist) {+ activeAccessAllowlist.Store(a)+}++// IsEmailAccessAllowed reports whether an email may sign in or use the API.+func IsEmailAccessAllowed(email string) bool {+ return activeAccessAllowlist.Load().AllowsEmail(email)+}++// CheckUserAccess returns nil when the user may call the API,+// ErrAccessNotAllowed when the allowlist excludes them, or a lookup error.+// email is used directly when the credential carries it (session JWTs);+// otherwise the email is resolved from userID.+func CheckUserAccess(ctx context.Context, userID, email string) error {+ return activeAccessAllowlist.Load().checkUser(ctx, userID, email)+}++// CheckAccountAccess enforces both the temporary disabled-user denylist and+// ACCESS_ALLOWED_EMAILS. It returns ErrTemporarilyDisabledUser,+// ErrAccessNotAllowed, a lookup error, or nil.+func CheckAccountAccess(ctx context.Context, userID, email string) error {+ if IsTemporarilyDisabledUser(userID, email) {+ return ErrTemporarilyDisabledUser+ }+ return CheckUserAccess(ctx, userID, email)+}diff --git a/server/internal/auth/access_allowlist_test.go b/server/internal/auth/access_allowlist_test.gonew file mode 100644index 0000000000..b858b8c368--- /dev/null+++ b/server/internal/auth/access_allowlist_test.go@@ -0,0 +1,175 @@+package auth++import (+ "context"+ "errors"+ "testing"+)++func TestParseAccessAllowlist(t *testing.T) {+ empty, err := ParseAccessAllowlist(" , ", nil)+ if err != nil || empty != nil {+ t.Fatalf("blank list must disable the gate, got %v, %v", empty, err)+ }+ for _, bad := range []string{+ "devv.ai", "@devv.ai", "*@", "a*@devv.ai", "*@*.devv.ai", "a@[email protected]", "*",+ // Typos inside an otherwise well-formed entry must not start an+ // instance that then refuses everyone.+ "*@dev v.ai", "*@devv..ai", "*@.devv.ai", "*@devv.ai.", "*@-devv.ai", "*@devv_ai.com",+ "al [email protected]", "alice@dev v.ai", "alice@devv,ai", "Alice <[email protected]>", `"a b"@devv.ai`,+ } {+ if _, err := ParseAccessAllowlist("[email protected],"+bad, nil); err == nil {+ t.Errorf("expected %q to be rejected", bad)+ }+ }+ for _, good := range []string{"*@devv.ai", "*@sub.devv.ai", "*@xn--bcher-kva.example", "[email protected]", "o'[email protected]", "admin@localhost"} {+ if _, err := ParseAccessAllowlist(good, nil); err != nil {+ t.Errorf("expected %q to be accepted, got %v", good, err)+ }+ }+}++func TestAccessAllowlistAllowsEmail(t *testing.T) {+ a, err := ParseAccessAllowlist(" *@Devv.ai , [email protected] ", nil)+ if err != nil {+ t.Fatal(err)+ }+ cases := map[string]bool{+ "[email protected]": true,+ " [email protected] ": true,+ "[email protected]": true,+ "[email protected]": true,+ "[email protected]": false,+ "[email protected]": false,+ "[email protected]": false,+ "devv.ai": false,+ "": false,+ }+ for email, want := range cases {+ if got := a.AllowsEmail(email); got != want {+ t.Errorf("AllowsEmail(%q) = %t, want %t", email, got, want)+ }+ }+ var none *AccessAllowlist+ if !none.AllowsEmail("[email protected]") {+ t.Fatal("a nil allowlist must allow everyone")+ }+}++func TestCheckUserAccess(t *testing.T) {+ t.Cleanup(func() { SetAccessAllowlist(nil) })++ if err := CheckUserAccess(context.Background(), "u1", ""); err != nil {+ t.Fatalf("no allowlist must allow everyone, got %v", err)+ }++ lookups := map[string]int{}+ lookupErr := errors.New("db down")+ failing := true+ a, err := ParseAccessAllowlist("*@devv.ai", func(_ context.Context, userID string) (string, error) {+ lookups[userID]+++ switch userID {+ case "flaky":+ if failing {+ return "", lookupErr+ }+ return "[email protected]", nil+ case "in":+ return "[email protected]", nil+ case "out":+ return "[email protected]", nil+ }+ return "", nil+ })+ if err != nil {+ t.Fatal(err)+ }+ SetAccessAllowlist(a)+ ctx := context.Background()++ if err := CheckUserAccess(ctx, "jwt-user", "[email protected]"); err != nil {+ t.Fatalf("email claim in list must pass, got %v", err)+ }+ if err := CheckUserAccess(ctx, "jwt-user", "[email protected]"); !errors.Is(err, ErrAccessNotAllowed) {+ t.Fatalf("email claim outside list must be denied, got %v", err)+ }+ if lookups["jwt-user"] != 0 {+ t.Fatal("a credential carrying an email must not trigger a lookup")+ }++ for range 2 {+ if err := CheckUserAccess(ctx, "in", ""); err != nil {+ t.Fatalf("listed user must pass, got %v", err)+ }+ if err := CheckUserAccess(ctx, "out", ""); !errors.Is(err, ErrAccessNotAllowed) {+ t.Fatalf("unlisted user must be denied, got %v", err)+ }+ }+ if lookups["in"] != 1 || lookups["out"] != 1 {+ t.Fatalf("decisions must be cached per user, lookups=%v", lookups)+ }+ if err := CheckUserAccess(ctx, "deleted", ""); !errors.Is(err, ErrAccessNotAllowed) {+ t.Fatalf("missing user must be denied, got %v", err)+ }++ if err := CheckUserAccess(ctx, "flaky", ""); !errors.Is(err, lookupErr) {+ t.Fatalf("lookup failure must surface, got %v", err)+ }+ failing = false+ if err := CheckUserAccess(ctx, "flaky", ""); err != nil {+ t.Fatalf("lookup failures must not be cached, got %v", err)+ }+}++func TestCheckAccountAccess(t *testing.T) {+ t.Cleanup(func() { SetAccessAllowlist(nil) })+ ctx := context.Background()++ var disabledID string+ for id := range temporarilyDisabledUserIDs {+ disabledID = id+ break+ }+ var disabledEmail string+ for email := range temporarilyDisabledUserEmails {+ disabledEmail = email+ break+ }++ if err := CheckAccountAccess(ctx, disabledID, ""); !errors.Is(err, ErrTemporarilyDisabledUser) {+ t.Fatalf("disabled user ID without allowlist must be denied, got %v", err)+ }+ if err := CheckAccountAccess(ctx, "other-user", disabledEmail); !errors.Is(err, ErrTemporarilyDisabledUser) {+ t.Fatalf("disabled user email without allowlist must be denied, got %v", err)+ }++ lookupErr := errors.New("db down")+ a, err := ParseAccessAllowlist("*@devv.ai", func(_ context.Context, userID string) (string, error) {+ switch userID {+ case "in":+ return "[email protected]", nil+ case "out":+ return "[email protected]", nil+ case "flaky":+ return "", lookupErr+ }+ return "", nil+ })+ if err != nil {+ t.Fatal(err)+ }+ SetAccessAllowlist(a)++ if err := CheckAccountAccess(ctx, disabledID, "[email protected]"); !errors.Is(err, ErrTemporarilyDisabledUser) {+ t.Fatalf("disabled user must stay denied even with listed email, got %v", err)+ }+ if err := CheckAccountAccess(ctx, "in", ""); err != nil {+ t.Fatalf("listed active user must pass, got %v", err)+ }+ if err := CheckAccountAccess(ctx, "out", ""); !errors.Is(err, ErrAccessNotAllowed) {+ t.Fatalf("unlisted user must be denied, got %v", err)+ }+ if err := CheckAccountAccess(ctx, "flaky", ""); !errors.Is(err, lookupErr) {+ t.Fatalf("lookup failure must surface, got %v", err)+ }+}diff --git a/server/internal/connectedapps/gateway.go b/server/internal/connectedapps/gateway.goindex 1fae7a63fe..6031d43099 100644--- a/server/internal/connectedapps/gateway.go+++ b/server/internal/connectedapps/gateway.go@@ -11,6 +11,7 @@ import ("strings""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/runtimeapps""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -149,6 +150,14 @@ func (s *Service) loadRun(ctx context.Context, taskID string) (*run, error) {if !s.mayRun(ctx, task, agent) {return nil, ErrNoLongerAllowed}+ // The gateway authenticates with its own run token, not through the API+ // auth middleware, so ACCESS_ALLOWED_EMAILS is applied to the person the+ // run acts for here.+ if task.OriginatorUserID.Valid {+ if err := auth.CheckUserAccess(ctx, util.UUIDToString(task.OriginatorUserID), ""); err != nil {+ return nil, err+ }+ }apps, err := s.q.ListAgentApps(ctx, agent.ID)if err != nil {return nil, errdiff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.goindex f385365916..73c128e220 100644--- a/server/internal/handler/auth.go+++ b/server/internal/handler/auth.go@@ -204,6 +204,9 @@ func (h *Handler) findOrCreateUser(ctx context.Context, email string) (user db.Uif auth.IsTemporarilyDisabledUserEmail(email) {return db.User{}, false, auth.ErrTemporarilyDisabledUser}+ if !auth.IsEmailAccessAllowed(email) {+ return db.User{}, false, ErrEmailNotAllowed+ }user, err = h.Queries.GetUserByEmail(ctx, email)isNew = isNotFound(err)@@ -333,6 +336,10 @@ func (h *Handler) SendCode(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusForbidden, auth.TemporarilyDisabledUserError)return}+ if !auth.IsEmailAccessAllowed(email) {+ writeError(w, http.StatusForbidden, ErrEmailNotAllowed.Error())+ return+ }// Check signup restrictions before sending magic linkexistingUser, err := h.Queries.GetUserByEmail(r.Context(), email)@@ -427,6 +434,10 @@ func (h *Handler) VerifyCode(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusForbidden, auth.TemporarilyDisabledUserError)return}+ if !auth.IsEmailAccessAllowed(email) {+ writeError(w, http.StatusForbidden, ErrEmailNotAllowed.Error())+ return+ }dbCode, err := h.Queries.GetLatestVerificationCode(r.Context(), email)if err != nil {diff --git a/server/internal/handler/auth_access_allowlist_test.go b/server/internal/handler/auth_access_allowlist_test.gonew file mode 100644index 0000000000..6e580e8cd8--- /dev/null+++ b/server/internal/handler/auth_access_allowlist_test.go@@ -0,0 +1,139 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestLoginAccessAllowlist(t *testing.T) {+ t.Setenv("RESEND_API_KEY", "")+ t.Setenv("SMTP_HOST", "")+ a, err := auth.ParseAccessAllowlist("*@allowed.example,[email protected]", nil)+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })++ h := *testHandler+ // Signup itself is open: only the access allowlist decides.+ h.cfg = Config{AllowSignup: true}+ h.EmailService = service.NewEmailService()++ for email, want := range map[string]int{+ "[email protected]": http.StatusOK,+ "[email protected]": http.StatusOK,+ "[email protected]": http.StatusForbidden,+ // Existing accounts are gated too, not only new signups.+ handlerTestEmail: http.StatusForbidden,+ } {+ t.Run(email, func(t *testing.T) {+ dbfx.Cleanup(t, `DELETE FROM verification_code WHERE email = $1`, email)+ req := testutil.JSONRequest(http.MethodPost, "/auth/send-code", map[string]string{"email": email})+ testutil.Call(t, h.SendCode, req).Want(want)+ if want != http.StatusOK {+ if n := dbfx.Count(t, `SELECT count(*) FROM verification_code WHERE email = $1`, email); n != 0 {+ t.Fatal("a rejected email must not receive a code")+ }+ }+ })+ }++ const outsider = "[email protected]"+ dbfx.Cleanup(t, `DELETE FROM "user" WHERE email = $1`, outsider)+ if _, _, err := h.findOrCreateUser(context.Background(), outsider); !errors.Is(err, ErrEmailNotAllowed) {+ t.Fatalf("expected ErrEmailNotAllowed, got %v", err)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM "user" WHERE email = $1`, outsider); n != 0 {+ t.Fatal("a rejected email must not create an account")+ }+}++func TestClaimTask_AccessAllowlistFailsUnlistedOriginator(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })++ ctx := context.Background()+ rt := createClaimReclaimRuntime(t, ctx, "Allowlist claim rt")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, rt, "Allowlist claim agent")+ agent2ID, issue2ID := createClaimReclaimAgentAndIssue(t, ctx, rt, "Allowlist claim agent 2")++ const (+ outsiderID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"+ flakyID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"+ )++ unlistedTaskID := seedQueuedIssueTask(t, ctx, agentID, rt, issueID)+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id = $1, accountable_user_id = $1 WHERE id = $2`, outsiderID, unlistedTaskID)++ allowedTaskID := seedQueuedIssueTask(t, ctx, agent2ID, rt, issue2ID)+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id = $1, accountable_user_id = $1 WHERE id = $2`, testUserID, allowedTaskID)++ a, err := auth.ParseAccessAllowlist(handlerTestEmail, func(_ context.Context, userID string) (string, error) {+ switch userID {+ case testUserID:+ return handlerTestEmail, nil+ case outsiderID:+ return "[email protected]", nil+ case flakyID:+ return "", errors.New("database is down")+ }+ return "", nil+ })+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)++ w := postBatchClaim(t, testWorkspaceID, []string{rt}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp batchClaimReceiptResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 1 || resp.Tasks[0].ID != allowedTaskID {+ t.Fatalf("claimed = %+v, want only allowed task %s", resp.Tasks, allowedTaskID)+ }++ var unlistedStatus, unlistedErr string+ if err := testPool.QueryRow(ctx, `SELECT status, COALESCE(error, '') FROM agent_task_queue WHERE id = $1`, unlistedTaskID).Scan(&unlistedStatus, &unlistedErr); err != nil {+ t.Fatalf("read unlisted task: %v", err)+ }+ if unlistedStatus != "failed" || unlistedErr != auth.AccessNotAllowedError {+ t.Fatalf("unlisted task status=%q err=%q, want failed/%q", unlistedStatus, unlistedErr, auth.AccessNotAllowedError)+ }++ // Lookup errors must requeue the task rather than permanently failing it.+ flakyTaskID := seedQueuedIssueTask(t, ctx, agentID, rt, issueID)+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id = $1, accountable_user_id = $1 WHERE id = $2`, flakyID, flakyTaskID)++ w = postBatchClaim(t, testWorkspaceID, []string{rt}, 5)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200 on lookup failure batch, got %d: %s", w.Code, w.Body.String())+ }+ resp = batchClaimReceiptResponse{}+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if len(resp.Tasks) != 0 {+ t.Fatalf("flaky lookup must not dispatch task, got %+v", resp.Tasks)+ }+ var flakyStatus string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, flakyTaskID).Scan(&flakyStatus); err != nil {+ t.Fatalf("read flaky task: %v", err)+ }+ if flakyStatus != "queued" {+ t.Fatalf("flaky task status = %q, want queued (requeued)", flakyStatus)+ }+}diff --git a/server/internal/handler/connected_apps_access_test.go b/server/internal/handler/connected_apps_access_test.goindex cfbce08342..3dcec6dff0 100644--- a/server/internal/handler/connected_apps_access_test.go+++ b/server/internal/handler/connected_apps_access_test.go@@ -7,6 +7,7 @@ import ("testing""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/connectedapps""github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -65,6 +66,44 @@ func TestConnectedApps_GatewayRechecksAccess(t *testing.T) {}}+// The gateway authenticates with its own run token, so it must apply+// ACCESS_ALLOWED_EMAILS to the run's originator itself: a run started before+// the originator was removed from the list stops reaching connected apps.+func TestConnectedApps_GatewayAppliesAccessAllowlist(t *testing.T) {+ f := newAppsFixture(t)+ f.executionAccount(t, "team")+ if w := f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "team", "level": "write"}}); w.Code != http.StatusOK {+ t.Fatalf("attach: %d %s", w.Code, w.Body.String())+ }+ lookup := func(ctx context.Context, userID string) (string, error) {+ user, err := f.h.Queries.GetUser(ctx, parseUUID(userID))+ if err != nil {+ return "", err+ }+ return user.Email, nil+ }+ setAllowlist := func(raw string) {+ a, err := auth.ParseAccessAllowlist(raw, lookup)+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)+ }+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })++ setAllowlist("*@multica.ai")+ if code, response, isErr := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); code != http.StatusOK || isErr {+ t.Fatalf("listed originator: %d %s", code, response)+ }+ setAllowlist("*@allowed.example")+ if code, response, _ := f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_SEND_EMAIL"}); code != http.StatusUnauthorized {+ t.Fatalf("unlisted originator: %d %s", code, response)+ }+ if n := len(f.sdk.executions()); n != 1 {+ t.Fatalf("executions = %d, want only the listed originator's send", n)+ }+}+func TestConnectedApps_SystemRunRechecksInvocationPermission(t *testing.T) {for _, accountable := range []string{"none", "owner", "departed_member"} {for _, revoke := range []string{"private", "member_only", "no_workspace_grant"} {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 2089cc158b..1206a0f9cf 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3013,6 +3013,19 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu// to leader role; the quick-create branch below re-populates resp.SquadID// exclusively when qc.SquadID is present.resp.SquadID = ""+ if task.OriginatorUserID.Valid {+ originatorID := uuidToString(task.OriginatorUserID)+ if err := auth.CheckAccountAccess(r.Context(), originatorID, ""); err != nil {+ switch {+ case errors.Is(err, auth.ErrTemporarilyDisabledUser):+ return resp, nil, nil, 0, 0, h.failClaimedTaskBeforeLaunch(r.Context(), task, auth.TemporarilyDisabledUserError, taskfailure.ReasonInvalidTaskIdentity, "account_disabled", http.StatusConflict, auth.TemporarilyDisabledUserError)+ case errors.Is(err, auth.ErrAccessNotAllowed):+ return resp, nil, nil, 0, 0, h.failClaimedTaskBeforeLaunch(r.Context(), task, auth.AccessNotAllowedError, taskfailure.ReasonInvalidTaskIdentity, auth.AccessNotAllowedCode, http.StatusConflict, auth.AccessNotAllowedError)+ default:+ return resp, nil, nil, 0, 0, h.rejectClaimSourceLoad(r.Context(), task, err, "access_allowlist", originatorID)+ }+ }+ }if err := (&service.IssueWakeupService{Tasks: h.TaskService}).CheckClaim(r.Context(), *task); err != nil {if !errors.Is(err, service.ErrWakeupForbidden) {return resp, nil, nil, 0, 0, h.rejectClaimSourceLoad(r.Context(), task, err, "wakeup", resp.WakeupID)diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.goindex d94764dc7b..312f5b3120 100644--- a/server/internal/handler/plugin_action.go+++ b/server/internal/handler/plugin_action.go@@ -4,6 +4,7 @@ import ("encoding/json""errors""fmt"+ "log/slog""net/http""strconv""strings"@@ -11,6 +12,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/projectaccess""github.com/multica-ai/multica/server/internal/service"@@ -220,6 +222,17 @@ func (h *Handler) pluginTokenCaller(w http.ResponseWriter, r *http.Request, toke// person's membership TODAY. Re-checking here means revoking someone's// access takes effect on a token already in flight.if memberUserID.Valid {+ // Plugin bearer tokens skip the API auth middleware, so the+ // ACCESS_ALLOWED_EMAILS gate it applies is repeated here.+ if err := auth.CheckUserAccess(r.Context(), uuidToString(memberUserID), ""); err != nil {+ if errors.Is(err, auth.ErrAccessNotAllowed) {+ publicapiv1.WriteProblem(w, r, http.StatusForbidden, auth.AccessNotAllowedCode, auth.AccessNotAllowedError)+ } else {+ slog.Error("plugin callback: access allowlist check failed", "user_id", uuidToString(memberUserID), "error", err)+ publicapiv1.WriteProblem(w, r, http.StatusServiceUnavailable, "access_check_failed", "failed to verify account access")+ }+ return service.PluginActionCaller{}, pluginActor{}, false+ }member, err := h.getWorkspaceMember(r.Context(), uuidToString(memberUserID), uuidToString(caller.WorkspaceID))if err != nil {publicapiv1.WriteProblem(w, r, http.StatusForbidden, "actor_membership_revoked", "the user this callback acts for is no longer a member")diff --git a/server/internal/handler/plugin_callback_test.go b/server/internal/handler/plugin_callback_test.goindex a859055933..e7116d57a3 100644--- a/server/internal/handler/plugin_callback_test.go+++ b/server/internal/handler/plugin_callback_test.go@@ -9,6 +9,7 @@ import ("testing""github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/plugincontract"@@ -300,3 +301,41 @@ func TestCallbackTokenWithoutAnIssueIsNotNarrowed(t *testing.T) {t.Fatalf("an unscoped grant must still reach the workspace: status=%d body=%s", recorder.Code, recorder.Body.String())}}++// Plugin bearer tokens skip the API auth middleware. A callback acting for a+// person outside ACCESS_ALLOWED_EMAILS is refused here instead; one acting as+// the plugin itself has no person behind it and is unaffected.+func TestCallbackForAMemberOutsideAccessAllowlistIsRefused(t *testing.T) {+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ withCallbackTokens(t)+ installationID := installHookPlugin(t)+ issueID := createTestIssue(t, "Callback access allowlist", "todo", "none")++ allowlist, err := auth.ParseAccessAllowlist("*@allowed.example", func(context.Context, string) (string, error) {+ return handlerTestEmail, nil+ })+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(allowlist)+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })++ post := func(actor service.HookActor) *httptest.ResponseRecorder {+ recorder := httptest.NewRecorder()+ testHandler.CreatePluginComment(recorder, callbackRequest(issueCallbackToken(t, installationID, actor), http.MethodPost,+ "/v1/issues/"+issueID+"/comments",+ map[string]any{"content": "posted by a hook"},+ map[string]string{"issue_ref": issueID}))+ return recorder+ }+ if recorder := post(service.HookActor{Type: "member", ID: parseUUID(testUserID)}); recorder.Code != http.StatusForbidden {+ t.Fatalf("member outside the allowlist: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ if recorder := post(service.HookActor{Type: "plugin", ID: parseUUID(installationID)}); recorder.Code != http.StatusCreated {+ t.Fatalf("plugin actor: status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ if comment := latestComment(t, issueID); comment.AuthorType != "plugin" {+ t.Fatalf("only the plugin's comment may land, got author_type=%q", comment.AuthorType)+ }+}diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.goindex cf4e349bb2..13b29cc9f9 100644--- a/server/internal/integrations/channel/engine/resolvers.go+++ b/server/internal/integrations/channel/engine/resolvers.go@@ -49,6 +49,7 @@ const (DropReasonRevokedInstallation DropReason = "revoked_installation"DropReasonInvalidEvent DropReason = "invalid_event"DropReasonInvokeDenied DropReason = "invocation_not_allowed"+ DropReasonAccessNotAllowed DropReason = "access_not_allowed")// Result is the typed verdict the Router produces for one inbound message,diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 8a7c81df88..5dd69cc2e8 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -12,6 +12,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"@@ -389,6 +390,16 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe}}+ // 4a. Instance access gate: enforce temporary account disables and+ // ACCESS_ALLOWED_EMAILS before invoke permission, /help, /issue,+ // session creation, media resolution, or task enqueue.+ if err := auth.CheckAccountAccess(ctx, util.UUIDToString(identity.UserID), ""); err != nil {+ if errors.Is(err, auth.ErrAccessNotAllowed) || errors.Is(err, auth.ErrTemporarilyDisabledUser) {+ return r.drop(ctx, set, msg, inst.ID, DropReasonAccessNotAllowed), finalizeMark, nil+ }+ return Result{}, finalizeRelease, fmt.Errorf("check user access: %w", err)+ }+// 4b. Invoke permission (MUL-3963): the same verdict the web chat applies// before it opens a session. It judges the SENDER, never the installer// who owns a group's route, and it runs before anything is stored — sodiff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 1b809a2d62..ce31302838 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -14,6 +14,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"@@ -758,6 +759,135 @@ func TestRouter_NonMember_Drops(t *testing.T) {}}+func TestRouter_AccessAllowlist_RefusesUnlistedSenderBeforeAnythingIsStored(t *testing.T) {+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })+ const (+ allowedID = "44444444-4444-4444-4444-444444444444"+ outsiderID = "77777777-7777-7777-7777-777777777777"+ )+ a, err := auth.ParseAccessAllowlist("*@allowed.example", func(_ context.Context, userID string) (string, error) {+ switch userID {+ case allowedID:+ return "[email protected]", nil+ case outsiderID:+ return "[email protected]", nil+ }+ return "", nil+ })+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)++ for _, tc := range []struct {+ name string+ text string+ }{+ {name: "chat_message", text: "run my agent"},+ {name: "issue_command", text: "/issue Fix login"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ h := newHarness(t)+ h.ident.id = ResolvedIdentity{UserID: uuidFromString(t, outsiderID)}+ h.binder.parseIssue = true+ msg := p2pMessage(t)+ msg.Text = tc.text+ msg.CommandText = tc.text++ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatalf("access refusal must be a product drop, got err: %v", err)+ }+ if r, _ := h.audit.last(); r != DropReasonAccessNotAllowed {+ t.Fatalf("audit = %q, want %q", r, DropReasonAccessNotAllowed)+ }+ if h.dedup.marks() != 1 || h.dedup.releases() != 0 {+ t.Fatalf("marks=%d releases=%d, want 1/0", h.dedup.marks(), h.dedup.releases())+ }+ h.binder.mu.Lock()+ ensures, starts := h.binder.ensureCalls, h.binder.startCalls+ h.binder.mu.Unlock()+ if ensures != 0 || starts != 0 {+ t.Fatalf("unlisted sender must not create or ensure a chat session (ensures=%d starts=%d)", ensures, starts)+ }+ if h.issues.called {+ t.Fatal("unlisted sender must not create an issue")+ }+ h.tasks.mu.Lock()+ taskCalled := h.tasks.called || h.tasks.callCount > 0 || h.tasks.prepared+ h.tasks.mu.Unlock()+ if taskCalled {+ t.Fatal("unlisted sender must not enqueue an agent task")+ }+ if h.media.calls() != 0 {+ t.Fatal("unlisted sender must not resolve media")+ }+ })+ }++ // Listed sender continues normally.+ h := newHarness(t)+ h.ident.id = ResolvedIdentity{UserID: uuidFromString(t, allowedID)}+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("listed sender failed: %v", err)+ }+ if _, dropped := h.audit.last(); dropped {+ t.Fatal("listed sender must not be dropped")+ }+ h.binder.mu.Lock()+ ensures := h.binder.ensureCalls+ h.binder.mu.Unlock()+ if ensures != 1 {+ t.Fatalf("listed sender should proceed to session ensure, got %d", ensures)+ }+}++func TestRouter_TemporarilyDisabledSender_Drops(t *testing.T) {+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })+ h := newHarness(t)+ h.ident.id = ResolvedIdentity{UserID: uuidFromString(t, "514492f7-b30f-4147-bd33-c0e8ce5d6d4f")}++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if r, _ := h.audit.last(); r != DropReasonAccessNotAllowed {+ t.Fatalf("audit = %q, want %q", r, DropReasonAccessNotAllowed)+ }+ if h.dedup.marks() != 1 {+ t.Fatalf("disabled sender drop must mark dedup, got %d", h.dedup.marks())+ }+ h.binder.mu.Lock()+ ensures := h.binder.ensureCalls+ h.binder.mu.Unlock()+ if ensures != 0 || h.issues.called || h.media.calls() != 0 {+ t.Fatal("disabled sender must not create session, issue, or resolve media")+ }+}++func TestRouter_AccessCheckLookupError_Releases(t *testing.T) {+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })+ a, err := auth.ParseAccessAllowlist("*@allowed.example", func(context.Context, string) (string, error) {+ return "", errors.New("database is down")+ })+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)++ h := newHarness(t)+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err == nil {+ t.Fatal("failed access allowlist lookup must surface as an error")+ }+ if h.dedup.marks() != 0 || h.dedup.releases() != 1 {+ t.Fatalf("marks=%d releases=%d, want 0/1", h.dedup.marks(), h.dedup.releases())+ }+ h.binder.mu.Lock()+ ensures := h.binder.ensureCalls+ h.binder.mu.Unlock()+ if ensures != 0 || h.issues.called {+ t.Fatal("failed access lookup must not create session or issue")+ }+}+func TestRouter_EnsureSessionError_Releases(t *testing.T) {h := newHarness(t)h.binder.ensureErr = errors.New("db down")diff --git a/server/internal/integrations/slack/slash_command.go b/server/internal/integrations/slack/slash_command.goindex 14e18c6e0a..e156dc5bc4 100644--- a/server/internal/integrations/slack/slash_command.go+++ b/server/internal/integrations/slack/slash_command.go@@ -11,7 +11,9 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/slack-go/slack"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -50,6 +52,8 @@ const (slashUsageText = "Tell me what to file, e.g. `/issue the login button does nothing on Safari`."slashQueuedText = "✅ On it — I'm turning that into an issue. You'll get a Multica notification when it's ready."slashNotMemberText = "You're not a member of this Multica workspace, so I can't file an issue for you."+ slashAccessNotAllowedText = "This account is not allowed to access this Multica instance."+ slashAccountDisabledText = "This Multica account is disabled."slashLinkAccountFallback = "Link your Slack account to Multica first, then try `/issue` again."slashInternalErrorText = "⚠️ Something went wrong creating the issue. Please try again."slashDisabledText = "This Slack app isn't connected to Multica (or was disconnected). Ask a workspace admin to reconnect it."@@ -189,6 +193,10 @@ func (p *SlashCommandProcessor) processControl(ctx context.Context, cmd slack.Slreturn p.bindingText(ctx, inst, cmd.UserID)case errors.Is(err, engine.ErrSenderNotMember):return slashNotMemberText+ case errors.Is(err, auth.ErrAccessNotAllowed):+ return slashAccessNotAllowedText+ case errors.Is(err, auth.ErrTemporarilyDisabledUser):+ return slashAccountDisabledTextdefault:return slashInternalErrorText}@@ -262,6 +270,10 @@ func (p *SlashCommandProcessor) process(ctx context.Context, cmd slack.SlashCommreturn p.bindingText(ctx, inst, cmd.UserID)case errors.Is(err, engine.ErrSenderNotMember):return slashNotMemberText+ case errors.Is(err, auth.ErrAccessNotAllowed):+ return slashAccessNotAllowedText+ case errors.Is(err, auth.ErrTemporarilyDisabledUser):+ return slashAccountDisabledTextdefault:p.logger.WarnContext(ctx, "slack slash command: resolve user failed","app_id", cmd.APIAppID, "error", err)@@ -343,6 +355,9 @@ func (p *SlashCommandProcessor) resolveUser(ctx context.Context, inst engine.Res}return pgtype.UUID{}, err}+ if err := auth.CheckAccountAccess(ctx, util.UUIDToString(binding.MulticaUserID), ""); err != nil {+ return pgtype.UUID{}, err+ }return binding.MulticaUserID, nil}diff --git a/server/internal/integrations/slack/slash_command_test.go b/server/internal/integrations/slack/slash_command_test.goindex 4003acc315..5e24b0c29b 100644--- a/server/internal/integrations/slack/slash_command_test.go+++ b/server/internal/integrations/slack/slash_command_test.go@@ -11,7 +11,9 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/slack-go/slack"+ "github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -252,6 +254,103 @@ func TestSlashHandle_NonMemberDropped(t *testing.T) {}}+func TestSlashHandle_AccessAllowlistRefusesUnlistedUser(t *testing.T) {+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })+ allowedUID := slashTestUUID(9)+ outsiderUID := slashTestUUID(10)+ a, err := auth.ParseAccessAllowlist("*@allowed.example", func(_ context.Context, userID string) (string, error) {+ switch userID {+ case util.UUIDToString(allowedUID):+ return "[email protected]", nil+ case util.UUIDToString(outsiderUID):+ return "[email protected]", nil+ }+ return "", nil+ })+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)++ // Unlisted user cannot file /issue.+ q := &fakeSlashQueries{+ inst: activeSlashInstallation(),+ binding: db.ChannelUserBinding{MulticaUserID: outsiderUID},+ }+ tasks := &fakeQuickCreate{}+ starter := &fakeSlashControlStarter{}+ p, captured, _ := newTestSlashProcessor(q, tasks, &fakeBindingMinter{})+ p.control = starter++ p.Handle(context.Background(), issueSlashCmd())+ if tasks.calls != 0 {+ t.Fatalf("unlisted user must not enqueue /issue, got %d calls", tasks.calls)+ }+ if *captured != slashAccessNotAllowedText {+ t.Fatalf("reply = %q, want %q", *captured, slashAccessNotAllowedText)+ }++ // Unlisted user cannot run control commands (/new) either.+ cmd := issueSlashCmd()+ cmd.Command, cmd.ChannelID, cmd.Text = "/new", "D1", "new topic"+ p.HandleEnvelope(context.Background(), cmd, "env-unlisted")+ if starter.newCalls != 0 {+ t.Fatalf("unlisted user must not start a chat, got %d calls", starter.newCalls)+ }+ if *captured != slashAccessNotAllowedText {+ t.Fatalf("control reply = %q, want %q", *captured, slashAccessNotAllowedText)+ }++ // Listed user succeeds.+ q.binding.MulticaUserID = allowedUID+ p.Handle(context.Background(), issueSlashCmd())+ if tasks.calls != 1 || *captured != slashQueuedText {+ t.Fatalf("listed user: calls=%d reply=%q", tasks.calls, *captured)+ }+}++func TestSlashHandle_TemporarilyDisabledUserRefused(t *testing.T) {+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })+ var disabledUID pgtype.UUID+ if err := disabledUID.Scan("514492f7-b30f-4147-bd33-c0e8ce5d6d4f"); err != nil {+ t.Fatal(err)+ }+ q := &fakeSlashQueries{+ inst: activeSlashInstallation(),+ binding: db.ChannelUserBinding{MulticaUserID: disabledUID},+ }+ tasks := &fakeQuickCreate{}+ p, captured, _ := newTestSlashProcessor(q, tasks, &fakeBindingMinter{})++ p.Handle(context.Background(), issueSlashCmd())+ if tasks.calls != 0 || *captured != slashAccountDisabledText {+ t.Fatalf("disabled user: calls=%d reply=%q", tasks.calls, *captured)+ }+}++func TestSlashHandle_AccessCheckLookupErrorIsInternalError(t *testing.T) {+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })+ a, err := auth.ParseAccessAllowlist("*@allowed.example", func(context.Context, string) (string, error) {+ return "", errors.New("db down")+ })+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)++ q := &fakeSlashQueries{+ inst: activeSlashInstallation(),+ binding: db.ChannelUserBinding{MulticaUserID: slashTestUUID(9)},+ }+ tasks := &fakeQuickCreate{}+ p, captured, _ := newTestSlashProcessor(q, tasks, &fakeBindingMinter{})++ p.Handle(context.Background(), issueSlashCmd())+ if tasks.calls != 0 || *captured != slashInternalErrorText {+ t.Fatalf("lookup error: calls=%d reply=%q", tasks.calls, *captured)+ }+}+func TestSlashHandle_InactiveInstallation(t *testing.T) {inst := activeSlashInstallation()inst.Status = "revoked"diff --git a/server/internal/middleware/access_allowlist_test.go b/server/internal/middleware/access_allowlist_test.gonew file mode 100644index 0000000000..ec97e949c0--- /dev/null+++ b/server/internal/middleware/access_allowlist_test.go@@ -0,0 +1,85 @@+package middleware++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/multica-ai/multica/server/internal/auth"+)++func setAccessAllowlist(t *testing.T, raw string, lookup auth.UserEmailLookup) {+ t.Helper()+ a, err := auth.ParseAccessAllowlist(raw, lookup)+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })+}++func TestAuth_AccessAllowlistJWT(t *testing.T) {+ setAccessAllowlist(t, "*@multica.ai,[email protected]", nil)+ for email, want := range map[string]int{+ "[email protected]": http.StatusOK,+ "[email protected]": http.StatusOK,+ "[email protected]": http.StatusForbidden,+ } {+ t.Run(email, func(t *testing.T) {+ claims := validClaims()+ claims["email"] = email+ handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ req := httptest.NewRequest("GET", "/api/me", nil)+ req.Header.Set("Authorization", "Bearer "+generateToken(claims, auth.JWTSecret()))+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code != want {+ t.Fatalf("expected %d, got %d: %s", want, w.Code, w.Body.String())+ }+ if want == http.StatusForbidden {+ var body map[string]string+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body["code"] != auth.AccessNotAllowedCode {+ t.Fatalf("denial must carry code %q for clients to end the session, got %s", auth.AccessNotAllowedCode, w.Body.String())+ }+ }+ })+ }+}++// Credentials without an email claim (PATs, task, daemon and cloud tokens)+// resolve the owner's email through the registered lookup.+func TestRejectDeniedUser_ResolvesEmailForUserIDCredentials(t *testing.T) {+ setAccessAllowlist(t, "*@multica.ai", func(_ context.Context, userID string) (string, error) {+ switch userID {+ case "listed":+ return "[email protected]", nil+ case "unlisted":+ return "[email protected]", nil+ }+ return "", errors.New("db down")+ })+ for userID, want := range map[string]int{+ "listed": 0,+ "unlisted": http.StatusForbidden,+ "broken": http.StatusServiceUnavailable,+ } {+ t.Run(userID, func(t *testing.T) {+ w := httptest.NewRecorder()+ rejected := rejectDeniedUser(w, httptest.NewRequest("GET", "/api/me", nil), userID, "", "pat")+ if want == 0 {+ if rejected {+ t.Fatalf("listed user rejected: %d %s", w.Code, w.Body.String())+ }+ return+ }+ if !rejected || w.Code != want {+ t.Fatalf("expected %d, got rejected=%t code=%d", want, rejected, w.Code)+ }+ })+ }+}diff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.goindex 2c00c0c50f..84aa444343 100644--- a/server/internal/middleware/auth.go+++ b/server/internal/middleware/auth.go@@ -17,18 +17,39 @@ import (func uuidToString(u pgtype.UUID) string { return util.UUIDToString(u) }-func rejectTemporarilyDisabledUser(w http.ResponseWriter, r *http.Request, userID, email, authPath string) bool {- if !auth.IsTemporarilyDisabledUser(userID, email) {- return false+// rejectDeniedUser writes the response and returns true when the+// authenticated user is temporarily disabled or outside+// ACCESS_ALLOWED_EMAILS. email is the credential's own email claim when it+// carries one; otherwise the allowlist resolves it from userID.+func rejectDeniedUser(w http.ResponseWriter, r *http.Request, userID, email, authPath string) bool {+ if auth.IsTemporarilyDisabledUser(userID, email) {+ slog.Warn(+ "auth: temporarily disabled user rejected",+ "path", r.URL.Path,+ "user_id", userID,+ "auth_path", authPath,+ )+ writeError(w, http.StatusForbidden, auth.TemporarilyDisabledUserError)+ return true}- slog.Warn(- "auth: temporarily disabled user rejected",- "path", r.URL.Path,- "user_id", userID,- "auth_path", authPath,- )- writeError(w, http.StatusForbidden, auth.TemporarilyDisabledUserError)- return true+ if err := auth.CheckUserAccess(r.Context(), userID, email); err != nil {+ if errors.Is(err, auth.ErrAccessNotAllowed) {+ slog.Warn(+ "auth: user outside access allowlist rejected",+ "path", r.URL.Path,+ "user_id", userID,+ "auth_path", authPath,+ )+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusForbidden)+ w.Write([]byte(auth.AccessNotAllowedBody))+ return true+ }+ slog.Error("auth: access allowlist check failed", "path", r.URL.Path, "user_id", userID, "error", err)+ writeError(w, http.StatusServiceUnavailable, "failed to verify account access")+ return true+ }+ return false}// Auth middleware validates JWT tokens or Personal Access Tokens.@@ -120,7 +141,7 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATVreturn}userID := uuidToString(tt.UserID)- if rejectTemporarilyDisabledUser(w, r, userID, "", "task_token") {+ if rejectDeniedUser(w, r, userID, "", "task_token") {return}boundWorkspaceID := uuidToString(tt.WorkspaceID)@@ -186,7 +207,7 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATVhttp.Error(w, `{"error":"cloud pat verifier unavailable"}`, http.StatusServiceUnavailable)return}- if rejectTemporarilyDisabledUser(w, r, identity.OwnerID, "", "cloud_pat") {+ if rejectDeniedUser(w, r, identity.OwnerID, "", "cloud_pat") {return}r.Header.Set("X-User-ID", identity.OwnerID)@@ -215,7 +236,7 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATV// entry since. Skip the DB SELECT and the last_used_at// UPDATE — last_used_at is bumped once per TTL window.if userID, ok := patCache.Get(r.Context(), hash); ok {- if rejectTemporarilyDisabledUser(w, r, userID, "", "pat_cache") {+ if rejectDeniedUser(w, r, userID, "", "pat_cache") {return}r.Header.Set("X-User-ID", userID)@@ -235,7 +256,7 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATV}userID := uuidToString(pat.UserID)- if rejectTemporarilyDisabledUser(w, r, userID, "", "pat") {+ if rejectDeniedUser(w, r, userID, "", "pat") {return}r.Header.Set("X-User-ID", userID)@@ -285,7 +306,7 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATVreturn}email, _ := claims["email"].(string)- if rejectTemporarilyDisabledUser(w, r, sub, email, "jwt") {+ if rejectDeniedUser(w, r, sub, email, "jwt") {return}r.Header.Set("X-User-ID", sub)diff --git a/server/internal/middleware/daemon_auth.go b/server/internal/middleware/daemon_auth.goindex dfd087c25d..103c0c08b6 100644--- a/server/internal/middleware/daemon_auth.go+++ b/server/internal/middleware/daemon_auth.go@@ -161,6 +161,9 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.hash := auth.HashToken(tokenString)if id, ok := daemonCache.Get(r.Context(), hash); ok {+ if rejectDeniedDaemonTokenOwner(w, r, id.OwnerID) {+ return+ }ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, id.WorkspaceID)ctx = context.WithValue(ctx, ctxKeyDaemonID, id.DaemonID)ctx = context.WithValue(ctx, ctxKeyDaemonAuthPath, DaemonAuthPathDaemonToken)@@ -211,6 +214,9 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.if cacheable {daemonCache.Set(r.Context(), hash, identity, auth.TTLForExpiry(time.Now(), expiresAt))}+ if rejectDeniedDaemonTokenOwner(w, r, identity.OwnerID) {+ return+ }ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, identity.WorkspaceID)ctx = context.WithValue(ctx, ctxKeyDaemonID, identity.DaemonID)@@ -246,7 +252,7 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.writeError(w, http.StatusServiceUnavailable, "cloud pat verifier unavailable")return}- if rejectTemporarilyDisabledUser(w, r, identity.OwnerID, "", DaemonAuthPathCloudPAT) {+ if rejectDeniedUser(w, r, identity.OwnerID, "", DaemonAuthPathCloudPAT) {return}r.Header.Set("X-User-ID", identity.OwnerID)@@ -270,7 +276,7 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.hash := auth.HashToken(tokenString)if userID, ok := patCache.Get(r.Context(), hash); ok {- if rejectTemporarilyDisabledUser(w, r, userID, "", DaemonAuthPathPAT) {+ if rejectDeniedUser(w, r, userID, "", DaemonAuthPathPAT) {return}r.Header.Set("X-User-ID", userID)@@ -295,7 +301,7 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.}userID := uuidToString(pat.UserID)- if rejectTemporarilyDisabledUser(w, r, userID, "", DaemonAuthPathPAT) {+ if rejectDeniedUser(w, r, userID, "", DaemonAuthPathPAT) {return}r.Header.Set("X-User-ID", userID)@@ -339,7 +345,7 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.return}email, _ := claims["email"].(string)- if rejectTemporarilyDisabledUser(w, r, sub, email, DaemonAuthPathJWT) {+ if rejectDeniedUser(w, r, sub, email, DaemonAuthPathJWT) {return}r.Header.Set("X-User-ID", sub)@@ -349,6 +355,17 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.}}+// rejectDeniedDaemonTokenOwner applies the user gates to the human a daemon+// token was issued for. Ownerless tokens (managed runtimes, unresolved legacy+// tokens) carry no user identity and are refused by the runtime binding check+// instead.+func rejectDeniedDaemonTokenOwner(w http.ResponseWriter, r *http.Request, ownerID string) bool {+ if ownerID == "" {+ return false+ }+ return rejectDeniedUser(w, r, ownerID, "", DaemonAuthPathDaemonToken)+}+// legacyDaemonTokenOwner recovers the issuing runtime owner of a daemon token// minted before migration 588 added daemon_token.owner_id (MUL-8198).//diff --git a/server/internal/realtime/hub.go b/server/internal/realtime/hub.goindex 7012bfbaa9..a991848f74 100644--- a/server/internal/realtime/hub.go+++ b/server/internal/realtime/hub.go@@ -709,7 +709,10 @@ func authenticateToken(tokenStr string, pr PATResolver, ctx context.Context) (streturn "", `{"error":"invalid token"}`}if auth.IsTemporarilyDisabledUserID(uid) {- return "", `{"error":"account disabled"}`+ return "", wsAccountDisabledMessage+ }+ if msg := accessDeniedMessage(ctx, uid, ""); msg != "" {+ return "", msg}return uid, ""}@@ -735,11 +738,46 @@ func authenticateToken(tokenStr string, pr PATResolver, ctx context.Context) (st}email, _ := claims["email"].(string)if auth.IsTemporarilyDisabledUser(uid, email) {- return "", `{"error":"account disabled"}`+ return "", wsAccountDisabledMessage+ }+ if msg := accessDeniedMessage(ctx, uid, email); msg != "" {+ return "", msg}return uid, ""}+const (+ wsAccountDisabledMessage = `{"error":"account disabled"}`+ wsAccessCheckFailedMessage = `{"error":"failed to verify account access"}`+)++// accessDeniedMessage applies ACCESS_ALLOWED_EMAILS to a WebSocket caller.+func accessDeniedMessage(ctx context.Context, userID, email string) string {+ err := auth.CheckUserAccess(ctx, userID, email)+ switch {+ case err == nil:+ return ""+ case errors.Is(err, auth.ErrAccessNotAllowed):+ return auth.AccessNotAllowedBody+ default:+ slog.Error("realtime: access allowlist check failed", "user_id", userID, "error", err)+ return wsAccessCheckFailedMessage+ }+}++// handshakeAuthStatus maps an authenticateToken error to the HTTP status of+// a cookie-authenticated handshake: a valid credential the instance refuses+// is 403, a failed access check is retryable 503, anything else is 401.+func handshakeAuthStatus(errMsg string) int {+ switch errMsg {+ case wsAccountDisabledMessage, auth.AccessNotAllowedBody:+ return http.StatusForbidden+ case wsAccessCheckFailedMessage:+ return http.StatusServiceUnavailable+ }+ return http.StatusUnauthorized+}+// firstMessageAuth reads the first WebSocket message expecting an auth payload.// A non-empty errMsg is for the caller to write back before closing the// connection. closed=true means the connection is already torn down and the@@ -816,11 +854,7 @@ func HandleWebSocket(hub *Hub, mc MembershipChecker, pr PATResolver, resolveSlugif cookie, err := r.Cookie(auth.AuthCookieName); err == nil && cookie.Value != "" {uid, errMsg := authenticateToken(cookie.Value, pr, r.Context())if errMsg != "" {- status := http.StatusUnauthorized- if errMsg == `{"error":"account disabled"}` {- status = http.StatusForbidden- }- http.Error(w, errMsg, status)+ http.Error(w, errMsg, handshakeAuthStatus(errMsg))return}member, lookupErr := checkMembership(mc, uid, workspaceID)diff --git a/server/internal/realtime/hub_test.go b/server/internal/realtime/hub_test.goindex 1c4b527138..1394371e5c 100644--- a/server/internal/realtime/hub_test.go+++ b/server/internal/realtime/hub_test.go@@ -657,3 +657,47 @@ func TestReadPump_AcceptsFrameUnderReadLimit(t *testing.T) {t.Fatalf("got %s, want a pong frame", raw)}}++// A cookie handshake refused by ACCESS_ALLOWED_EMAILS is 403, like a+// disabled account: the credential is valid, so it must not read as a 401.+func TestHandleWebSocket_CookieHandshakeOutsideAccessAllowlist(t *testing.T) {+ a, err := auth.ParseAccessAllowlist("*@allowed.example", nil)+ if err != nil {+ t.Fatal(err)+ }+ auth.SetAccessAllowlist(a)+ t.Cleanup(func() { auth.SetAccessAllowlist(nil) })++ hub := NewHub()+ for email, want := range map[string]int{+ "[email protected]": http.StatusForbidden,+ // No email claim and no lookup to resolve one: denied.+ "": http.StatusForbidden,+ } {+ t.Run(email, func(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/ws?workspace_id="+testWorkspaceID, nil)+ req.AddCookie(&http.Cookie{Name: auth.AuthCookieName, Value: makeTestTokenForUser(t, "", email)})+ w := httptest.NewRecorder()+ HandleWebSocket(hub, &mockMembershipChecker{}, nil, nil, w, req)+ if w.Code != want {+ t.Fatalf("status = %d, want %d: %s", w.Code, want, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), auth.AccessNotAllowedCode) {+ t.Fatalf("body must carry %q: %s", auth.AccessNotAllowedCode, w.Body.String())+ }+ })+ }+}++func TestHandshakeAuthStatus(t *testing.T) {+ for msg, want := range map[string]int{+ auth.AccessNotAllowedBody: http.StatusForbidden,+ wsAccountDisabledMessage: http.StatusForbidden,+ wsAccessCheckFailedMessage: http.StatusServiceUnavailable,+ `{"error":"invalid token"}`: http.StatusUnauthorized,+ } {+ if got := handshakeAuthStatus(msg); got != want {+ t.Errorf("handshakeAuthStatus(%s) = %d, want %d", msg, got, want)+ }+ }+}