The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Replace redux-auth-wrapper with guard components (#77259)
Romeo Van Snick9a6f10f9dca6
diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjsindex 29d494eaf58..2e7d24f8b24 100644--- a/frontend/lint/module-boundaries.mjs+++ b/frontend/lint/module-boundaries.mjs@@ -191,8 +191,6 @@ const elements = ["frontend/src/metabase/reducers-public.ts","frontend/src/metabase/routes.tsx","frontend/src/metabase/routes-embed.tsx",- "frontend/src/metabase/route-guards.tsx",- "frontend/src/metabase/route-guards.unit.spec.tsx","frontend/src/metabase/LoadCurrentUser.tsx","frontend/src/metabase/LoadCurrentUser.unit.spec.tsx","frontend/src/metabase/routes-public.tsx",diff --git a/frontend/src/metabase/admin/utils.ts b/frontend/src/metabase/admin/utils.tsindex 7b722a091f0..4ef193abf82 100644--- a/frontend/src/metabase/admin/utils.ts+++ b/frontend/src/metabase/admin/utils.ts@@ -1,27 +1,20 @@import { useLayoutEffect } from "react";-import { connectedReduxRedirect } from "redux-auth-wrapper/history3/redirect";import { shouldShowTenantsUpsell } from "metabase/admin/people/selectors";-import { connect, metabaseReduxContext } from "metabase/redux";+import { connect } from "metabase/redux";import type { State } from "metabase/redux/store";import type { AdminPath } from "metabase/redux/store/admin";-import { push, replace, routerActions } from "metabase/router";+import { push, replace } from "metabase/router";+import { createRedirectGuard } from "metabase/router/guards";import { getAdminPaths } from "metabase/selectors/admin";import { getSetting } from "metabase/selectors/settings";-export const createAdminRouteGuard = (routeKey: string) => {- const Wrapper = connectedReduxRedirect<any, State>({- wrapperDisplayName: `CanAccess(${routeKey})`,- redirectPath: "/unauthorized",- allowRedirectBack: false,- authenticatedSelector: (state) =>+export const createAdminRouteGuard = (routeKey: string) =>+ createRedirectGuard(+ (state) =>getAdminPaths(state)?.find((path) => path.key === routeKey) != null,- redirectAction: routerActions.replace,- context: metabaseReduxContext,- });-- return Wrapper(({ children }) => children);-};+ "/unauthorized",+ );const mapStateToProps = (state: State, props: { location: Location }) => ({adminItems: getAdminPaths(state),@@ -54,17 +47,10 @@ export const RedirectToAllowedSettings = connect(mapDispatchToProps,)(RedirectToAllowedSettingsInner);-export const createTenantsRouteGuard = () => {- const Wrapper = connectedReduxRedirect<any, State>({- wrapperDisplayName: "CanAccessTenants",- redirectPath: "/admin/people",- allowRedirectBack: false,- authenticatedSelector: (state) =>+export const createTenantsRouteGuard = () =>+ createRedirectGuard(+ (state) =>getAdminPaths(state)?.find((path) => path.key === "people") != null &&(getSetting(state, "use-tenants") || shouldShowTenantsUpsell(state)),- redirectAction: routerActions.replace,- context: metabaseReduxContext,- });-- return Wrapper(({ children }) => children);-};+ "/admin/people",+ );diff --git a/frontend/src/metabase/common/data-studio/selectors.ts b/frontend/src/metabase/common/data-studio/selectors.tsindex fe00e1fd9cf..6ec87d798c1 100644--- a/frontend/src/metabase/common/data-studio/selectors.ts+++ b/frontend/src/metabase/common/data-studio/selectors.ts@@ -3,7 +3,7 @@ import type { State } from "metabase/redux/store";import { getIsEmbeddingIframe } from "metabase/selectors/embed";import { getUserIsAdmin, getUserIsAnalyst } from "metabase/selectors/user";-// Must be in sync with CanAccessDataStudio in frontend/src/metabase/route-guards.tsx+// Must be in sync with CanAccessDataStudio in frontend/src/metabase/router/guards.tsxexport function canAccessDataStudio(state: State) {if (getIsEmbeddingIframe(state)) {return false;diff --git a/frontend/src/metabase/route-guards.tsx b/frontend/src/metabase/route-guards.tsxdeleted file mode 100644index b9bb49fcd9e..00000000000--- a/frontend/src/metabase/route-guards.tsx+++ /dev/null@@ -1,157 +0,0 @@-import { connectedReduxRedirect } from "redux-auth-wrapper/history3/redirect";--import { canAccessDataStudio } from "metabase/common/data-studio/selectors";-import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";-import { metabaseReduxContext } from "metabase/redux";-import type { State } from "metabase/redux/store";-import { routerActions } from "metabase/router";-import { getAdminPaths } from "metabase/selectors/admin";-import { getCanAccessOnboardingPage } from "metabase/selectors/onboarding";-import { getSetting } from "metabase/selectors/settings";-import { isSameOrSiteUrlOrigin } from "metabase/utils/dom";--import { getIsEmbeddingIframe } from "./selectors/embed";--type Props = { children: React.ReactElement };--/** Paths that are handled by the backend server, not the frontend SPA router. */-export const BACKEND_ONLY_PATH_PREFIXES = ["/oauth/", "/auth/sso/"];--export const isBackendOnlyPath = (path: string): boolean =>- BACKEND_ONLY_PATH_PREFIXES.some((prefix) => path.startsWith(prefix));--const getRedirectUrl = () => {- const params = new URLSearchParams(window.location.search);- const redirectUrlParam = params.get("redirect");-- return redirectUrlParam != null && isSameOrSiteUrlOrigin(redirectUrlParam)- ? redirectUrlParam- : "/";-};--const MetabaseIsSetup = connectedReduxRedirect<Props, State>({- // eslint-disable-next-line metabase/no-literal-metabase-strings -- Not a user facing string- wrapperDisplayName: "MetabaseIsSetup",- redirectPath: "/setup",- allowRedirectBack: false,- authenticatedSelector: (state) => getSetting(state, "has-user-setup"),- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--const AvailableInEmbedding = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "AvailableInEmbedding",- redirectPath: "/unauthorized",- allowRedirectBack: false,- authenticatedSelector: (state) => !getIsEmbeddingIframe(state),- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--const UserIsAuthenticated = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "UserIsAuthenticated",- redirectPath: "/auth/login",- authenticatedSelector: (state) => !!state.currentUser,- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--const UserIsAdmin = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "UserIsAdmin",- redirectPath: "/unauthorized",- allowRedirectBack: false,- authenticatedSelector: (state) =>- Boolean(state.currentUser && state.currentUser.is_superuser),- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--const UserIsNotAuthenticated = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "UserIsNotAuthenticated",- redirectPath: () => getRedirectUrl(),- allowRedirectBack: false,- authenticatingSelector: (state) =>- state.auth.loginPending || !state.auth.redirect,- authenticatedSelector: (state) => !state.currentUser,- redirectAction: (location: {- pathname: string;- query?: Record<string, string>;- }) => {- if (isBackendOnlyPath(location.pathname)) {- const params = new URLSearchParams(location.query);- const qs = params.toString();- const url = qs ? `${location.pathname}?${qs}` : location.pathname;- window.location.replace(url);- return routerActions.replace("/");- }- return routerActions.replace(location);- },- context: metabaseReduxContext,-});--const UserCanAccessSettings = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "UserCanAccessSettings",- redirectPath: "/unauthorized",- allowRedirectBack: false,- authenticatedSelector: (state) => (getAdminPaths(state)?.length ?? 0) > 0,- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--const UserCanAccessOnboarding = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "UserCanAccessOnboarding",- redirectPath: "/",- allowRedirectBack: false,- authenticatedSelector: (state) => getCanAccessOnboardingPage(state),- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--const UserCanAccessDataModel = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "UserCanAccessDataModel",- redirectPath: "/unauthorized",- allowRedirectBack: false,- authenticatedSelector: (state) =>- PLUGIN_FEATURE_LEVEL_PERMISSIONS.canAccessDataModel(state),- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--const UserCanAccessDataStudio = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "UserCanAccessDataStudio",- redirectPath: "/unauthorized",- allowRedirectBack: false,- authenticatedSelector: (state) => canAccessDataStudio(state),- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--export const IsAuthenticated = MetabaseIsSetup(- UserIsAuthenticated(({ children }) => children),-);-export const IsAdmin = MetabaseIsSetup(- UserIsAuthenticated(UserIsAdmin(({ children }) => children)),-);--export const IsNotAuthenticated = MetabaseIsSetup(- UserIsNotAuthenticated(({ children }) => children),-);--export const CanAccessSettings = MetabaseIsSetup(- UserIsAuthenticated(UserCanAccessSettings(({ children }) => children)),-);--export const CanAccessOnboarding = UserCanAccessOnboarding(- ({ children }) => children,-);--// Must be in sync with canAccessDataStudio in frontend/src/metabase/data-studio/selectors.ts-export const CanAccessDataStudio = MetabaseIsSetup(- UserIsAuthenticated(- UserCanAccessDataStudio(AvailableInEmbedding(({ children }) => children)),- ),-);--export const CanAccessDataModel = UserCanAccessDataModel(- ({ children }) => children,-);diff --git a/frontend/src/metabase/route-guards.unit.spec.tsx b/frontend/src/metabase/route-guards.unit.spec.tsxdeleted file mode 100644index 288555bbba2..00000000000--- a/frontend/src/metabase/route-guards.unit.spec.tsx+++ /dev/null@@ -1,152 +0,0 @@-import { type Context, createContext } from "react";-import { connectedReduxRedirect } from "redux-auth-wrapper/history3/redirect";--import { renderWithProviders, screen, waitFor } from "__support__/ui";-import { metabaseReduxContext } from "metabase/redux/context";-import { createMockState } from "metabase/redux/store/mocks";-import { Route, routerActions } from "metabase/router";--import {- IsAuthenticated,- IsNotAuthenticated,- isBackendOnlyPath,-} from "./route-guards";--describe("route-guards", () => {- describe("patched redux-auth-wrapper", () => {- it("connectedReduxRedirect should throw an error if no context is provided", async () => {- expect(() => connectedReduxRedirect({} as any)).toThrow(- "you must provide a custom context",- );- });-- it("connectedReduxRedirect should be able to use same context as the main application", async () => {- let selectorState: any;- const RouteGuard = setupRouteGuard({- // leverage the same context used by the main application- context: metabaseReduxContext,- authenticatedSelector: (state) => {- selectorState = state;- return !!state.auth.VAL_ONLY_IN_THIS_CTX;- },- });-- const text = "User can see since context is shared";- const state = { auth: { VAL_ONLY_IN_THIS_CTX: true } };- renderWithProviders(<RouteGuard>{text}</RouteGuard>, {- storeInitialState: createMockState(state as any),- });-- expect(selectorState.auth.VAL_ONLY_IN_THIS_CTX).toBe(true);- expect(screen.getByText(text)).toBeInTheDocument();- });-- it("connectedReduxRedirect should be able to use a different context than the main application", async () => {- let selectorState: any;- const RouteGuard = setupRouteGuard({- // provide a different context than the one that will get created within renderWithProviders- context: createContext({- store: {- dispatch: () => {},- subscribe: () => {},- getState: () => ({ auth: { VAL_ONLY_IN_THIS_CTX: false } }),- },- }),- authenticatedSelector: (state) => {- selectorState = state;- return !!state.auth.VAL_ONLY_IN_THIS_CTX;- },- });-- const text = "User should not be able to see this";- const state = { auth: { VAL_ONLY_IN_THIS_CTX: true } };- renderWithProviders(<RouteGuard>{text}</RouteGuard>, {- storeInitialState: createMockState(state as any),- });-- expect(selectorState.auth.VAL_ONLY_IN_THIS_CTX).toBe(false);- expect(screen.queryByText(text)).not.toBeInTheDocument();- });- });-- describe("redirect-after-login flow (UXW-3939)", () => {- it("UserIsAuthenticated should preserve original path as ?redirect= when sending logged-out user to /auth/login", async () => {- const settings = {- "has-user-setup": true,- } as any;- const state = createMockState({- currentUser: undefined,- settings: { values: settings } as any,- });-- const Dashboard = () => <div>protected dashboard</div>;- const LoginPage = () => <div>login page</div>;-- const { history } = renderWithProviders(- <>- <Route component={IsAuthenticated}>- <Route path="/dashboard/:slug" component={Dashboard} />- </Route>- <Route component={IsNotAuthenticated}>- <Route path="/auth/login" component={LoginPage} />- </Route>- </>,- {- storeInitialState: state,- withRouter: true,- initialRoute: "/dashboard/123",- },- );-- await waitFor(() => {- expect(history?.getCurrentLocation().pathname).toBe("/auth/login");- });-- const location = history!.getCurrentLocation();- expect(location.query).toEqual(- expect.objectContaining({ redirect: "/dashboard/123" }),- );- expect(location.search).toContain("redirect");- });- });-- describe("isBackendOnlyPath", () => {- it("should return true for /oauth/ paths", () => {- expect(isBackendOnlyPath("/oauth/authorize")).toBe(true);- expect(isBackendOnlyPath("/oauth/authorize/decision")).toBe(true);- expect(isBackendOnlyPath("/oauth/token")).toBe(true);- });-- it("should return true for /auth/sso/ paths", () => {- expect(isBackendOnlyPath("/auth/sso/slack-connect")).toBe(true);- expect(isBackendOnlyPath("/auth/sso/slack-connect/callback")).toBe(true);- expect(isBackendOnlyPath("/auth/sso/my-provider")).toBe(true);- });-- it("should return false for frontend paths", () => {- expect(isBackendOnlyPath("/")).toBe(false);- expect(isBackendOnlyPath("/auth/login")).toBe(false);- expect(isBackendOnlyPath("/collection/root")).toBe(false);- expect(isBackendOnlyPath("/question/1")).toBe(false);- });-- it("should not match partial prefixes", () => {- expect(isBackendOnlyPath("/oauthx/foo")).toBe(false);- });- });-});--function setupRouteGuard(opts: {- context: Context<any>;- authenticatedSelector: (state: any) => boolean;-}) {- const RouteGuard = connectedReduxRedirect<any, any>({- wrapperDisplayName: "testing",- redirectPath: "/test",- allowRedirectBack: false,- redirectAction: routerActions.replace,- ...opts,- });-- return RouteGuard(({ children }: any) => children);-}diff --git a/frontend/src/metabase/router/guards.tsx b/frontend/src/metabase/router/guards.tsxnew file mode 100644index 00000000000..2fd6d8ad3d0--- /dev/null+++ b/frontend/src/metabase/router/guards.tsx@@ -0,0 +1,215 @@+import { type ReactElement, useEffect } from "react";++import { canAccessDataStudio } from "metabase/common/data-studio/selectors";+import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";+import { useSelector } from "metabase/redux";+import type { State } from "metabase/redux/store";+import { getAdminPaths } from "metabase/selectors/admin";+import { getIsEmbeddingIframe } from "metabase/selectors/embed";+import { getCanAccessOnboardingPage } from "metabase/selectors/onboarding";+import { getSetting } from "metabase/selectors/settings";+import { isSameOrSiteUrlOrigin, replaceLocation } from "metabase/utils/dom";++import { Navigate } from "./Navigate";+import type { Location } from "./types";+import { useLocation } from "./use-location";++type Props = { children: ReactElement };++/** Paths that are handled by the backend server, not the frontend SPA router. */+export const BACKEND_ONLY_PATH_PREFIXES = ["/oauth/", "/auth/sso/"];++export const isBackendOnlyPath = (path: string): boolean =>+ BACKEND_ONLY_PATH_PREFIXES.some((prefix) => path.startsWith(prefix));++const getRedirectUrl = () => {+ const params = new URLSearchParams(window.location.search);+ const redirectUrlParam = params.get("redirect");++ return redirectUrlParam != null && isSameOrSiteUrlOrigin(redirectUrlParam)+ ? redirectUrlParam+ : "/";+};++/**+ * `getRedirectUrl` accepts site-url-origin targets as well as same-origin ones,+ * so it can hand back an absolute URL. The SPA router only understands in-app+ * paths, so split the target into the path to navigate to and whether the SPA+ * can serve that origin at all.+ */+const resolveRedirectTarget = (url: string) => {+ const target = new URL(url, window.location.origin);++ return {+ // Absolute, so a full-page redirect is not re-resolved against the current+ // path (a bare `auth/sso/x` would otherwise land under `/auth/login`).+ href: target.href,+ path: `${target.pathname}${target.search}${target.hash}`,+ isInAppOrigin: target.origin === window.location.origin,+ };+};++const NEVER_AUTHENTICATING = () => false;++type GuardSelectors = {+ isAllowed: (state: State) => boolean;+ isAuthenticating?: (state: State) => boolean;+};++/**+ * Builds a route guard component from redux selectors. When access is denied it+ * renders the element from `renderRedirect` instead of the guarded children.+ *+ * While `isAuthenticating` is true the guard renders nothing (no redirect and no+ * children), so a route is not bounced while its auth state is still resolving.+ */+function createGuard(+ { isAllowed, isAuthenticating = NEVER_AUTHENTICATING }: GuardSelectors,+ renderRedirect: (location: Location) => ReactElement | null,+) {+ return function Guard({ children }: Props) {+ const location = useLocation();+ const allowed = useSelector(isAllowed);+ const authenticating = useSelector(isAuthenticating);++ if (allowed) {+ return children;+ }+ if (authenticating) {+ return null;+ }+ return renderRedirect(location);+ };+}++/**+ * Builds a guard that redirects to a fixed path when access is denied, the+ * common case with no `?redirect=` round-trip.+ */+export function createRedirectGuard(+ isAllowed: (state: State) => boolean,+ redirectPath: string,+) {+ return createGuard({ isAllowed }, () => (+ <Navigate to={redirectPath} replace />+ ));+}++function FullPageRedirect({ to }: { to: string }): null {+ useEffect(() => {+ replaceLocation(to);+ }, [to]);+ return null;+}++const loginUrlWithRedirect = (location: Location) => {+ const from = `${location.pathname}${location.search}`;+ const query = new URLSearchParams({ redirect: from }).toString();+ return `/auth/login?${query}`;+};++const MetabaseIsSetup = createRedirectGuard(+ (state) => getSetting(state, "has-user-setup"),+ "/setup",+);++const AvailableInEmbedding = createRedirectGuard(+ (state) => !getIsEmbeddingIframe(state),+ "/unauthorized",+);++const UserIsAuthenticated = createGuard(+ { isAllowed: (state) => !!state.currentUser },+ (location) => <Navigate to={loginUrlWithRedirect(location)} replace />,+);++const UserIsAdmin = createRedirectGuard(+ (state) => Boolean(state.currentUser && state.currentUser.is_superuser),+ "/unauthorized",+);++const UserIsNotAuthenticated = createGuard(+ {+ isAllowed: (state) => !state.currentUser,+ isAuthenticating: (state) =>+ state.auth.loginPending || !state.auth.redirect,+ },+ () => {+ const { href, path, isInAppOrigin } =+ resolveRedirectTarget(getRedirectUrl());+ const needsFullPageLoad = !isInAppOrigin || isBackendOnlyPath(path);++ return needsFullPageLoad ? (+ <FullPageRedirect to={href} />+ ) : (+ <Navigate to={path} replace />+ );+ },+);++const UserCanAccessSettings = createRedirectGuard(+ (state) => (getAdminPaths(state)?.length ?? 0) > 0,+ "/unauthorized",+);++const UserCanAccessOnboarding = createRedirectGuard(+ (state) => getCanAccessOnboardingPage(state),+ "/",+);++const UserCanAccessDataModel = createRedirectGuard(+ (state) => PLUGIN_FEATURE_LEVEL_PERMISSIONS.canAccessDataModel(state),+ "/unauthorized",+);++const UserCanAccessDataStudio = createRedirectGuard(+ (state) => canAccessDataStudio(state),+ "/unauthorized",+);++export const IsAuthenticated = ({ children }: Props) => (+ <MetabaseIsSetup>+ <UserIsAuthenticated>{children}</UserIsAuthenticated>+ </MetabaseIsSetup>+);++export const IsAdmin = ({ children }: Props) => (+ <MetabaseIsSetup>+ <UserIsAuthenticated>+ <UserIsAdmin>{children}</UserIsAdmin>+ </UserIsAuthenticated>+ </MetabaseIsSetup>+);++export const IsNotAuthenticated = ({ children }: Props) => (+ <MetabaseIsSetup>+ <UserIsNotAuthenticated>{children}</UserIsNotAuthenticated>+ </MetabaseIsSetup>+);++export const CanAccessSettings = ({ children }: Props) => (+ <MetabaseIsSetup>+ <UserIsAuthenticated>+ <UserCanAccessSettings>{children}</UserCanAccessSettings>+ </UserIsAuthenticated>+ </MetabaseIsSetup>+);++export const CanAccessOnboarding = ({ children }: Props) => (+ <UserCanAccessOnboarding>{children}</UserCanAccessOnboarding>+);++// Must be in sync with canAccessDataStudio in frontend/src/metabase/data-studio/selectors.ts+export const CanAccessDataStudio = ({ children }: Props) => (+ <MetabaseIsSetup>+ <UserIsAuthenticated>+ <UserCanAccessDataStudio>+ <AvailableInEmbedding>{children}</AvailableInEmbedding>+ </UserCanAccessDataStudio>+ </UserIsAuthenticated>+ </MetabaseIsSetup>+);++export const CanAccessDataModel = ({ children }: Props) => (+ <UserCanAccessDataModel>{children}</UserCanAccessDataModel>+);diff --git a/frontend/src/metabase/router/guards.unit.spec.tsx b/frontend/src/metabase/router/guards.unit.spec.tsxnew file mode 100644index 00000000000..d5e8e88999a--- /dev/null+++ b/frontend/src/metabase/router/guards.unit.spec.tsx@@ -0,0 +1,240 @@+import { mockSettings } from "__support__/settings";+import { renderWithProviders, waitFor } from "__support__/ui";+import {+ createMockSettingsState,+ createMockState,+} from "metabase/redux/store/mocks";+import { replaceLocation } from "metabase/utils/dom";+import { createMockUser } from "metabase-types/api/mocks";++import {+ IsAdmin,+ IsAuthenticated,+ IsNotAuthenticated,+ isBackendOnlyPath,+} from "./guards";+import { Route } from "./react-router";++jest.mock("metabase/utils/dom", () => ({+ ...jest.requireActual("metabase/utils/dom"),+ replaceLocation: jest.fn(),+}));++const Protected = () => <div>protected</div>;+const LoginPage = () => <div>login page</div>;+const Unauthorized = () => <div>unauthorized</div>;+const Home = () => <div>home</div>;++describe("route-guards", () => {+ describe("redirect-after-login flow (UXW-3939)", () => {+ it("UserIsAuthenticated should preserve original path as ?redirect= when sending logged-out user to /auth/login", async () => {+ const state = createMockState({+ currentUser: undefined,+ settings: createMockSettingsState({ "has-user-setup": true }),+ });++ const Dashboard = () => <div>protected dashboard</div>;++ const { history } = renderWithProviders(+ <>+ <Route component={IsAuthenticated}>+ <Route path="/dashboard/:slug" component={Dashboard} />+ </Route>+ <Route component={IsNotAuthenticated}>+ <Route path="/auth/login" component={LoginPage} />+ </Route>+ </>,+ {+ storeInitialState: state,+ withRouter: true,+ initialRoute: "/dashboard/123",+ },+ );++ await waitFor(() => {+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");+ });++ const location = history!.getCurrentLocation();+ expect(location.query).toEqual(+ expect.objectContaining({ redirect: "/dashboard/123" }),+ );+ expect(location.search).toContain("redirect");+ });+ });++ describe("IsAdmin", () => {+ it("redirects a non-admin user to /unauthorized", async () => {+ const state = createMockState({+ currentUser: createMockUser({ is_superuser: false }),+ settings: createMockSettingsState({ "has-user-setup": true }),+ });++ const { history } = renderWithProviders(+ <>+ <Route component={IsAdmin}>+ <Route path="/admin/settings" component={Protected} />+ </Route>+ <Route path="/unauthorized" component={Unauthorized} />+ </>,+ {+ storeInitialState: state,+ withRouter: true,+ initialRoute: "/admin/settings",+ },+ );++ await waitFor(() => {+ expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");+ });+ });+ });++ describe("IsNotAuthenticated", () => {+ it("bounces a logged-in user off /auth/login", async () => {+ const state = createMockState({+ currentUser: createMockUser(),+ auth: { loginPending: false, redirect: true },+ settings: createMockSettingsState({ "has-user-setup": true }),+ });++ const { history } = renderWithProviders(+ <>+ <Route component={IsNotAuthenticated}>+ <Route path="/auth/login" component={LoginPage} />+ </Route>+ <Route path="/" component={Home} />+ </>,+ {+ storeInitialState: state,+ withRouter: true,+ initialRoute: "/auth/login",+ },+ );++ await waitFor(() => {+ expect(history?.getCurrentLocation().pathname).toBe("/");+ });+ });+ });++ describe("IsNotAuthenticated redirect targets", () => {+ const ORIGIN = "http://localhost";+ const replaceLocationMock = jest.mocked(replaceLocation);++ const setup = (redirectParam: string) => {+ window.history.replaceState(+ {},+ "",+ `/auth/login?redirect=${encodeURIComponent(redirectParam)}`,+ );++ const state = createMockState({+ currentUser: createMockUser(),+ auth: { loginPending: false, redirect: true },+ settings: createMockSettingsState({ "has-user-setup": true }),+ });++ const { history } = renderWithProviders(+ <Route component={IsNotAuthenticated}>+ <Route path="/auth/login" component={LoginPage} />+ </Route>,+ {+ storeInitialState: state,+ withRouter: true,+ initialRoute: "/auth/login",+ },+ );++ return { history };+ };++ afterEach(() => {+ replaceLocationMock.mockClear();+ window.history.replaceState({}, "", "/");+ // reset the global MetabaseSettings singleton mutated by mockSettings+ mockSettings();+ });++ it("does a full-page redirect for a relative backend-only path", async () => {+ const { history } = setup("/auth/sso/google");++ await waitFor(() => {+ expect(replaceLocationMock).toHaveBeenCalledWith(+ `${ORIGIN}/auth/sso/google`,+ );+ });+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");+ });++ it("normalizes a relative backend-only target without a leading slash", async () => {+ const { history } = setup("auth/sso/google");++ await waitFor(() => {+ expect(replaceLocationMock).toHaveBeenCalledWith(+ `${ORIGIN}/auth/sso/google`,+ );+ });+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");+ });++ it("does a full-page redirect for an absolute same-origin backend-only URL", async () => {+ const { history } = setup(`${ORIGIN}/auth/sso/google`);++ await waitFor(() => {+ expect(replaceLocationMock).toHaveBeenCalledWith(+ `${ORIGIN}/auth/sso/google`,+ );+ });+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");+ });++ it("navigates in-app to the path of an absolute same-origin URL", async () => {+ const { history } = setup(`${ORIGIN}/dashboard/1`);++ await waitFor(() => {+ expect(history?.getCurrentLocation().pathname).toBe("/dashboard/1");+ });+ expect(replaceLocationMock).not.toHaveBeenCalled();+ });++ it("does a full-page redirect for a site-url URL on another origin", async () => {+ const siteUrl = "https://metabase.example.com";+ mockSettings({ "site-url": siteUrl });++ const { history } = setup(`${siteUrl}/dashboard/1`);++ await waitFor(() => {+ expect(replaceLocationMock).toHaveBeenCalledWith(+ `${siteUrl}/dashboard/1`,+ );+ });+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");+ });+ });++ describe("isBackendOnlyPath", () => {+ it("should return true for /oauth/ paths", () => {+ expect(isBackendOnlyPath("/oauth/authorize")).toBe(true);+ expect(isBackendOnlyPath("/oauth/authorize/decision")).toBe(true);+ expect(isBackendOnlyPath("/oauth/token")).toBe(true);+ });++ it("should return true for /auth/sso/ paths", () => {+ expect(isBackendOnlyPath("/auth/sso/slack-connect")).toBe(true);+ expect(isBackendOnlyPath("/auth/sso/slack-connect/callback")).toBe(true);+ expect(isBackendOnlyPath("/auth/sso/my-provider")).toBe(true);+ });++ it("should return false for frontend paths", () => {+ expect(isBackendOnlyPath("/")).toBe(false);+ expect(isBackendOnlyPath("/auth/login")).toBe(false);+ expect(isBackendOnlyPath("/collection/root")).toBe(false);+ expect(isBackendOnlyPath("/question/1")).toBe(false);+ });++ it("should not match partial prefixes", () => {+ expect(isBackendOnlyPath("/oauthx/foo")).toBe(false);+ });+ });+});diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsxindex e1e8359d4c6..7919712b484 100644--- a/frontend/src/metabase/routes.tsx+++ b/frontend/src/metabase/routes.tsx@@ -66,12 +66,6 @@ import SegmentListContainer from "metabase/reference/segments/SegmentListContainimport SegmentQuestionsContainer from "metabase/reference/segments/SegmentQuestionsContainer";import SegmentRevisionsContainer from "metabase/reference/segments/SegmentRevisionsContainer";import { IndexRedirect, IndexRoute, Redirect, Route } from "metabase/router";-import { SearchApp } from "metabase/search/containers/SearchApp";-import { RedirectIfSetup } from "metabase/setup/components/RedirectIfSetup";-import { Setup } from "metabase/setup/components/Setup";-import getCollectionTimelineRoutes from "metabase/timelines/collections/routes";--import { LoadCurrentUser } from "./LoadCurrentUser";import {CanAccessDataModel,CanAccessDataStudio,@@ -80,7 +74,13 @@ import {IsAdmin,IsAuthenticated,IsNotAuthenticated,-} from "./route-guards";+} from "metabase/router/guards";+import { SearchApp } from "metabase/search/containers/SearchApp";+import { RedirectIfSetup } from "metabase/setup/components/RedirectIfSetup";+import { Setup } from "metabase/setup/components/Setup";+import getCollectionTimelineRoutes from "metabase/timelines/collections/routes";++import { LoadCurrentUser } from "./LoadCurrentUser";import { createEntityIdRedirect } from "./routes-stable-id-aware";type AppStore = Store<State> & {diff --git a/frontend/src/metabase/transforms/route-guards.tsx b/frontend/src/metabase/transforms/route-guards.tsxindex f8d9a96330f..6d36f10b8aa 100644--- a/frontend/src/metabase/transforms/route-guards.tsx+++ b/frontend/src/metabase/transforms/route-guards.tsx@@ -1,24 +1,10 @@-import { connectedReduxRedirect } from "redux-auth-wrapper/history3/redirect";--import { metabaseReduxContext } from "metabase/redux";-import type { State } from "metabase/redux/store";-import { routerActions } from "metabase/router";+import { createRedirectGuard } from "metabase/router/guards";import { getSetting } from "metabase/selectors/settings";import * as Urls from "metabase/urls";-type Props = { children: React.ReactElement };--const TransformsNotDisabledGuard = connectedReduxRedirect<Props, State>({- wrapperDisplayName: "TransformsNotDisabled",- redirectPath: Urls.dataStudioSettings(),- allowRedirectBack: false,- authenticatedSelector: (state) =>+export const TransformsNotDisabled = createRedirectGuard(+ (state) =>!getSetting(state, "transforms-setup-complete") ||getSetting(state, "transforms-enabled"),- redirectAction: routerActions.replace,- context: metabaseReduxContext,-});--export const TransformsNotDisabled = TransformsNotDisabledGuard(- ({ children }) => children,+ Urls.dataStudioSettings(),);diff --git a/frontend/src/metabase/utils/dom.ts b/frontend/src/metabase/utils/dom.tsindex 61c3b0dc9da..e694111a83d 100644--- a/frontend/src/metabase/utils/dom.ts+++ b/frontend/src/metabase/utils/dom.ts@@ -242,6 +242,14 @@ export function redirect(url: string): void {window.location.href = url;}+/**+ * Wrapper around window.location is used as we can't override window in jest with jsdom anymore+ * https://github.com/jsdom/jsdom/issues/3492+ */+export function replaceLocation(url: string): void {+ window.location.replace(url);+}+export function openSaveDialog(fileName: string, fileContent: Blob): void {const url = URL.createObjectURL(fileContent);const link = document.createElement("a");