Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: add doc for sso failure (#21190)

ecmadao24cb8f9db338
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index bfb575ffe1..a44235099e 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -125,6 +125,7 @@
"title": "You have logged in as another user"
},
"oauth-callback": {
+ "idp-error": "The identity provider returned an error.",
"invalid-state": "Authentication failed: Invalid callback state. Please try again.",
"opener-failed": "Authentication completed, but failed to communicate with the parent window. Please close this window and try again.",
"opener-unavailable": "Authentication completed, but the parent window is no longer available. Please close this window and try again.",
@@ -159,10 +160,24 @@
"invited-email": "You've been invited. Please sign in with {{email}}",
"load-failed": "Couldn't load sign-in options. Please retry.",
"new-user": "New to Bytebase?",
+ "no-method-available": {
+ "description": "Password and email-code sign-in are disabled, and no identity provider is configured for this workspace.",
+ "title": "No sign-in method is available"
+ },
"resend-code": "Resend code",
"resend-in": "Resend in {{seconds}}s",
"sign-in-or-create": "Sign in or create your account",
"sign-in-to-account": "Sign in to your account",
+ "sso-failure": {
+ "administrators": "Administrators:",
+ "contact-administrator": "Contact your workspace administrator.",
+ "contact-support": "Contact Bytebase support",
+ "description": "The identity provider returned an error.",
+ "no-fallback": "Password and email-code sign-in are disabled for this workspace, so there is no fallback right now.",
+ "password-disabled": "Password sign-in is disabled for this workspace.",
+ "recovery-guide": "see the recovery guide",
+ "title": "Couldn't sign in with {{idp}}"
+ },
"standard-tab": "Standard",
"tos": "By continuing, you agree to our <terms>Terms of Service</terms> and <privacy>Privacy Policy</privacy>.",
"verification-code": "Verification code"
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 1532e4b943..8925c0ec53 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -125,6 +125,7 @@
"title": "Has iniciado sesión como otro usuario"
},
"oauth-callback": {
+ "idp-error": "El proveedor de identidad devolvió un error.",
"invalid-state": "La autenticación falló: estado de devolución de llamada no válido. Inténtalo de nuevo.",
"opener-failed": "La autenticación se completó, pero no se pudo comunicar con la ventana principal. Cierra esta ventana e inténtalo de nuevo.",
"opener-unavailable": "La autenticación se completó, pero la ventana principal ya no está disponible. Cierra esta ventana e inténtalo de nuevo.",
@@ -159,10 +160,24 @@
"invited-email": "Has sido invitado. Inicia sesión con {{email}}",
"load-failed": "No se pudieron cargar las opciones de inicio de sesión. Inténtalo de nuevo.",
"new-user": "¿Nuevo en Bytebase?",
+ "no-method-available": {
+ "description": "El inicio de sesión con contraseña y código por email está deshabilitado, y no hay ningún proveedor de identidad configurado para este espacio de trabajo.",
+ "title": "No hay ningún método de inicio de sesión disponible"
+ },
"resend-code": "Reenviar código",
"resend-in": "Reenviar en {{seconds}}s",
"sign-in-or-create": "Inicia sesión o crea tu cuenta",
"sign-in-to-account": "Inicia sesión en tu cuenta",
+ "sso-failure": {
+ "administrators": "Administradores:",
+ "contact-administrator": "Contacta con el administrador de tu espacio de trabajo.",
+ "contact-support": "Contactar con el soporte de Bytebase",
+ "description": "El proveedor de identidad devolvió un error.",
+ "no-fallback": "El inicio de sesión con contraseña y código por email está deshabilitado para este espacio de trabajo, por lo que no hay una alternativa disponible en este momento.",
+ "password-disabled": "El inicio de sesión con contraseña está deshabilitado para este espacio de trabajo.",
+ "recovery-guide": "consultar la guía de recuperación",
+ "title": "No se pudo iniciar sesión con {{idp}}"
+ },
"standard-tab": "Estándar",
"tos": "Al continuar, aceptas nuestros <terms>Términos de servicio</terms> y la <privacy>Política de privacidad</privacy>.",
"verification-code": "Código de verificación"
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 2b3363db9e..2c31ccc7c1 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -125,6 +125,7 @@
"title": "別のユーザーとしてログインしています"
},
"oauth-callback": {
+ "idp-error": "ID プロバイダーからエラーが返されました。",
"invalid-state": "認証に失敗しました:無効なコールバック状態です。もう一度お試しください。",
"opener-failed": "認証は完了しましたが、親ウィンドウとの通信に失敗しました。このウィンドウを閉じてもう一度お試しください。",
"opener-unavailable": "認証は完了しましたが、親ウィンドウを利用できなくなっています。このウィンドウを閉じてもう一度お試しください。",
@@ -159,10 +160,24 @@
"invited-email": "招待されました。{{email}} でログインしてください",
"load-failed": "サインインオプションを読み込めませんでした。もう一度お試しください。",
"new-user": "Bytebase を初めて使用しますか?",
+ "no-method-available": {
+ "description": "このワークスペースではパスワードとメール認証コードによるログインが無効で、ID プロバイダーも設定されていません。",
+ "title": "利用可能なログイン方法がありません"
+ },
"resend-code": "コードを再送信",
"resend-in": "{{seconds}}秒後に再送信可能",
"sign-in-or-create": "ログインまたはアカウントを作成",
"sign-in-to-account": "アカウントにログイン",
+ "sso-failure": {
+ "administrators": "管理者:",
+ "contact-administrator": "ワークスペース管理者に連絡してください。",
+ "contact-support": "Bytebase サポートに連絡",
+ "description": "ID プロバイダーからエラーが返されました。",
+ "no-fallback": "このワークスペースではパスワードとメール認証コードによるログインが無効なため、現在利用できる代替手段はありません。",
+ "password-disabled": "このワークスペースではパスワードによるログインが無効です。",
+ "recovery-guide": "復旧ガイドを確認",
+ "title": "{{idp}} でログインできませんでした"
+ },
"standard-tab": "標準",
"tos": "続行すると、<terms>利用規約</terms>および<privacy>プライバシーポリシー</privacy>に同意したものとみなされます。",
"verification-code": "認証コード"
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 61b6336b67..be8335b4d0 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -125,6 +125,7 @@
"title": "Bạn đã đăng nhập với tư cách người dùng khác"
},
"oauth-callback": {
+ "idp-error": "Nhà cung cấp danh tính đã trả về lỗi.",
"invalid-state": "Xác thực thất bại: Trạng thái gọi lại không hợp lệ. Vui lòng thử lại.",
"opener-failed": "Xác thực đã hoàn tất, nhưng không thể giao tiếp với cửa sổ cha. Vui lòng đóng cửa sổ này và thử lại.",
"opener-unavailable": "Xác thực đã hoàn tất, nhưng cửa sổ cha không còn khả dụng. Vui lòng đóng cửa sổ này và thử lại.",
@@ -159,10 +160,24 @@
"invited-email": "Bạn đã được mời. Vui lòng đăng nhập bằng {{email}}",
"load-failed": "Không thể tải các tùy chọn đăng nhập. Vui lòng thử lại.",
"new-user": "Mới sử dụng Bytebase?",
+ "no-method-available": {
+ "description": "Đăng nhập bằng mật khẩu và mã email đã bị tắt, đồng thời chưa có nhà cung cấp danh tính nào được cấu hình cho không gian làm việc này.",
+ "title": "Không có phương thức đăng nhập khả dụng"
+ },
"resend-code": "Gửi lại mã",
"resend-in": "Gửi lại sau {{seconds}}s",
"sign-in-or-create": "Đăng nhập hoặc tạo tài khoản của bạn",
"sign-in-to-account": "Đăng nhập vào tài khoản của bạn",
+ "sso-failure": {
+ "administrators": "Quản trị viên:",
+ "contact-administrator": "Liên hệ với quản trị viên không gian làm việc của bạn.",
+ "contact-support": "Liên hệ bộ phận hỗ trợ Bytebase",
+ "description": "Nhà cung cấp danh tính đã trả về lỗi.",
+ "no-fallback": "Đăng nhập bằng mật khẩu và mã email đã bị tắt cho không gian làm việc này, vì vậy hiện không có phương án dự phòng.",
+ "password-disabled": "Đăng nhập bằng mật khẩu đã bị tắt cho không gian làm việc này.",
+ "recovery-guide": "xem hướng dẫn khôi phục",
+ "title": "Không thể đăng nhập bằng {{idp}}"
+ },
"standard-tab": "Tiêu chuẩn",
"tos": "Bằng cách tiếp tục, bạn đồng ý với <terms>Điều khoản dịch vụ</terms> và <privacy>Chính sách quyền riêng tư</privacy> của chúng tôi.",
"verification-code": "Mã xác minh"
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index f722b4fb49..a4395a84e7 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -125,6 +125,7 @@
"title": "您已以其他用户身份登录"
},
"oauth-callback": {
+ "idp-error": "身份提供商返回了错误。",
"invalid-state": "认证失败:无效的回调状态。请重试。",
"opener-failed": "认证已完成,但与父窗口通信失败。请关闭此窗口并重试。",
"opener-unavailable": "认证已完成,但父窗口不再可用。请关闭此窗口并重试。",
@@ -159,10 +160,24 @@
"invited-email": "您已被邀请,请使用 {{email}} 登录",
"load-failed": "无法加载登录选项,请重试。",
"new-user": "第一次使用 Bytebase?",
+ "no-method-available": {
+ "description": "此工作区已禁用密码和邮箱验证码登录,且未配置身份提供商。",
+ "title": "没有可用的登录方式"
+ },
"resend-code": "重新发送验证码",
"resend-in": "{{seconds}} 秒后重新发送",
"sign-in-or-create": "登录或创建您的账户",
"sign-in-to-account": "登录您的账户",
+ "sso-failure": {
+ "administrators": "管理员:",
+ "contact-administrator": "请联系您的工作区管理员。",
+ "contact-support": "联系 Bytebase 支持",
+ "description": "身份提供商返回了错误。",
+ "no-fallback": "此工作区已禁用密码和邮箱验证码登录,目前没有备用登录方式。",
+ "password-disabled": "此工作区已禁用密码登录。",
+ "recovery-guide": "查看恢复指南",
+ "title": "无法使用 {{idp}} 登录"
+ },
"standard-tab": "标准",
"tos": "继续即表示您同意我们的<terms>服务条款</terms>和<privacy>隐私政策</privacy>。",
"verification-code": "验证码"
diff --git a/frontend/src/routes/auth/OAuthCallbackPage.test.tsx b/frontend/src/routes/auth/OAuthCallbackPage.test.tsx
index 848863e707..69fee9d791 100644
--- a/frontend/src/routes/auth/OAuthCallbackPage.test.tsx
+++ b/frontend/src/routes/auth/OAuthCallbackPage.test.tsx
@@ -225,6 +225,63 @@ describe("OAuthCallbackPage", () => {
unmount();
});
+ test("redirect mode: returns an IdP callback error to signin", async () => {
+ mocks.currentRoute.value.query = {
+ state: "idp-error-token",
+ error: "temporarily_unavailable",
+ };
+ mocks.retrieveOAuthState.mockReturnValue({
+ token: "idp-error-token",
+ event: "bb.oauth.signin.idps/okta",
+ idpType: IdentityProviderType.OIDC,
+ popup: false,
+ redirect: "/projects",
+ timestamp: Date.now(),
+ });
+
+ const { render, unmount } = renderIntoContainer(<OAuthCallbackPage />);
+ render();
+ await flushPromises();
+
+ expect(mocks.login).not.toHaveBeenCalled();
+ expect(mocks.routerPush).toHaveBeenCalledWith({
+ name: "auth.signin",
+ query: {
+ redirect: "/projects",
+ failedIdpName: "idps/okta",
+ },
+ });
+ unmount();
+ });
+
+ test("redirect mode: returns a failed token exchange to signin", async () => {
+ mocks.currentRoute.value.query = {
+ state: "token-exchange-error-token",
+ code: "abc",
+ };
+ mocks.retrieveOAuthState.mockReturnValue({
+ token: "token-exchange-error-token",
+ event: "bb.oauth.signin.idps/okta",
+ idpType: IdentityProviderType.OIDC,
+ popup: false,
+ timestamp: Date.now(),
+ });
+ mocks.login.mockRejectedValueOnce(new Error("identity provider unavailable"));
+
+ const { render, unmount } = renderIntoContainer(<OAuthCallbackPage />);
+ render();
+ await flushPromises();
+
+ expect(mocks.routerPush).toHaveBeenCalledWith({
+ name: "auth.signin",
+ query: {
+ redirect: undefined,
+ failedIdpName: "idps/okta",
+ },
+ });
+ unmount();
+ });
+
test("remount replays the processed outcome instead of re-processing the consumed token", async () => {
mocks.currentRoute.value.query = { state: "remount-token", code: "abc" };
// Single-use token: consumed (cleared) by the first mount, gone afterwards.
diff --git a/frontend/src/routes/auth/OAuthCallbackPage.tsx b/frontend/src/routes/auth/OAuthCallbackPage.tsx
index d2cb6aeb56..81aaf8c28f 100644
--- a/frontend/src/routes/auth/OAuthCallbackPage.tsx
+++ b/frontend/src/routes/auth/OAuthCallbackPage.tsx
@@ -29,6 +29,7 @@ type ProcessedOutcome = {
// leaving the side effects (opener dispatch / login) to the run that computed
// it.
const processedOutcomes = new Map<string, ProcessedOutcome>();
+const SIGNIN_EVENT_PREFIX = "bb.oauth.signin.";
export function OAuthCallbackPage() {
const { t } = useTranslation();
@@ -91,14 +92,19 @@ export function OAuthCallbackPage() {
return;
}
+ const callbackError = typeof query.error === "string" ? query.error : "";
+ payloadRef.current.error = callbackError;
apply({
- hasError: false,
- messageKey: "auth.oauth-callback.success-redirecting",
+ hasError: callbackError.length > 0,
+ messageKey:
+ callbackError.length > 0
+ ? "auth.oauth-callback.idp-error"
+ : "auth.oauth-callback.success-redirecting",
oAuthState: storedState,
});
payloadRef.current.code = (query.code as string) || "";
clearOAuthState(storedState.token);
- triggerAuthCallback(storedState, false);
+ triggerAuthCallback(storedState, callbackError.length > 0);
}, []);
const triggerAuthCallback = async (
@@ -146,37 +152,60 @@ export function OAuthCallbackPage() {
return;
}
- if (isError || !state) {
+ if (isError && state) {
+ returnToSigninAfterSSOFailure(state);
+ return;
+ }
+
+ if (!state) {
return;
}
const eventName = state.event;
- if (eventName.startsWith("bb.oauth.signin")) {
+ if (eventName.startsWith(SIGNIN_EVENT_PREFIX)) {
const isOidc = state.idpType === IdentityProviderType.OIDC;
- const idpName = eventName.split(".").pop();
+ const idpName = eventName.slice(SIGNIN_EVENT_PREFIX.length);
if (!idpName) {
return;
}
- await useAppStore.getState().login({
- request: create(LoginRequestSchema, {
- idpName,
- idpContext: {
- context: {
- case: isOidc ? "oidcContext" : "oauth2Context",
- value: {
- code: payloadRef.current.code,
+ try {
+ await useAppStore.getState().login({
+ request: create(LoginRequestSchema, {
+ idpName,
+ idpContext: {
+ context: {
+ case: isOidc ? "oidcContext" : "oauth2Context",
+ value: {
+ code: payloadRef.current.code,
+ },
},
},
- },
- workspace: resolveWorkspaceName(),
- }),
- redirect: true,
- redirectUrl: state.redirect,
- });
+ workspace: resolveWorkspaceName(),
+ }),
+ redirect: true,
+ redirectUrl: state.redirect,
+ silent: true,
+ });
+ } catch {
+ returnToSigninAfterSSOFailure(state);
+ }
}
};
+ const returnToSigninAfterSSOFailure = (state: OAuthState) => {
+ const idpName = state.event.startsWith(SIGNIN_EVENT_PREFIX)
+ ? state.event.slice(SIGNIN_EVENT_PREFIX.length)
+ : "";
+ router.push({
+ name: AUTH_SIGNIN_MODULE,
+ query: {
+ redirect: state.redirect,
+ failedIdpName: idpName,
+ },
+ });
+ };
+
const backToSignin = () => {
router.push({ name: AUTH_SIGNIN_MODULE });
};
diff --git a/frontend/src/routes/auth/SigninPage.test.tsx b/frontend/src/routes/auth/SigninPage.test.tsx
index e3ef0f8158..4129d8fda4 100644
--- a/frontend/src/routes/auth/SigninPage.test.tsx
+++ b/frontend/src/routes/auth/SigninPage.test.tsx
@@ -40,8 +40,13 @@ vi.mock("@/stores/app", () => {
const getState = () => {
const store = mocks.actuatorStore as Record<string, unknown>;
const info = store.authenticationInfo as Record<string, unknown> | undefined;
+ const isSaaSMode = store.isSaaSMode;
return {
...store,
+ isSaaSMode:
+ typeof isSaaSMode === "function"
+ ? (isSaaSMode as () => boolean)
+ : () => false,
// The login page reads its providers off the authentication info.
authenticationInfo: info
? { ...info, identityProviders: mocks.identityProviders }
@@ -385,4 +390,153 @@ describe("SigninPage", () => {
unmount();
});
+
+ test("shows recovery instructions after an SSO failure", async () => {
+ mocks.currentRoute.value.query = {
+ failedIdpName: "idps/okta",
+ };
+ const idps = [
+ {
+ name: "idps/okta",
+ title: "Okta",
+ type: IdentityProviderType.OIDC,
+ },
+ ];
+ mocks.identityProviders = idps;
+
+ const { container, render, unmount } = renderIntoContainer(<SigninPage />);
+ render();
+ await flushPromises();
+
+ expect(container.textContent).toContain(
+ 'auth.sign-in.sso-failure.title:{"idp":"Okta"}'
+ );
+ expect(container.textContent).toContain(
+ "auth.sign-in.sso-failure.no-fallback"
+ );
+ expect(container.textContent).toContain(
+ "auth.sign-in.sso-failure.recovery-guide"
+ );
+
+ const oktaButton = Array.from(
+ container.querySelectorAll<HTMLButtonElement>("button")
+ ).find((button) =>
+ button.textContent?.includes(
+ 'auth.sign-in.continue-with-idp:{"idp":"Okta"}'
+ )
+ );
+ expect(oktaButton).toBeTruthy();
+ await act(async () => {
+ oktaButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await Promise.resolve();
+ });
+ expect(mocks.openWindowForSSO).toHaveBeenCalledWith(
+ idps[0],
+ false,
+ undefined
+ );
+ unmount();
+ });
+
+ test("offers recovery help when password signin is disabled and email-code signin is available", async () => {
+ mocks.currentRoute.value.query = {
+ failedIdpName: "idps/okta",
+ };
+ mocks.actuatorStore = {
+ authenticationInfo: {
+ workspace: "workspaces/default",
+ restriction: {
+ disallowPasswordSignin: true,
+ allowEmailCodeSignin: true,
+ disallowSignup: true,
+ },
+ },
+ fetchAuthenticationInfo: vi.fn(async () => ({})),
+ };
+ const idps = [
+ {
+ name: "idps/okta",
+ title: "Okta",
+ type: IdentityProviderType.OIDC,
+ },
+ ];
+ mocks.identityProviders = idps;
+
+ const { container, render, unmount } = renderIntoContainer(<SigninPage />);
+ render();
+ await flushPromises();
+
+ expect(container.textContent).toContain(
+ 'auth.sign-in.sso-failure.title:{"idp":"Okta"}'
+ );
+ expect(container.textContent).toContain(
+ "auth.sign-in.sso-failure.password-disabled"
+ );
+ expect(container.textContent).toContain(
+ "auth.sign-in.sso-failure.recovery-guide"
+ );
+ expect(container.textContent).not.toContain(
+ "auth.sign-in.sso-failure.no-fallback"
+ );
+ unmount();
+ });
+
+ test("directs Cloud users to Bytebase support instead of the recovery guide", async () => {
+ mocks.currentRoute.value.query = {
+ failedIdpName: "idps/okta",
+ };
+ mocks.actuatorStore = {
+ authenticationInfo: {
+ workspace: "workspaces/default",
+ restriction: {
+ disallowPasswordSignin: true,
+ allowEmailCodeSignin: false,
+ disallowSignup: true,
+ },
+ },
+ fetchAuthenticationInfo: vi.fn(async () => ({})),
+ isSaaSMode: () => true,
+ };
+ const idps = [
+ {
+ name: "idps/okta",
+ title: "Okta",
+ type: IdentityProviderType.OIDC,
+ },
+ ];
+ mocks.identityProviders = idps;
+
+ const { container, render, unmount } = renderIntoContainer(<SigninPage />);
+ render();
+ await flushPromises();
+
+ expect(container.textContent).toContain(
+ "auth.sign-in.sso-failure.contact-support"
+ );
+ expect(container.textContent).not.toContain(
+ "auth.sign-in.sso-failure.recovery-guide"
+ );
+ expect(
+ container.querySelector(
+ 'a[href="https://docs.bytebase.com/faq#how-to-reach-us?source=console"]'
+ )
+ ).toBeTruthy();
+ unmount();
+ });
+
+ test("shows recovery instructions when no signin method is configured", async () => {
+ mocks.identityProviders = [];
+
+ const { container, render, unmount } = renderIntoContainer(<SigninPage />);
+ render();
+ await flushPromises();
+
+ expect(container.textContent).toContain(
+ "auth.sign-in.no-method-available.title"
+ );
+ expect(container.textContent).toContain(
+ "auth.sign-in.sso-failure.recovery-guide"
+ );
+ unmount();
+ });
});
diff --git a/frontend/src/routes/auth/SigninPage.tsx b/frontend/src/routes/auth/SigninPage.tsx
index 8a5408bf99..aaa970f134 100644
--- a/frontend/src/routes/auth/SigninPage.tsx
+++ b/frontend/src/routes/auth/SigninPage.tsx
@@ -1,3 +1,4 @@
+import { ExternalLink } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Trans, useTranslation } from "react-i18next";
import { router } from "@/app/router";
@@ -21,7 +22,7 @@ import type {
LoginRequest,
} from "@/types/proto-es/v1/auth_service_pb";
import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";
-import { openWindowForSSO, SsoConfigError } from "@/utils";
+import { openWindowForSSO } from "@/utils";
export type SigninPageProps = {
readonly redirect?: boolean;
@@ -31,6 +32,25 @@ export type SigninPageProps = {
readonly footerOverride?: React.ReactNode;
};
+type SSOFailure = {
+ idpName: string;
+};
+
+const ADMIN_RECOVERY_URL =
+ "https://docs.bytebase.com/administration/admin-recovery?source=console";
+const SUPPORT_URL =
+ "https://docs.bytebase.com/faq#how-to-reach-us?source=console";
+
+function queryString(value: unknown): string {
+ return typeof value === "string" ? value : "";
+}
+
+function queryFailure(query: Record<string, unknown>): SSOFailure | undefined {
+ const idpName = queryString(query.failedIdpName);
+ if (!idpName) return undefined;
+ return { idpName };
+}
+
export function SigninPage(props: SigninPageProps) {
const {
redirect = true,
@@ -42,11 +62,16 @@ export function SigninPage(props: SigninPageProps) {
const { t } = useTranslation();
const [isLoading, setIsLoading] = useState(false);
const [initialized, setInitialized] = useState(false);
+ const query = router.currentRoute.value.query;
+ const initialSSOFailure = queryFailure(query);
+ const [ssoFailure, setSSOFailure] = useState<SSOFailure | undefined>(
+ initialSSOFailure
+ );
const authenticationInfo = useAppStore((s) => s.authenticationInfo);
+ const isSaaSMode = useAppStore((s) => s.isSaaSMode());
const identityProviders = authenticationInfo?.identityProviders ?? [];
- const query = router.currentRoute.value.query;
const invitedEmail = (query.email as string | undefined) ?? "";
const disallowSignup =
@@ -88,11 +113,9 @@ export function SigninPage(props: SigninPageProps) {
module: "bytebase",
style: "CRITICAL",
title: "Request error occurred",
- description:
- error instanceof SsoConfigError
- ? t(error.i18nKey)
- : (error as Error).message,
+ description: (error as Error).message,
});
+ setSSOFailure({ idpName: idp.name });
}
};
@@ -215,6 +238,49 @@ export function SigninPage(props: SigninPageProps) {
allowSignupProp &&
!authenticationInfo?.restriction?.disallowSignup;
const showTerms = allowSignupProp && emailCodeEnabled;
+ const disallowPasswordSignin =
+ !!authenticationInfo?.restriction?.disallowPasswordSignin;
+ const hasNoPasswordFallback =
+ disallowPasswordSignin &&
+ !authenticationInfo?.restriction?.allowEmailCodeSignin;
+ const noSigninMethodAvailable =
+ hasNoPasswordFallback && identityProviders.length === 0;
+ const failedIdp = ssoFailure
+ ? identityProviders.find((idp) => idp.name === ssoFailure.idpName)
+ : undefined;
+ const failedIdpTitle =
+ failedIdp?.title ?? ssoFailure?.idpName.replace(idpNamePrefix, "") ?? "";
+ const recoveryLinks = (
+ <ul className="mt-2 list-disc pl-5">
+ <li>{t("auth.sign-in.sso-failure.contact-administrator")}</li>
+ <li>
+ {isSaaSMode ? (
+ <a
+ href={SUPPORT_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium underline"
+ >
+ {t("auth.sign-in.sso-failure.contact-support")}
+ <ExternalLink className="ml-1 inline size-3" />
+ </a>
+ ) : (
+ <>
+ {t("auth.sign-in.sso-failure.administrators")}{" "}
+ <a
+ href={ADMIN_RECOVERY_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium underline"
+ >
+ {t("auth.sign-in.sso-failure.recovery-guide")}
+ <ExternalLink className="ml-1 inline size-3" />
+ </a>
+ </>
+ )}
+ </li>
+ </ul>
+ );
return (
<>
@@ -236,6 +302,39 @@ export function SigninPage(props: SigninPageProps) {
/>
)}
+ {noSigninMethodAvailable && (
+ <Alert
+ variant="info"
+ className="mb-4"
+ title={t("auth.sign-in.no-method-available.title")}
+ description={t("auth.sign-in.no-method-available.description")}
+ >
+ {recoveryLinks}
+ </Alert>
+ )}
+
+ {ssoFailure && (
+ <Alert
+ variant="warning"
+ className="mb-4"
+ title={t("auth.sign-in.sso-failure.title", {
+ idp: failedIdpTitle,
+ })}
+ description={t("auth.sign-in.sso-failure.description")}
+ >
+ {disallowPasswordSignin && (
+ <div className="mt-2">
+ <p>
+ {hasNoPasswordFallback
+ ? t("auth.sign-in.sso-failure.no-fallback")
+ : t("auth.sign-in.sso-failure.password-disabled")}
+ </p>
+ {recoveryLinks}
+ </div>
+ )}
+ </Alert>
+ )}
+
{separatedIdps.length > 0 && (
<div className="flex flex-col gap-y-2">
{separatedIdps.map((idp) => (
diff --git a/frontend/src/routes/workspace/IdpTestConnection.tsx b/frontend/src/routes/workspace/IdpTestConnection.tsx
index f7c6037519..4547817ad4 100644
--- a/frontend/src/routes/workspace/IdpTestConnection.tsx
+++ b/frontend/src/routes/workspace/IdpTestConnection.tsx
@@ -17,11 +17,7 @@ import {
IdentityProviderType,
TestIdentityProviderRequestSchema,
} from "@/types/proto-es/v1/idp_service_pb";
-import {
- openWindowForSSO,
- SsoConfigError,
- toLoginIdentityProvider,
-} from "@/utils";
+import { openWindowForSSO, toLoginIdentityProvider } from "@/utils";
// ============================================================
// KeyValueBox
@@ -359,10 +355,7 @@ export function TestConnectionButton({
module: "bytebase",
style: "CRITICAL",
title: "Request error occurred",
- description:
- error instanceof SsoConfigError
- ? t(error.i18nKey)
- : (error as ConnectError).message,
+ description: (error as ConnectError).message,
});
}
} else if (idp.type === IdentityProviderType.LDAP) {
diff --git a/frontend/src/stores/app/auth.ts b/frontend/src/stores/app/auth.ts
index cd6b3f991c..a02f7f58bb 100644
--- a/frontend/src/stores/app/auth.ts
+++ b/frontend/src/stores/app/auth.ts
@@ -151,13 +151,13 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
// sometimes we have to redirect users even if we don't want to redirect them.
// for example, the user is forced to reset their password,
// or the user is using the LDAP to signin.
- login: async ({ request, redirect = true, redirectUrl }) => {
+ login: async ({ request, redirect = true, redirectUrl, silent = false }) => {
const resp = await authServiceClientConnect.login(
create(LoginRequestSchema, { ...request, web: true }),
{
- contextValues: createContextValues().set(ignoredCodesContextKey, [
- Code.NotFound,
- ]),
+ contextValues: createContextValues()
+ .set(ignoredCodesContextKey, [Code.NotFound])
+ .set(silentContextKey, silent),
}
);
const redirectQuery = new URLSearchParams(window.location.search).get(
diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.ts
index e36e574c0e..ee136a14e8 100644
--- a/frontend/src/stores/app/index.test.ts
+++ b/frontend/src/stores/app/index.test.ts
@@ -602,8 +602,11 @@ describe("useAppStore", () => {
await store.getState().login({
request: { email: user.email, password: "secret" } as never,
redirectUrl,
+ silent: true,
});
+ const requestOptions = mocks.login.mock.calls[0]?.[1];
+ expect(requestOptions?.contextValues.get(silentContextKey)).toBe(true);
expect(mocks.navigateToPath).toHaveBeenCalledWith(redirectUrl, {
replace: true,
});
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index 09d7b7944b..26ed6bfaa4 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -211,6 +211,7 @@ export type AuthSlice = {
request: LoginRequest;
redirect?: boolean;
redirectUrl?: string;
+ silent?: boolean;
}) => Promise<void>;
signup: (request: Partial<User>) => Promise<void>;
logout: () => Promise<void>;
diff --git a/frontend/src/utils/sso.test.ts b/frontend/src/utils/sso.test.ts
new file mode 100644
index 0000000000..e2c83b31a4
--- /dev/null
+++ b/frontend/src/utils/sso.test.ts
@@ -0,0 +1,45 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import {
+ AuthorizationRequestSchema,
+ LoginIdentityProviderSchema,
+} from "@/types/proto-es/v1/auth_service_pb";
+import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";
+import { openWindowForSSO } from "./sso";
+
+describe("openWindowForSSO", () => {
+ test.each([
+ {
+ identityProvider: create(LoginIdentityProviderSchema, {
+ type: IdentityProviderType.LDAP,
+ }),
+ message: "This identity provider type does not support SSO redirect.",
+ },
+ {
+ identityProvider: create(LoginIdentityProviderSchema, {
+ type: IdentityProviderType.OAUTH2,
+ authorizationRequest: create(AuthorizationRequestSchema),
+ }),
+ message:
+ "The identity provider published no authorization endpoint. Check its configuration.",
+ },
+ {
+ identityProvider: create(LoginIdentityProviderSchema, {
+ type: IdentityProviderType.OIDC,
+ authorizationRequest: create(AuthorizationRequestSchema, {
+ endpoint: "javascript:alert(1)",
+ }),
+ }),
+ message:
+ "Invalid authorization URL: it must be a valid HTTP or HTTPS URL.",
+ },
+ ])(
+ "throws the localized SSO configuration error",
+ async ({ identityProvider, message }) => {
+ await expect(openWindowForSSO(identityProvider)).rejects.toMatchObject({
+ message,
+ });
+ }
+ );
+});
diff --git a/frontend/src/utils/sso.ts b/frontend/src/utils/sso.ts
index 5e5643f57e..1d7dc22e30 100644
--- a/frontend/src/utils/sso.ts
+++ b/frontend/src/utils/sso.ts
@@ -1,4 +1,5 @@
import { create } from "@bufbuild/protobuf";
+import i18n from "@/lib/i18n";
import type { OAuthState } from "@/types";
import type {
AuthorizationRequest,
@@ -95,17 +96,6 @@ export function clearOAuthState(token: string): void {
console.error("Failed to clear OAuth state:", error);
}
}
-/**
- * An SSO failure whose message is an i18n key. `sso.ts` has no translator, so
- * the caller that renders the failure translates it.
- */
-export class SsoConfigError extends Error {
- constructor(readonly i18nKey: string) {
- super(i18nKey);
- this.name = "SsoConfigError";
- }
-}
-
export async function openWindowForSSO(
identityProvider: LoginIdentityProvider,
popup = true,
@@ -118,16 +108,16 @@ export async function openWindowForSSO(
} else if (identityProvider.type === IdentityProviderType.OIDC) {
callbackPath = "/oidc/callback";
} else {
- throw new SsoConfigError("auth.sso.unsupported-provider-type");
+ throw new Error(i18n.t("auth.sso.unsupported-provider-type"));
}
const request = identityProvider.authorizationRequest;
if (!request || request.endpoint === "") {
- throw new SsoConfigError("auth.sso.no-authorization-endpoint");
+ throw new Error(i18n.t("auth.sso.no-authorization-endpoint"));
}
// Validate the endpoint to prevent XSS via javascript: URIs.
if (!isValidHttpUrl(request.endpoint)) {
- throw new SsoConfigError("auth.sso.invalid-authorization-url");
+ throw new Error(i18n.t("auth.sso.invalid-authorization-url"));
}
// Generate cryptographically secure random token for CSRF protection