Skip to content

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

fix(auth): stop "Authentication failed" flash during SSO sign-in (#20572)

Danny Xuba0a6164b676
diff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjs
index 01eb892165..ee1db80fbf 100644
--- a/frontend/scripts/check-react-i18n.mjs
+++ b/frontend/scripts/check-react-i18n.mjs
@@ -32,6 +32,10 @@ const DYNAMIC_PREFIXES = [
"settings.sensitive-data.algorithms.",
"instance.selected-n-instances",
"settings.sidebar.",
+ // Stored as messageKey string literals and translated via t(messageKey) at
+ // render, not as literal t("…") calls. See
+ // frontend/src/react/pages/auth/OAuthCallbackPage.tsx.
+ "auth.oauth-callback.",
// Returned from getReviewBadge as labelKey string literals, not invoked
// via t("…") in source. See frontend/src/react/pages/project/utils/reviewBadge.ts.
"common.bypassed",
diff --git a/frontend/src/react/app/AuthGate.test.tsx b/frontend/src/react/app/AuthGate.test.tsx
index ab81b4a258..f19ffa400e 100644
--- a/frontend/src/react/app/AuthGate.test.tsx
+++ b/frontend/src/react/app/AuthGate.test.tsx
@@ -72,7 +72,7 @@ vi.mock("@/react/components/auth/InactiveRemindModal", () => ({
vi.mock("@/react/router/guard", () => ({
buildSigninRedirectQuery: mocks.buildSigninRedirectQuery,
- isAuthRelatedRoute: () => false,
+ isAuthRelatedRoute: (name: string) => name.startsWith("auth."),
}));
vi.mock("@/react/router/handles", () => ({
@@ -236,6 +236,39 @@ describe("AuthGate", () => {
expect(container.querySelector("[data-testid='page']")).not.toBeNull();
});
+ test("keeps auth-route children mounted while post-login workspace data loads", async () => {
+ mocks.session.isLoggedIn = false;
+ mocks.routeName = "auth.oauth.callback";
+ mocks.location.pathname = "/oauth/callback";
+ // Hold the post-login data load open so the gate stays in its loading
+ // phase for the rest of the test (once: it must not leak into later tests
+ // — clearAllMocks doesn't restore implementations).
+ mocks.loadSubscription.mockImplementationOnce(() => new Promise(() => {}));
+
+ await act(async () => {
+ root.render(
+ <AuthGate>
+ <div data-testid="page">Page</div>
+ </AuthGate>
+ );
+ });
+
+ expect(container.querySelector("[data-testid='page']")).not.toBeNull();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+
+ // The OAuth callback page completes login() mid-page: the session flips
+ // without a navigation. The callback page must stay mounted — unmounting
+ // would discard its in-flight UI and re-process the single-use OAuth
+ // state token on remount.
+ await act(async () => {
+ mocks.session.isLoggedIn = true;
+ useAppStore.setState({});
+ });
+
+ expect(container.querySelector("[data-testid='page']")).not.toBeNull();
+ expect(container.querySelector("[role='status']")).toBeNull();
+ });
+
test("refreshes permission data in the background during session polling", async () => {
await act(async () => {
root.render(
diff --git a/frontend/src/react/app/AuthGate.tsx b/frontend/src/react/app/AuthGate.tsx
index 76a6fc9b10..9a6cf30585 100644
--- a/frontend/src/react/app/AuthGate.tsx
+++ b/frontend/src/react/app/AuthGate.tsx
@@ -132,9 +132,14 @@ export function AuthGate({ children }: { children: ReactNode }) {
});
}, [currentUserName, navigate, t]);
+ // Auth surfaces (signin, OAuth/OIDC callbacks, MFA, …) render outside the
+ // readiness gate: they don't depend on the workspace data loaded above, and
+ // hiding them while it loads would unmount the OAuth callback page mid-login
+ // (its `login()` flips `isLoggedIn`, which triggers that load) and blank the
+ // signin page on first paint.
return (
<>
- {ready && !shouldRedirectToSignin ? (
+ {(ready || isAuthRoute) && !shouldRedirectToSignin ? (
children
) : (
<div className="flex items-center justify-center h-screen">
diff --git a/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx b/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx
index 3afd239b7b..0bde80b12b 100644
--- a/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx
+++ b/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx
@@ -107,6 +107,9 @@ beforeEach(async () => {
mocks.login.mockResolvedValue(undefined);
mocks.retrieveOAuthState.mockReset();
mocks.clearOAuthState.mockReset();
+ // The module memoizes processed callbacks by state token for the lifetime of
+ // the page load (the module instance is cached across tests here), so every
+ // test must use a token unique to that test.
({ OAuthCallbackPage } = await import("./OAuthCallbackPage"));
});
@@ -133,7 +136,7 @@ describe("OAuthCallbackPage", () => {
});
test("renders error when stored state not found", async () => {
- mocks.currentRoute.value.query = { state: "xyz" };
+ mocks.currentRoute.value.query = { state: "expired-token" };
mocks.retrieveOAuthState.mockReturnValue(null);
const { container, render, unmount } = renderIntoContainer(
<OAuthCallbackPage />
@@ -147,7 +150,7 @@ describe("OAuthCallbackPage", () => {
});
test("renders security-validation error and clears state when token mismatches", async () => {
- mocks.currentRoute.value.query = { state: "xyz" };
+ mocks.currentRoute.value.query = { state: "mismatch-token" };
mocks.retrieveOAuthState.mockReturnValue({
token: "OTHER",
event: "bb.oauth.signin.gh",
@@ -162,14 +165,14 @@ describe("OAuthCallbackPage", () => {
expect(container.textContent).toContain(
"auth.oauth-callback.security-failed"
);
- expect(mocks.clearOAuthState).toHaveBeenCalledWith("xyz");
+ expect(mocks.clearOAuthState).toHaveBeenCalledWith("mismatch-token");
unmount();
});
test("redirect mode: valid signin event calls authStore.login with oauth2Context", async () => {
- mocks.currentRoute.value.query = { state: "xyz", code: "abc" };
+ mocks.currentRoute.value.query = { state: "signin-token", code: "abc" };
mocks.retrieveOAuthState.mockReturnValue({
- token: "xyz",
+ token: "signin-token",
event: "bb.oauth.signin.gh",
idpType: IdentityProviderType.OAUTH2,
popup: false,
@@ -199,9 +202,9 @@ describe("OAuthCallbackPage", () => {
});
test("redirect mode: OIDC event uses oidcContext", async () => {
- mocks.currentRoute.value.query = { state: "xyz", code: "abc" };
+ mocks.currentRoute.value.query = { state: "oidc-token", code: "abc" };
mocks.retrieveOAuthState.mockReturnValue({
- token: "xyz",
+ token: "oidc-token",
event: "bb.oauth.signin.okta",
idpType: IdentityProviderType.OIDC,
popup: false,
@@ -222,10 +225,46 @@ describe("OAuthCallbackPage", () => {
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.
+ mocks.retrieveOAuthState
+ .mockReturnValueOnce({
+ token: "remount-token",
+ event: "bb.oauth.signin.gh",
+ idpType: IdentityProviderType.OAUTH2,
+ popup: false,
+ redirect: "/home",
+ timestamp: Date.now(),
+ })
+ .mockReturnValue(null);
+
+ const first = renderIntoContainer(<OAuthCallbackPage />);
+ first.render();
+ await flushPromises();
+ expect(mocks.login).toHaveBeenCalledTimes(1);
+ first.unmount();
+
+ // The app shell may remount routed content while login() is still running
+ // (e.g. AuthGate reloading workspace data when the session flips).
+ const second = renderIntoContainer(<OAuthCallbackPage />);
+ second.render();
+ await flushPromises();
+ expect(second.container.textContent).toContain(
+ "auth.oauth-callback.success-redirecting"
+ );
+ expect(second.container.textContent).not.toContain(
+ "auth.oauth-callback.session-expired"
+ );
+ // The in-flight login from the first mount must not be re-issued.
+ expect(mocks.login).toHaveBeenCalledTimes(1);
+ second.unmount();
+ });
+
test("popup mode: dispatches CustomEvent on window.opener with payload", async () => {
- mocks.currentRoute.value.query = { state: "xyz", code: "abc" };
+ mocks.currentRoute.value.query = { state: "popup-token", code: "abc" };
mocks.retrieveOAuthState.mockReturnValue({
- token: "xyz",
+ token: "popup-token",
event: "bb.oauth.signin.gh",
idpType: IdentityProviderType.OAUTH2,
popup: true,
diff --git a/frontend/src/react/pages/auth/OAuthCallbackPage.tsx b/frontend/src/react/pages/auth/OAuthCallbackPage.tsx
index c535c9dc67..fcf7adcaff 100644
--- a/frontend/src/react/pages/auth/OAuthCallbackPage.tsx
+++ b/frontend/src/react/pages/auth/OAuthCallbackPage.tsx
@@ -12,57 +12,90 @@ import { LoginRequestSchema } from "@/types/proto-es/v1/auth_service_pb";
import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";
import { clearOAuthState, retrieveOAuthState } from "@/utils/sso";
+type ProcessedOutcome = {
+ hasError: boolean;
+ messageKey: string;
+ oAuthState: OAuthState | undefined;
+};
+
+// The OAuth `state` token is single-use: processing consumes it from
+// localStorage (`clearOAuthState`). The page component, however, can mount
+// more than once per callback navigation — StrictMode double-invokes effects,
+// and the app shell can remount routed content while the kicked-off `login()`
+// is still running. Re-processing would find the token already consumed and
+// misreport a fatal-looking "session expired" error mid-login. Memoizing the
+// outcome at module scope makes processing once-per-page-load (the standard
+// redirect-callback contract): later mounts replay the outcome render-only,
+// leaving the side effects (opener dispatch / login) to the run that computed
+// it.
+const processedOutcomes = new Map<string, ProcessedOutcome>();
+
export function OAuthCallbackPage() {
const { t } = useTranslation();
- const [message, setMessage] = useState("");
+ const [messageKey, setMessageKey] = useState("");
const [hasError, setHasError] = useState(false);
const [oAuthState, setOAuthState] = useState<OAuthState | undefined>(
undefined
);
const [showCloseButton, setShowCloseButton] = useState(false);
const payloadRef = useRef<OAuthWindowEventPayload>({ error: "", code: "" });
- // StrictMode double-invokes effects; the OAuth state token is single-use
- // (consumed via `clearOAuthState`). Without this guard the second invocation
- // would fail to retrieve the already-cleared token and flash a
- // "session expired" error before the login completes.
- const initRef = useRef(false);
useEffect(() => {
- if (initRef.current) return;
- initRef.current = true;
const query = router.currentRoute.value.query;
- const stateToken = query.state as string | undefined;
-
- if (
- !stateToken ||
- typeof stateToken !== "string" ||
- stateToken.length === 0
- ) {
- setHasError(true);
- setMessage(t("auth.oauth-callback.invalid-state"));
+ const stateToken = typeof query.state === "string" ? query.state : "";
+
+ const replayed = processedOutcomes.get(stateToken);
+ if (replayed) {
+ setHasError(replayed.hasError);
+ setMessageKey(replayed.messageKey);
+ setOAuthState(replayed.oAuthState);
+ return;
+ }
+
+ const apply = (outcome: ProcessedOutcome) => {
+ processedOutcomes.set(stateToken, outcome);
+ setHasError(outcome.hasError);
+ setMessageKey(outcome.messageKey);
+ setOAuthState(outcome.oAuthState);
+ };
+
+ if (stateToken.length === 0) {
+ apply({
+ hasError: true,
+ messageKey: "auth.oauth-callback.invalid-state",
+ oAuthState: undefined,
+ });
triggerAuthCallback(undefined, true);
return;
}
const storedState = retrieveOAuthState(stateToken);
if (!storedState) {
- setHasError(true);
- setMessage(t("auth.oauth-callback.session-expired"));
+ apply({
+ hasError: true,
+ messageKey: "auth.oauth-callback.session-expired",
+ oAuthState: undefined,
+ });
triggerAuthCallback(undefined, true);
return;
}
if (storedState.token !== stateToken) {
- setHasError(true);
- setMessage(t("auth.oauth-callback.security-failed"));
+ apply({
+ hasError: true,
+ messageKey: "auth.oauth-callback.security-failed",
+ oAuthState: undefined,
+ });
clearOAuthState(stateToken);
triggerAuthCallback(undefined, true);
return;
}
- setOAuthState(storedState);
- setHasError(false);
- setMessage(t("auth.oauth-callback.success-redirecting"));
+ apply({
+ hasError: false,
+ messageKey: "auth.oauth-callback.success-redirecting",
+ oAuthState: storedState,
+ });
payloadRef.current.code = (query.code as string) || "";
clearOAuthState(storedState.token);
triggerAuthCallback(storedState, false);
@@ -76,7 +109,7 @@ export function OAuthCallbackPage() {
try {
if (!window.opener || window.opener.closed) {
setHasError(true);
- setMessage(t("auth.oauth-callback.opener-unavailable"));
+ setMessageKey("auth.oauth-callback.opener-unavailable");
setShowCloseButton(true);
return;
}
@@ -94,20 +127,20 @@ export function OAuthCallbackPage() {
if (!window.closed) {
setShowCloseButton(true);
if (!isError) {
- setMessage(t("auth.oauth-callback.success-close"));
+ setMessageKey("auth.oauth-callback.success-close");
}
}
}, 500);
} catch {
setShowCloseButton(true);
if (!isError) {
- setMessage(t("auth.oauth-callback.please-close"));
+ setMessageKey("auth.oauth-callback.please-close");
}
}
} catch (error) {
console.error("Failed to communicate with opener window:", error);
setHasError(true);
- setMessage(t("auth.oauth-callback.opener-failed"));
+ setMessageKey("auth.oauth-callback.opener-failed");
setShowCloseButton(true);
}
return;
@@ -152,7 +185,7 @@ export function OAuthCallbackPage() {
<div className="p-4">
{hasError ? (
<div className="mt-2">
- <div>{message}</div>
+ <div>{messageKey && t(messageKey)}</div>
{oAuthState?.popup ? (
<Button onClick={() => window.close()}>{t("common.close")}</Button>
) : (
@@ -165,7 +198,7 @@ export function OAuthCallbackPage() {
<div className="mt-2">
<div className="flex items-center gap-x-2">
<Loader2 className="size-4 animate-spin" />
- <span>{message || t("auth.oauth-callback.processing")}</span>
+ <span>{t(messageKey || "auth.oauth-callback.processing")}</span>
</div>
{oAuthState?.popup && showCloseButton && (
<Button className="mt-4" onClick={() => window.close()}>