Skip to content

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

fix(frontend): redirect logged-out react auth routes (#20549)

p0ny701a0469a3f5
diff --git a/frontend/src/react/app/AuthGate.test.tsx b/frontend/src/react/app/AuthGate.test.tsx
index 97e818a3be..ab81b4a258 100644
--- a/frontend/src/react/app/AuthGate.test.tsx
+++ b/frontend/src/react/app/AuthGate.test.tsx
@@ -7,7 +7,46 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
+ session: {
+ isLoggedIn: true,
+ },
navigate: vi.fn(),
+ location: {
+ pathname: "/projects",
+ search: "",
+ hash: "",
+ },
+ routeName: "workspace.dashboard",
+ resolvePath: vi.fn(
+ (
+ _name: string,
+ options?: { query?: Record<string, string | undefined> }
+ ) => {
+ const query = new URLSearchParams();
+ for (const [key, value] of Object.entries(options?.query ?? {})) {
+ if (value) query.set(key, value);
+ }
+ const serialized = query.toString();
+ return serialized ? `/auth?${serialized}` : "/auth";
+ }
+ ),
+ buildSigninRedirectQuery: vi.fn((url: URL) => {
+ const query: Record<string, string> = {};
+ for (const param of ["idp", "workspace", "email", "token", "invitation"]) {
+ const value = url.searchParams.get(param);
+ if (value) query[param] = value;
+ }
+ const redirectURL = new URL(url.toString());
+ for (const param of ["idp", "workspace", "email", "token", "invitation"]) {
+ redirectURL.searchParams.delete(param);
+ }
+ const redirectPath =
+ redirectURL.pathname + redirectURL.search + redirectURL.hash;
+ if (redirectPath !== "/" && !url.searchParams.get("redirect")) {
+ query.redirect = redirectPath;
+ }
+ return query;
+ }),
loadSubscription: vi.fn(async () => undefined),
fetchWorkspaceIamPolicy: vi.fn(async () => undefined),
loadWorkspaceList: vi.fn(async () => undefined),
@@ -22,7 +61,8 @@ vi.mock("react-i18next", () => ({
}));
vi.mock("react-router-dom", () => ({
- useMatches: () => [{ handle: { name: "workspace.dashboard" } }],
+ useLocation: () => mocks.location,
+ useMatches: () => [{ handle: { name: mocks.routeName } }],
useNavigate: () => mocks.navigate,
}));
@@ -31,15 +71,19 @@ vi.mock("@/react/components/auth/InactiveRemindModal", () => ({
}));
vi.mock("@/react/router/guard", () => ({
+ buildSigninRedirectQuery: mocks.buildSigninRedirectQuery,
isAuthRelatedRoute: () => false,
}));
vi.mock("@/react/router/handles", () => ({
+ AUTH_SIGNIN_MODULE: "auth.signin",
+ WORKSPACE_ROUTE_403: "error.403",
+ WORKSPACE_ROUTE_404: "error.404",
WORKSPACE_ROOT_MODULE: "workspace.root",
}));
vi.mock("@/react/router/navigation", () => ({
- resolvePath: () => "/",
+ resolvePath: mocks.resolvePath,
}));
vi.mock("@/store", () => ({
@@ -64,7 +108,7 @@ vi.mock("@/react/stores/app", async () => {
currentUserName: initialUser.name,
unauthenticatedOccurred: false,
isSelfEmailUpdate: false,
- isLoggedIn: () => true,
+ isLoggedIn: () => mocks.session.isLoggedIn,
loadSubscription: mocks.loadSubscription,
fetchWorkspaceIamPolicy: mocks.fetchWorkspaceIamPolicy,
loadWorkspaceList: mocks.loadWorkspaceList,
@@ -85,6 +129,11 @@ describe("AuthGate", () => {
beforeEach(() => {
vi.useFakeTimers();
+ mocks.session.isLoggedIn = true;
+ mocks.routeName = "workspace.dashboard";
+ mocks.location.pathname = "/projects";
+ mocks.location.search = "";
+ mocks.location.hash = "";
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
@@ -124,6 +173,69 @@ describe("AuthGate", () => {
expect(container.querySelector("[role='status']")).toBeNull();
});
+ test("redirects protected routes to signin when the session is logged out", async () => {
+ mocks.session.isLoggedIn = false;
+
+ await act(async () => {
+ root.render(
+ <AuthGate>
+ <div data-testid="page">Page</div>
+ </AuthGate>
+ );
+ });
+
+ expect(mocks.navigate).toHaveBeenCalledWith("/auth?redirect=%2Fprojects", {
+ replace: true,
+ });
+ expect(container.querySelector("[data-testid='page']")).toBeNull();
+ expect(container.querySelector("[role='status']")).not.toBeNull();
+ });
+
+ test("preserves signin query params outside the redirect target", async () => {
+ mocks.session.isLoggedIn = false;
+ mocks.location.search =
+ "?idp=idp-1&email=alice%40example.com&foo=bar&invitation=invite-1";
+ mocks.location.hash = "#section";
+
+ await act(async () => {
+ root.render(
+ <AuthGate>
+ <div data-testid="page">Page</div>
+ </AuthGate>
+ );
+ });
+
+ expect(mocks.resolvePath).toHaveBeenCalledWith("auth.signin", {
+ query: {
+ idp: "idp-1",
+ email: "[email protected]",
+ invitation: "invite-1",
+ redirect: "/projects?foo=bar#section",
+ },
+ });
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ "/auth?idp=idp-1&email=alice%40example.com&invitation=invite-1&redirect=%2Fprojects%3Ffoo%3Dbar%23section",
+ { replace: true }
+ );
+ });
+
+ test("keeps public error routes visible when the session is logged out", async () => {
+ mocks.session.isLoggedIn = false;
+ mocks.routeName = "error.404";
+ mocks.location.pathname = "/404";
+
+ await act(async () => {
+ root.render(
+ <AuthGate>
+ <div data-testid="page">Page</div>
+ </AuthGate>
+ );
+ });
+
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(container.querySelector("[data-testid='page']")).not.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 bfe8313dd8..76a6fc9b10 100644
--- a/frontend/src/react/app/AuthGate.tsx
+++ b/frontend/src/react/app/AuthGate.tsx
@@ -1,10 +1,18 @@
import { Loader2 } from "lucide-react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { useMatches, useNavigate } from "react-router-dom";
+import { useLocation, useMatches, useNavigate } from "react-router-dom";
import { InactiveRemindModal } from "@/react/components/auth/InactiveRemindModal";
-import { isAuthRelatedRoute } from "@/react/router/guard";
-import { WORKSPACE_ROOT_MODULE } from "@/react/router/handles";
+import {
+ buildSigninRedirectQuery,
+ isAuthRelatedRoute,
+} from "@/react/router/guard";
+import {
+ AUTH_SIGNIN_MODULE,
+ WORKSPACE_ROOT_MODULE,
+ WORKSPACE_ROUTE_403,
+ WORKSPACE_ROUTE_404,
+} from "@/react/router/handles";
import { resolvePath } from "@/react/router/navigation";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
@@ -26,6 +34,7 @@ export function AuthGate({ children }: { children: ReactNode }) {
const { t } = useTranslation();
const navigate = useNavigate();
+ const location = useLocation();
const matches = useMatches();
const currentRouteName = (
matches.at(-1)?.handle as { name?: string } | undefined
@@ -33,11 +42,28 @@ export function AuthGate({ children }: { children: ReactNode }) {
const isAuthRoute = Boolean(
currentRouteName && isAuthRelatedRoute(currentRouteName)
);
+ const isPublicRoute =
+ currentRouteName === WORKSPACE_ROUTE_403 ||
+ currentRouteName === WORKSPACE_ROUTE_404;
const currentUserWorkspace = currentUser?.workspace ?? "";
const currentUserGroupsKey = (currentUser?.groups ?? []).join("\0");
+ const currentPath = `${location.pathname}${location.search}${location.hash}`;
+ const shouldRedirectToSignin = !isLoggedIn && !isAuthRoute && !isPublicRoute;
const [ready, setReady] = useState(false);
+ useEffect(() => {
+ if (!shouldRedirectToSignin) return;
+ navigate(
+ resolvePath(AUTH_SIGNIN_MODULE, {
+ query: buildSigninRedirectQuery(
+ new URL(currentPath, window.location.origin)
+ ),
+ }),
+ { replace: true }
+ );
+ }, [currentPath, navigate, shouldRedirectToSignin]);
+
// Load workspace-scoped data once authenticated, then reveal the app.
useEffect(() => {
const store = useAppStore.getState();
@@ -108,7 +134,7 @@ export function AuthGate({ children }: { children: ReactNode }) {
return (
<>
- {ready ? (
+ {ready && !shouldRedirectToSignin ? (
children
) : (
<div className="flex items-center justify-center h-screen">
diff --git a/frontend/src/react/router/guard.test.ts b/frontend/src/react/router/guard.test.ts
index f4a88057cc..93dc717640 100644
--- a/frontend/src/react/router/guard.test.ts
+++ b/frontend/src/react/router/guard.test.ts
@@ -35,7 +35,7 @@ vi.mock("@/plugins/ai/store", () => ({
useConversationStore: { getState: () => ({ reset: vi.fn() }) },
}));
-import { rootGuard } from "./guard";
+import { buildSigninRedirectQuery, rootGuard } from "./guard";
import {
AUTH_2FA_SETUP_MODULE,
AUTH_OAUTH_CALLBACK_MODULE,
@@ -113,6 +113,21 @@ describe("rootGuard", () => {
expect(target).toBe("/auth?redirect=%2Fprojects%2Fp1");
});
+ test("builds signin query while stripping signin-only params from redirect", () => {
+ expect(
+ buildSigninRedirectQuery(
+ new URL(
+ "https://app.example.com/projects?idp=idp-1&email=alice%40example.com&foo=bar&invitation=invite-1#section"
+ )
+ )
+ ).toEqual({
+ idp: "idp-1",
+ email: "[email protected]",
+ invitation: "invite-1",
+ redirect: "/projects?foo=bar#section",
+ });
+ });
+
test("enforces 2FA setup when required", () => {
session.isLoggedIn = true;
session.hasTwoFa = true;
diff --git a/frontend/src/react/router/guard.ts b/frontend/src/react/router/guard.ts
index 5da3f8b346..75879af5ec 100644
--- a/frontend/src/react/router/guard.ts
+++ b/frontend/src/react/router/guard.ts
@@ -63,6 +63,21 @@ function stripSigninQueryParams(fullPath: string): string {
return url.pathname + url.search + url.hash;
}
+export function buildSigninRedirectQuery(url: URL): Record<string, string> {
+ const query: Record<string, string> = {};
+ // Forward signin-only query params (consumed by the signin page).
+ for (const param of SIGNIN_QUERY_PARAMS) {
+ const value = url.searchParams.get(param);
+ if (value) query[param] = value;
+ }
+ const fullPath = url.pathname + url.search + url.hash;
+ // Set redirect if not root and not already set; strip signin-only params.
+ if (fullPath !== "/" && !url.searchParams.get("redirect")) {
+ query["redirect"] = stripSigninQueryParams(fullPath);
+ }
+ return query;
+}
+
// Route-name prefixes that an authenticated user may always access.
const ALLOWED_ROUTE_PATTERNS = [
ENVIRONMENT_V1_ROUTE_DASHBOARD,
@@ -217,18 +232,11 @@ export function rootGuard({
// Require authentication for all other pages.
if (!isLoggedIn) {
- const query: Record<string, string> = {};
- // Forward signin-only query params (consumed by the signin page).
- for (const param of SIGNIN_QUERY_PARAMS) {
- const value = url.searchParams.get(param);
- if (value) query[param] = value;
- }
- const fullPath = url.pathname + url.search + url.hash;
- // Set redirect if not root and not already set; strip signin-only params.
- if (fullPath !== "/" && !url.searchParams.get("redirect")) {
- query["redirect"] = stripSigninQueryParams(fullPath);
- }
- return redirect(resolvePath(AUTH_SIGNIN_MODULE, { query }));
+ return redirect(
+ resolvePath(AUTH_SIGNIN_MODULE, {
+ query: buildSigninRedirectQuery(url),
+ })
+ );
}
// Enforce 2FA setup if required.
diff --git a/frontend/src/react/stores/app/auth.ts b/frontend/src/react/stores/app/auth.ts
index d1df5c5168..d9ad9a2833 100644
--- a/frontend/src/react/stores/app/auth.ts
+++ b/frontend/src/react/stores/app/auth.ts
@@ -108,7 +108,11 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
// Don't cache failures — the next call (e.g., after login) should
// retry. Without this, a pre-login failure permanently prevents
// the React store from loading the authenticated user.
- set({ currentUser: undefined, currentUserRequest: undefined });
+ set({
+ currentUser: undefined,
+ currentUserName: undefined,
+ currentUserRequest: undefined,
+ });
return undefined;
});
set({ currentUserRequest: request });
diff --git a/frontend/src/react/stores/app/index.test.ts b/frontend/src/react/stores/app/index.test.ts
index d6762c5918..002708a263 100644
--- a/frontend/src/react/stores/app/index.test.ts
+++ b/frontend/src/react/stores/app/index.test.ts
@@ -418,6 +418,37 @@ describe("useAppStore", () => {
expect(state.removeRecentVisit).toBeTypeOf("function");
});
+ test("keeps the signed-in identity when marking the session expired", () => {
+ const store = createAppStore();
+ store.setState({
+ currentUser: user,
+ currentUserName: user.name,
+ });
+
+ store.getState().setUnauthenticatedOccurred(true);
+
+ expect(store.getState().unauthenticatedOccurred).toBe(true);
+ expect(store.getState().currentUser).toBe(user);
+ expect(store.getState().currentUserName).toBe(user.name);
+ expect(store.getState().isLoggedIn()).toBe(true);
+ });
+
+ test("keeps the signed-in identity when current-user refresh has a transient failure", async () => {
+ mocks.getCurrentUser.mockRejectedValue(new Error("network unavailable"));
+ const store = createAppStore();
+ store.setState({
+ currentUser: user,
+ currentUserName: user.name,
+ });
+
+ const result = await store.getState().fetchCurrentUser();
+
+ expect(result).toBeUndefined();
+ expect(store.getState().currentUser).toBe(user);
+ expect(store.getState().currentUserName).toBe(user.name);
+ expect(store.getState().isLoggedIn()).toBe(true);
+ });
+
test("lists groups and populates the group cache", async () => {
mocks.listGroups.mockResolvedValue({
groups: [groupA, groupB],