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
Key guest embed tokens per instance instead of one shared slot (#81351)
Mahatthana (Kelvin) Nomsawadi63057ee4851d
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-token-refresh.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-token-refresh.cy.spec.tsindex f4b6db03429..f12ae9319f0 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-token-refresh.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-token-refresh.cy.spec.ts@@ -186,6 +186,19 @@ describe("scenarios > embedding > sdk iframe embedding > guest token refresh", (});}+ // Takes no parameters, unlike the question the initial token names, so a token+ // swap between the two also changes which parameters are valid.+ function createOtherStandaloneQuestion() {+ createQuestion({+ name: "Products",+ enable_embedding: true,+ embedding_type: "guest-embed",+ query: { "source-table": PRODUCTS_ID },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("otherQuestionId");+ });+ }+function createQuestionWithPriceFilter() {H.createNativeQuestion({name: "Products with price filter",@@ -679,6 +692,94 @@ describe("scenarios > embedding > sdk iframe embedding > guest token refresh", (});});+ describe("provider returns a different resource", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: () => {+ createQuestionWithCategoryFilter();+ createOtherStandaloneQuestion();+ },+ });+ });++ it("switches to the question the refreshed token names", () => {+ cy.get<number>("@questionId").then((questionId) => {+ cy.get<number>("@otherQuestionId").then((otherQuestionId) => {+ signJwt({ questionId, expirationSeconds: 600 }).then(+ (initialToken) => {+ signJwt({+ questionId: otherQuestionId,+ expirationSeconds: 600,+ }).then((freshToken) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({ statusCode: 200, body: { jwt: freshToken } });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-question",+ attributes: { token: initialToken },+ },+ ],+ });++ // Apply a filter value so the question runs with a parameter+ // set, which is the state that has to survive the swap.+ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByLabelText("Category").click();+ H.popover().within(() => {+ cy.findByRole("checkbox", { name: "Doohickey" }).click();+ cy.button("Add filter").click();+ });++ H.assertTableData({+ columns: ["ID", "TITLE", "CATEGORY"],+ });+ });++ cy.get("iframe[data-metabase-embed]")+ .its("0.contentWindow")+ .should("exist")+ .then((contentWindow) => {+ contentWindow.FORCE_REFRESH_GUEST_EMBED_TOKEN_IN_CYPRESS = true;+ });++ H.getSimpleEmbedIframeContent().within(() => {+ // The refresh only fires on the next request, so re-running+ // the query with a new filter value is what triggers it.+ cy.findByLabelText("Category").click();+ H.popover().within(() => {+ cy.findByRole("checkbox", { name: "Gadget" }).click();+ cy.button("Update filter").click();+ });++ cy.wait("@guestTokenProvider");+ });++ // The refreshed token names a question that takes no+ // parameters, so the old filter value must not be sent along+ // with it.+ H.getSimpleEmbedIframeContent()+ .findByText(/Unknown parameter/)+ .should("not.exist");++ // "Vendor" is only on the question the refreshed token names.+ H.getSimpleEmbedIframeContent()+ .findByText("Vendor")+ .should("exist");+ });+ },+ );+ });+ });+ });+ });+describe("provider error shows error state", () => {beforeEach(() => {H.prepareGuestEmbedSdkIframeEmbedTest({diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsxindex 05018ef5e27..704bd227cff 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx@@ -3,6 +3,7 @@ import {useCallback,useContext,useEffect,+ useId,useMemo,useState,} from "react";@@ -21,9 +22,13 @@ import { useWarnConflictingParameterProps } from "embedding-sdk-bundle/hooks/priimport { getEffectiveParameterValues } from "embedding-sdk-bundle/lib/controlled-parameters";import { EmbeddingSdkMode } from "embedding-sdk-bundle/lib/modes/EmbeddingSdkMode";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";-import { setInitialGuestToken } from "embedding-sdk-bundle/store/guest-embed";+import {+ clearGuestToken,+ setInitialGuestToken,+} from "embedding-sdk-bundle/store/guest-embed";import {getError,+ getGuestTokenForMount,getIsGuestEmbed,getPlugins,getSessionTokenState,@@ -94,8 +99,13 @@ export const SdkQuestionProvider = ({const dispatch = useSdkDispatch();const navigation = useSdkInternalNavigationOptional();const [isFirstRender, setIsFirstRender] = useState(true);- const { rawToken: tokenFromStore, error: tokenFetchError } =- useSdkSelector(getSessionTokenState);+ // Stable per-mount id: keeps this mount's guest token isolated from any+ // other guest StaticQuestion/StaticDashboard sharing the same MetabaseProvider.+ const mountId = useId();+ const { error: tokenFetchError } = useSdkSelector(getSessionTokenState);+ const tokenFromStore = useSdkSelector((state) =>+ getGuestTokenForMount(state, mountId),+ );const effectiveInitialSqlParameters = getEffectiveParameterValues(sqlParameters,@@ -105,9 +115,18 @@ export const SdkQuestionProvider = ({// Store token so the refresh handler can check expiry. No need to await — not used here.useEffect(() => {if (rawToken && isGuestEmbed) {- dispatch(setInitialGuestToken(rawToken));+ dispatch(setInitialGuestToken({ mountId, token: rawToken }));}- }, [rawToken, isGuestEmbed, dispatch]);+ }, [rawToken, isGuestEmbed, dispatch, mountId]);++ // Own effect: folding this into the one above would clear the token on every+ // rawToken change, leaving a window with no token for the refresh handler.+ useEffect(+ () => () => {+ dispatch(clearGuestToken(mountId));+ },+ [dispatch, mountId],+ );useEffect(() => {setIsFirstRender(false);diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion-multiple-guest-questions.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion-multiple-guest-questions.unit.spec.tsxnew file mode 100644index 00000000000..3afc761384c--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion-multiple-guest-questions.unit.spec.tsx@@ -0,0 +1,191 @@+import fetchMock from "fetch-mock";+import { SignJWT } from "jose";++import {+ mockGetBoundingClientRect,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";+import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";+import {+ createMockLoginStatusState,+ createMockSdkState,+} from "embedding-sdk-bundle/test/mocks/state";+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";+import type { Card, Dataset } from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDataset,+ createMockDatasetData,+} from "metabase-types/api/mocks";++import { StaticQuestion } from "./StaticQuestion";++const SECRET = new TextEncoder().encode("test-secret-key-for-jwt-signing");++const TEST_COLUMN = createMockColumn({+ display_name: "Test Column",+ name: "Test Column",+});++function getMockDataset(row: string) {+ return createMockDataset({+ data: createMockDatasetData({+ cols: [TEST_COLUMN],+ rows: [[row]],+ }),+ });+}++async function createQuestionJwt(questionId: number) {+ return new SignJWT({+ resource: { question: questionId },+ params: {},+ })+ .setProtectedHeader({ alg: "HS256" })+ .sign(SECRET);+}++function setupEmbedCardEndpoints(token: string, card: Card, dataset: Dataset) {+ fetchMock.get(`path:/api/embed/card/${token}`, card);+ fetchMock.get(`path:/api/embed/card/${token}/query`, dataset);+}++describe("StaticQuestion - multiple guest questions", () => {+ beforeAll(() => {+ mockGetBoundingClientRect();+ });++ it("should keep distinct questions when multiple guest StaticQuestions mount under one provider", async () => {+ const rows = ["Alpha", "Bravo"] as const;+ const cards = rows.map((row, index) =>+ createMockCard({+ id: index + 1,+ name: `Question ${row}`,+ }),+ );+ const tokens = await Promise.all(+ cards.map((card) => createQuestionJwt(card.id)),+ );++ const { state } = setupSdkState({+ sdkState: createMockSdkState({+ // Let initGuestEmbed run so /api → /api/embed request rewriting is installed.+ initStatus: createMockLoginStatusState({ status: "uninitialized" }),+ isGuestEmbed: true,+ }),+ });++ cards.forEach((card, index) => {+ setupEmbedCardEndpoints(tokens[index], card, getMockDataset(rows[index]));+ });++ const authConfig = createMockSdkConfig({ isGuest: true });++ const { rerender } = renderWithSDKProviders(+ <div>+ <StaticQuestion token={tokens[0]} />+ </div>,+ {+ componentProviderProps: { authConfig },+ storeInitialState: state,+ },+ );++ await waitFor(() => {+ expect(screen.getByText("Alpha")).toBeInTheDocument();+ });++ // Mount a second guest question under the same provider/store. Each mount+ // keeps its own guest token, so neither re-queries with the other's JWT.+ rerender(+ <div>+ <StaticQuestion token={tokens[0]} />+ <StaticQuestion token={tokens[1]} />+ </div>,+ );++ await waitFor(() => {+ for (const token of tokens) {+ expect(+ fetchMock.callHistory.calls(`path:/api/embed/card/${token}/query`),+ ).not.toHaveLength(0);+ }+ });++ await waitFor(() => {+ const tables = screen.getAllByTestId("table-root");+ const gridcells = screen.getAllByRole("gridcell");++ expect(tables).toHaveLength(rows.length);+ expect(gridcells).toHaveLength(rows.length);++ expect(within(gridcells[0]).getByText("Alpha")).toBeInTheDocument();+ expect(within(gridcells[1]).getByText("Bravo")).toBeInTheDocument();+ expect(screen.queryAllByText("Bravo")).toHaveLength(1);+ expect(screen.queryAllByText("Alpha")).toHaveLength(1);+ });+ });++ it("should query with the new token when a guest question remounts with a different token", async () => {+ const rows = ["Alpha", "Bravo"] as const;+ const cards = rows.map((row, index) =>+ createMockCard({+ id: index + 1,+ name: `Question ${row}`,+ }),+ );+ const tokens = await Promise.all(+ cards.map((card) => createQuestionJwt(card.id)),+ );++ const { state } = setupSdkState({+ sdkState: createMockSdkState({+ // Let initGuestEmbed run so /api → /api/embed request rewriting is installed.+ initStatus: createMockLoginStatusState({ status: "uninitialized" }),+ isGuestEmbed: true,+ }),+ });++ cards.forEach((card, index) => {+ setupEmbedCardEndpoints(tokens[index], card, getMockDataset(rows[index]));+ });++ // guestEmbedProviderUri installs the handler that rewrites every request+ // with the token held in the store.+ const authConfig = createMockSdkConfig({+ isGuest: true,+ guestEmbedProviderUri: "/mock-guest-token-provider",+ });++ const { rerender } = renderWithSDKProviders(+ <StaticQuestion key={tokens[0]} token={tokens[0]} />,+ {+ componentProviderProps: { authConfig },+ storeInitialState: state,+ },+ );++ await waitFor(() => {+ expect(screen.getByText("Alpha")).toBeInTheDocument();+ });++ // The iframe embed route re-keys its children when the token changes, so a+ // new token remounts the component rather than updating it in place.+ rerender(<StaticQuestion key={tokens[1]} token={tokens[1]} />);++ await waitFor(() => {+ expect(+ fetchMock.callHistory.calls(`path:/api/embed/card/${tokens[1]}/query`),+ ).not.toHaveLength(0);+ });++ await waitFor(() => {+ expect(screen.getByText("Bravo")).toBeInTheDocument();+ });+ expect(screen.queryByText("Alpha")).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsxindex 8b916f247aa..29f24887d3e 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx@@ -4,6 +4,7 @@ import {type ReactNode,useCallback,useEffect,+ useId,useMemo,useRef,useState,@@ -35,8 +36,12 @@ import { useSetupContentTranslations } from "embedding-sdk-bundle/hooks/private/import { useWarnConflictingParameterProps } from "embedding-sdk-bundle/hooks/private/use-warn-conflicting-parameter-props";import { getEffectiveParameterValues } from "embedding-sdk-bundle/lib/controlled-parameters";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";-import { setInitialGuestToken } from "embedding-sdk-bundle/store/guest-embed";import {+ clearGuestToken,+ setInitialGuestToken,+} from "embedding-sdk-bundle/store/guest-embed";+import {+ getGuestTokenForMount,getIsGuestEmbed,getPlugins,getSessionTokenState,@@ -262,6 +267,9 @@ const SdkDashboardInner = ({const isGuestEmbed = useSdkSelector(getIsGuestEmbed);const dispatch = useSdkDispatch();const [isFirstRender, setIsFirstRender] = useState(true);+ // Stable per-mount id: keeps this mount's guest token isolated from any+ // other guest StaticQuestion/StaticDashboard sharing the same MetabaseProvider.+ const mountId = useId();useWarnConflictingParameterProps({initialParameters,@@ -280,15 +288,26 @@ const SdkDashboardInner = ({onParametersChange,});- const { rawToken: tokenFromStore, error: tokenFetchError } =- useSdkSelector(getSessionTokenState);+ const { error: tokenFetchError } = useSdkSelector(getSessionTokenState);+ const tokenFromStore = useSdkSelector((state) =>+ getGuestTokenForMount(state, mountId),+ );// Store token so the refresh handler can check expiry. No need to await — not used here.useEffect(() => {if (rawToken && isGuestEmbed) {- dispatch(setInitialGuestToken(rawToken));+ dispatch(setInitialGuestToken({ mountId, token: rawToken }));}- }, [rawToken, isGuestEmbed, dispatch]);+ }, [rawToken, isGuestEmbed, dispatch, mountId]);++ // Own effect: folding this into the one above would clear the token on every+ // rawToken change, leaving a window with no token for the refresh handler.+ useEffect(+ () => () => {+ dispatch(clearGuestToken(mountId));+ },+ [dispatch, mountId],+ );useEffect(() => {setIsFirstRender(false);diff --git a/frontend/src/embedding-sdk-bundle/store/guest-embed/auth.ts b/frontend/src/embedding-sdk-bundle/store/guest-embed/auth.tsindex 4657f2ded1f..9be48ef82b4 100644--- a/frontend/src/embedding-sdk-bundle/store/guest-embed/auth.ts+++ b/frontend/src/embedding-sdk-bundle/store/guest-embed/auth.ts@@ -15,9 +15,19 @@ let refreshGuestSessionPromise: ReturnType<AsyncThunkAction<string | null, unknown, any>> | null = null;-// Sets the initial guest embed token when a component first loads.-export const setInitialGuestToken = createAction<string>(- "sdk/guest-embed/SET_INITIAL_TOKEN",+// Sets the initial guest embed token when a component first loads. Keyed by a+// stable per-mount id so concurrent guest embeds under one+// MetabaseProvider don't overwrite each other's token.+export const setInitialGuestToken = createAction<{+ mountId: string;+ token: string;+}>("sdk/guest-embed/SET_INITIAL_TOKEN");++// Drops a mount's guest token when it unmounts, so a remounted embed (the+// iframe route re-keys its children when the token changes) doesn't leave a+// stale entry behind for getOrRefreshGuestSession to pick up.+export const clearGuestToken = createAction<string>(+ "sdk/guest-embed/CLEAR_TOKEN",);export const setGuestTokenFetchError = createAction<SerializedError | null>(@@ -37,6 +47,9 @@ export const refreshGuestSession = createAsyncThunk(}: {authConfig: MetabaseAuthConfig;expiredToken: string;+ // Unused by the fetch itself; carried on the thunk arg so the reducer can+ // write the refreshed token back to the same guestTokensByMount key.+ mountId: string;}): Promise<string> => {if (authConfig.isGuest && !authConfig.guestEmbedProviderUri) {throw new Error(@@ -61,7 +74,17 @@ export const getOrRefreshGuestSession = createAsyncThunk(// Unjustified type cast. FIXMEconst state = getState() as SdkStoreState;const tokenState = getSessionTokenState(state);- const currentToken = tokenState.rawToken;+ // This thunk only runs for iframe/modular embeds (see the isEmbeddingEajs+ // check below), where each embed gets its own iframe and therefore its+ // own store, and each mount drops its entry on unmount — so there's only+ // ever one guest token in this map.+ // Needs rework for EMB-2295 (guestEmbedProviderUri in the plain SDK): there+ // one store can hold several mounts, and picking an arbitrary key would+ // hand every request the same token again.+ const mountId = Object.keys(tokenState.guestTokensByMount)[0];+ const currentToken = mountId+ ? tokenState.guestTokensByMount[mountId]+ : null;// No token in Redux yet, so we can't check expiration.if (!currentToken) {@@ -102,6 +125,7 @@ export const getOrRefreshGuestSession = createAsyncThunk(refreshGuestSession({authConfig,expiredToken: currentToken,+ mountId,}),);diff --git a/frontend/src/embedding-sdk-bundle/store/reducer.ts b/frontend/src/embedding-sdk-bundle/store/reducer.tsindex 896227939d0..d42d0112f0a 100644--- a/frontend/src/embedding-sdk-bundle/store/reducer.ts+++ b/frontend/src/embedding-sdk-bundle/store/reducer.ts@@ -13,6 +13,7 @@ import type { DashboardTabId } from "metabase-types/api";import { initAuth, refreshTokenAsync } from "./auth";import {+ clearGuestToken,initGuestEmbed,refreshGuestSession,setGuestTokenFetchError,@@ -71,7 +72,7 @@ const initialState: SdkState = {metabaseInstanceVersion: null,token: {token: null,- rawToken: null,+ guestTokensByMount: {},loading: false,error: null,},@@ -95,7 +96,7 @@ export const sdk = createReducer(initialState, (builder) => {builder.addCase(refreshTokenAsync.fulfilled, (state, action) => {state.token = {token: action.payload,- rawToken: null,+ guestTokensByMount: {},loading: false,error: null,};@@ -180,12 +181,14 @@ export const sdk = createReducer(initialState, (builder) => {});builder.addCase(setInitialGuestToken, (state, action) => {- state.token = {- ...state.token,- rawToken: action.payload,- loading: false,- error: null,- };+ const { mountId, token } = action.payload;+ state.token.guestTokensByMount[mountId] = token;+ state.token.loading = false;+ state.token.error = null;+ });++ builder.addCase(clearGuestToken, (state, action) => {+ delete state.token.guestTokensByMount[action.payload];});builder.addCase(refreshGuestSession.pending, (state) => {@@ -196,12 +199,10 @@ export const sdk = createReducer(initialState, (builder) => {});builder.addCase(refreshGuestSession.fulfilled, (state, action) => {- state.token = {- ...state.token,- rawToken: action.payload,- loading: false,- error: null,- };+ const { mountId } = action.meta.arg;+ state.token.guestTokensByMount[mountId] = action.payload;+ state.token.loading = false;+ state.token.error = null;});builder.addCase(refreshGuestSession.rejected, (state, action) => {diff --git a/frontend/src/embedding-sdk-bundle/store/selectors.ts b/frontend/src/embedding-sdk-bundle/store/selectors.tsindex d13ed914930..9f25ab34c30 100644--- a/frontend/src/embedding-sdk-bundle/store/selectors.ts+++ b/frontend/src/embedding-sdk-bundle/store/selectors.ts@@ -18,6 +18,9 @@ export const getIsLoggedIn = (state: SdkStoreState) =>export const getSessionTokenState = (state: SdkStoreState) => state.sdk.token;+export const getGuestTokenForMount = (state: SdkStoreState, mountId: string) =>+ state.sdk.token.guestTokensByMount[mountId] ?? null;+export const getPlugins = (state: SdkStoreState) => state.sdk.plugins;export const getEventHandlers = (state: SdkStoreState | State) =>diff --git a/frontend/src/embedding-sdk-bundle/store/types.ts b/frontend/src/embedding-sdk-bundle/store/types.tsindex 8177e76a6af..55bd1ec717b 100644--- a/frontend/src/embedding-sdk-bundle/store/types.ts+++ b/frontend/src/embedding-sdk-bundle/store/types.ts@@ -21,7 +21,11 @@ import type { State } from "metabase/redux/store";export type EmbeddingSessionTokenState = {token: MetabaseEmbeddingSessionToken | null;- rawToken: string | null; // Raw JWT string for guest embeds token refresh+ // Raw guest embed JWTs kept so the refresh handler can check expiry and write+ // the refreshed JWT back (see store/guest-embed/auth.ts). Keyed by a stable+ // per-mount id so concurrent guest embeds under one MetabaseProvider don't+ // overwrite each other's token.+ guestTokensByMount: Record<string, string>;loading: boolean;error: SerializedError | null;};diff --git a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts b/frontend/src/embedding-sdk-bundle/test/mocks/state.tsindex 763a9a72c8a..6cc4f2ff9e8 100644--- a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts+++ b/frontend/src/embedding-sdk-bundle/test/mocks/state.ts@@ -7,7 +7,13 @@ import type { LoginStatus } from "embedding-sdk-bundle/types/user";export const createMockTokenState = ({...opts}: Partial<EmbeddingSessionTokenState> = {}): EmbeddingSessionTokenState => {- return { error: null, loading: false, token: null, rawToken: null, ...opts };+ return {+ error: null,+ loading: false,+ token: null,+ guestTokensByMount: {},+ ...opts,+ };};export const createMockLoginStatusState = ({