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
Add token renewal mechanism for guest embeds (#71075)
Mahatthana (Kelvin) Nomsawadie82a4d027c7c
diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.tsindex 3c8dc475906..0769d3d6605 100644--- a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts@@ -26,6 +26,7 @@ export interface BaseEmbedTestPageOptions {// Passed to defineMetabaseConfigmetabaseConfig?: {isGuest?: boolean;+ guestEmbedProviderUri?: string;instanceUrl?: string;apiKey?: string;useExistingUserSession?: boolean;@@ -318,6 +319,7 @@ export const getNewEmbedScriptTag = ({export const getNewEmbedConfigurationScript = ({instanceUrl = "http://localhost:4000",isGuest,+ guestEmbedProviderUri,theme,apiKey,useExistingUserSession,@@ -327,6 +329,7 @@ export const getNewEmbedConfigurationScript = ({const config = {instanceUrl,isGuest,+ guestEmbedProviderUri,apiKey,useExistingUserSession,theme,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.tsnew file mode 100644index 00000000000..6a08f5ed823--- /dev/null+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-token-refresh.cy.spec.ts@@ -0,0 +1,1021 @@+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { createQuestion } from "e2e/support/helpers";+import { JWT_SHARED_SECRET } from "e2e/support/helpers/embedding-sdk-helpers/constants";++const { H } = cy;+const { ORDERS_ID, PRODUCTS, PRODUCTS_ID } = SAMPLE_DATABASE;++const PROVIDER_PATH = "/api/mock-guest-token-provider";+const PROVIDER_INTERCEPT = { method: "POST", pathname: PROVIDER_PATH } as const;++type SignJwtParams = (+ | { dashboardId: number; questionId?: never }+ | { questionId: number; dashboardId?: never }+) & { expirationSeconds: number; params?: Record<string, unknown> };++function signJwt({+ dashboardId,+ questionId,+ expirationSeconds,+ params = {},+}: SignJwtParams): Cypress.Chainable<string> {+ const resource =+ dashboardId !== undefined+ ? { dashboard: dashboardId }+ : { question: questionId };++ return cy+ .task<string>("signJwt", {+ payload: {+ resource,+ params,+ exp: Math.round(Date.now() / 1000) + expirationSeconds,+ },+ secret: JWT_SHARED_SECRET,+ })+ .then((token) => token);+}++const PRICE_DASHBOARD_PARAMETER = {+ name: "Price greater than",+ slug: "price",+ id: "aaaaaaaa",+ type: "number/>=",+ sectionId: "number",+};++const CATEGORY_DASHBOARD_PARAMETER = {+ name: "Category",+ slug: "category",+ id: "bbbbbbbb",+ type: "string/=",+ sectionId: "string",+};++describe("scenarios > embedding > sdk iframe embedding > guest token refresh", () => {+ function createDashboardWithQuestion() {+ H.createQuestionAndDashboard({+ questionDetails: {+ name: "Orders",+ query: { "source-table": ORDERS_ID },+ },+ dashboardDetails: {+ name: "Guest Token Refresh Dashboard",+ enable_embedding: true,+ embedding_type: "guest-embed",+ },+ cardDetails: { row: 0, col: 0, size_x: 11, size_y: 6 },+ }).then(({ body: { dashboard_id } }) => {+ cy.wrap(dashboard_id).as("dashboardId");+ });+ }++ function createDashboardWithPriceFilter() {+ H.createTestQuery({+ database: SAMPLE_DB_ID,+ stages: [+ {+ source: { type: "table", id: PRODUCTS_ID },+ fields: [+ { type: "column", name: "ID", sourceName: "PRODUCTS" },+ { type: "column", name: "TITLE", sourceName: "PRODUCTS" },+ { type: "column", name: "PRICE", sourceName: "PRODUCTS" },+ ],+ limit: 10,+ },+ ],+ }).then((datasetQuery) => {+ H.createCard({+ dataset_query: datasetQuery,+ name: "Products with price filter",+ }).then((question) => {+ cy.request("POST", "/api/dashboard", {+ name: "Guest Token Refresh Dashboard with Price Filter",+ parameters: [PRICE_DASHBOARD_PARAMETER],+ }).then(({ body: dashboard }) => {+ cy.wrap(dashboard.id).as("dashboardId");++ cy.request("PUT", `/api/dashboard/${dashboard.id}`, {+ enable_embedding: true,+ embedding_type: "guest-embed",+ embedding_params: { price: "enabled" },+ dashcards: [+ {+ id: -1,+ card_id: question.id,+ row: 0,+ col: 0,+ size_x: 24,+ size_y: 6,+ parameter_mappings: [+ {+ parameter_id: "aaaaaaaa",+ card_id: question.id,+ target: ["dimension", ["field", PRODUCTS.PRICE, null]],+ },+ ],+ },+ ],+ });+ });+ });+ });+ }++ function createDashboardWithCategoryFilter() {+ H.createTestQuery({+ database: SAMPLE_DB_ID,+ stages: [+ {+ source: { type: "table", id: PRODUCTS_ID },+ fields: [+ { type: "column", name: "ID", sourceName: "PRODUCTS" },+ { type: "column", name: "TITLE", sourceName: "PRODUCTS" },+ { type: "column", name: "CATEGORY", sourceName: "PRODUCTS" },+ ],+ limit: 10,+ },+ ],+ }).then((datasetQuery) => {+ H.createCard({+ dataset_query: datasetQuery,+ name: "Products with category filter",+ }).then((question) => {+ cy.request("POST", "/api/dashboard", {+ name: "Guest Token Refresh Dashboard with Category Filter",+ parameters: [CATEGORY_DASHBOARD_PARAMETER],+ }).then(({ body: dashboard }) => {+ cy.wrap(dashboard.id).as("dashboardId");++ cy.request("PUT", `/api/dashboard/${dashboard.id}`, {+ enable_embedding: true,+ embedding_type: "guest-embed",+ embedding_params: { category: "enabled" },+ dashcards: [+ {+ id: -1,+ card_id: question.id,+ row: 0,+ col: 0,+ size_x: 24,+ size_y: 6,+ parameter_mappings: [+ {+ parameter_id: "bbbbbbbb",+ card_id: question.id,+ target: ["dimension", ["field", PRODUCTS.CATEGORY, null]],+ },+ ],+ },+ ],+ });+ });+ });+ });+ }++ function createStandaloneQuestion() {+ createQuestion({+ name: "Orders",+ enable_embedding: true,+ embedding_type: "guest-embed",+ query: { "source-table": ORDERS_ID },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });+ }++ function createQuestionWithPriceFilter() {+ H.createNativeQuestion({+ name: "Products with price filter",+ native: {+ query: "SELECT ID, TITLE, PRICE FROM PRODUCTS WHERE {{price}} LIMIT 10",+ "template-tags": {+ price: {+ id: "cccccccc",+ name: "price",+ "display-name": "Price greater than",+ type: "dimension",+ dimension: ["field", PRODUCTS.PRICE, null],+ "widget-type": "number/>=",+ required: false,+ },+ },+ },+ enable_embedding: true,+ embedding_params: { price: "enabled" },+ embedding_type: "guest-embed",+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });+ }++ function createQuestionWithCategoryFilter() {+ H.createNativeQuestion({+ name: "Products with category filter",+ native: {+ query:+ "SELECT ID, TITLE, CATEGORY FROM PRODUCTS WHERE {{category}} LIMIT 10",+ "template-tags": {+ category: {+ id: "dddddddd",+ name: "category",+ "display-name": "Category",+ type: "dimension",+ dimension: ["field", PRODUCTS.CATEGORY, null],+ "widget-type": "category",+ required: false,+ },+ },+ },+ enable_embedding: true,+ embedding_params: { category: "enabled" },+ embedding_type: "guest-embed",+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });+ }++ describe("dashboard refresh-only", () => {+ describe("happy path", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createDashboardWithQuestion,+ });+ });++ it("calls guestEmbedProviderUri with { entityType, entityId } and loads dashboard after token refresh", () => {+ cy.get<number>("@dashboardId").then((dashboardId) => {+ signJwt({ dashboardId, expirationSeconds: -60 }).then(+ (expiredToken) => {+ signJwt({ dashboardId, 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-dashboard",+ attributes: {+ token: expiredToken,+ "custom-context": "test-custom-context",+ },+ },+ ],+ });++ cy.wait("@guestTokenProvider").then((interception) => {+ expect(interception.request.body).to.deep.include({+ entityType: "dashboard",+ entityId: dashboardId,+ customContext: "test-custom-context",+ });+ });++ H.getSimpleEmbedIframeContent().should("contain", "Orders");+ },+ );+ },+ );+ });+ });+ });++ describe("provider error shows error state", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createDashboardWithQuestion,+ });+ });++ it("shows an error when the provider returns an HTTP error", () => {+ cy.get<number>("@dashboardId").then((dashboardId) => {+ signJwt({ dashboardId, expirationSeconds: -60 }).then(+ (expiredToken) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({ statusCode: 500 });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: { token: expiredToken },+ },+ ],+ });++ cy.wait("@guestTokenProvider");+ H.getSimpleEmbedIframeContent()+ .findByText(+ "Failed to fetch JWT token from /api/mock-guest-token-provider, status: 500.",+ )+ .should("be.visible");+ },+ );+ });+ });++ it("shows an error when the provider returns a wrong response shape", () => {+ cy.get<number>("@dashboardId").then((dashboardId) => {+ signJwt({ dashboardId, expirationSeconds: -60 }).then(+ (expiredToken) => {+ signJwt({ dashboardId, expirationSeconds: 600 }).then(+ (freshToken) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({+ statusCode: 200,+ body: { token: freshToken },+ });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: { token: expiredToken },+ },+ ],+ });++ cy.wait("@guestTokenProvider");+ H.getSimpleEmbedIframeContent()+ .findByText(+ /Your JWT server endpoint must return an object with the shape { jwt: string }, but instead received {"token":/,+ )+ .should("be.visible");+ },+ );+ },+ );+ });+ });+ });++ describe("number filter interaction after token refresh", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createDashboardWithPriceFilter,+ });+ });++ it("applying a number filter after token refresh returns filtered results", () => {+ cy.get<number>("@dashboardId").then((dashboardId) => {+ signJwt({ dashboardId, expirationSeconds: 5 }).then(+ (shortLivedToken) => {+ signJwt({ dashboardId, 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-dashboard",+ attributes: { token: shortLivedToken },+ },+ ],+ });++ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByLabelText("Price greater than").should(+ "be.visible",+ );+ });++ 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(() => {+ cy.findByLabelText("Price greater than").click();+ H.popover().within(() => {+ cy.findByPlaceholderText("Enter a number").type(+ "50{enter}",+ );+ });+ cy.log(+ "ensure the token is refreshed after applying a filter value",+ );+ cy.wait("@guestTokenProvider");++ H.assertTableData({+ columns: ["ID", "Title", "Price"],+ firstRows: [["2", "Small Marble Shoes", "70.08"]],+ });+ });+ },+ );+ },+ );+ });+ });+ });++ describe("category filter interaction after token refresh", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createDashboardWithCategoryFilter,+ });+ });++ it("applying a category filter after token refresh returns filtered results", () => {+ cy.get<number>("@dashboardId").then((dashboardId) => {+ signJwt({ dashboardId, expirationSeconds: 5 }).then(+ (shortLivedToken) => {+ signJwt({ dashboardId, 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-dashboard",+ attributes: { token: shortLivedToken },+ },+ ],+ });++ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByLabelText("Category").should("be.visible");+ });++ 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(() => {+ cy.findByLabelText("Category").click();++ cy.log(+ "ensure the token is refreshed after the filter values endpoint is called",+ );+ cy.wait("@guestTokenProvider");++ H.popover().within(() => {+ cy.findByRole("checkbox", {+ name: "Doohickey",+ }).click();+ cy.button("Add filter").click();+ });++ H.assertTableData({+ columns: ["ID", "Title", "Category"],+ firstRows: [["2", "Small Marble Shoes", "Doohickey"]],+ });+ });+ },+ );+ },+ );+ });+ });+ });+ });++ describe("dashboard initial-token", () => {+ describe("happy path", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createDashboardWithQuestion,+ });+ });++ it("calls guestEmbedProviderUri with { entityType, entityId } and loads dashboard (initial token fetch)", () => {+ cy.get<number>("@dashboardId").then((dashboardId) => {+ signJwt({ dashboardId, 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-dashboard",+ attributes: {+ "dashboard-id": dashboardId,+ "custom-context": "test-custom-context",+ },+ },+ ],+ });++ cy.wait("@guestTokenProvider").then((interception) => {+ expect(interception.request.url).to.include("response=json");+ expect(interception.request.body).to.deep.include({+ entityType: "dashboard",+ entityId: dashboardId,+ customContext: "test-custom-context",+ });+ });++ H.getSimpleEmbedIframeContent().should("contain", "Orders");+ },+ );+ });+ });+ });++ describe("provider error shows error state", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createDashboardWithQuestion,+ });+ });++ it("shows an error when the provider returns an HTTP error", () => {+ cy.get<number>("@dashboardId").then((dashboardId) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({ statusCode: 500 });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: { "dashboard-id": dashboardId },+ },+ ],+ });++ cy.wait("@guestTokenProvider");+ H.getSimpleEmbedIframeContent()+ .findByText(+ "Failed to fetch JWT token from /api/mock-guest-token-provider, status: 500.",+ )+ .should("be.visible");+ });+ });++ it("shows an error when the provider returns a wrong response shape", () => {+ cy.get<number>("@dashboardId").then((dashboardId) => {+ signJwt({ dashboardId, expirationSeconds: 600 }).then(+ (freshToken) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({+ statusCode: 200,+ body: { token: freshToken },+ });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: { "dashboard-id": dashboardId },+ },+ ],+ });++ cy.wait("@guestTokenProvider");+ H.getSimpleEmbedIframeContent()+ .findByText(+ /Your JWT server endpoint must return an object with the shape { jwt: string }, but instead received {"token":/,+ )+ .should("be.visible");+ },+ );+ });+ });+ });+ });++ describe("question refresh-only", () => {+ describe("happy path", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createStandaloneQuestion,+ });+ });++ it("calls guestEmbedProviderUri with { entityType: question, entityId } and loads question after token refresh", () => {+ cy.get<number>("@questionId").then((questionId) => {+ signJwt({ questionId, expirationSeconds: -60 }).then(+ (expiredToken) => {+ signJwt({ questionId, 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: expiredToken,+ "custom-context": "test-custom-context",+ },+ },+ ],+ });++ cy.wait("@guestTokenProvider").then((interception) => {+ expect(interception.request.body).to.deep.include({+ entityType: "question",+ entityId: questionId,+ customContext: "test-custom-context",+ });+ });++ H.getSimpleEmbedIframeContent()+ .findByTestId("visualization-root")+ .should("exist");+ },+ );+ },+ );+ });+ });+ });++ describe("provider error shows error state", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createStandaloneQuestion,+ });+ });++ it("shows an error when the provider returns an HTTP error", () => {+ cy.get<number>("@questionId").then((questionId) => {+ signJwt({ questionId, expirationSeconds: -60 }).then(+ (expiredToken) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({ statusCode: 500 });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-question",+ attributes: { token: expiredToken },+ },+ ],+ });++ cy.wait("@guestTokenProvider");+ H.getSimpleEmbedIframeContent()+ .findByText(+ "Failed to fetch JWT token from /api/mock-guest-token-provider, status: 500.",+ )+ .should("be.visible");+ },+ );+ });+ });++ it("shows an error when the provider returns a wrong response shape", () => {+ cy.get<number>("@questionId").then((questionId) => {+ signJwt({ questionId, expirationSeconds: -60 }).then(+ (expiredToken) => {+ signJwt({ questionId, expirationSeconds: 600 }).then(+ (freshToken) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({+ statusCode: 200,+ body: { token: freshToken },+ });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-question",+ attributes: { token: expiredToken },+ },+ ],+ });++ cy.wait("@guestTokenProvider");+ H.getSimpleEmbedIframeContent()+ .findByText(+ /Your JWT server endpoint must return an object with the shape { jwt: string }, but instead received {"token":/,+ )+ .should("be.visible");+ },+ );+ },+ );+ });+ });+ });++ describe("number filter interaction after token refresh", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createQuestionWithPriceFilter,+ });+ });++ it("applying a number filter after token refresh returns filtered results", () => {+ cy.get<number>("@questionId").then((questionId) => {+ signJwt({ questionId, expirationSeconds: 5 }).then(+ (shortLivedToken) => {+ signJwt({ questionId, 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: shortLivedToken },+ },+ ],+ });++ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByText("Products with price filter").should(+ "be.visible",+ );+ });++ 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(() => {+ cy.findByLabelText("Price greater than").click();+ H.popover().within(() => {+ cy.findByPlaceholderText("Enter a number").type(+ "50{enter}",+ );+ });+ cy.log(+ "ensure the token is refreshed after applying a filter value",+ );+ cy.wait("@guestTokenProvider");++ H.assertTableData({+ columns: ["ID", "TITLE", "PRICE"],+ firstRows: [["2", "Small Marble Shoes", "70.08"]],+ });+ });+ },+ );+ },+ );+ });+ });+ });++ describe("category filter interaction after token refresh", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createQuestionWithCategoryFilter,+ });+ });++ it("applying a category filter after token refresh returns filtered results", () => {+ cy.get<number>("@questionId").then((questionId) => {+ signJwt({ questionId, expirationSeconds: 5 }).then(+ (shortLivedToken) => {+ signJwt({ questionId, 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: shortLivedToken },+ },+ ],+ });++ H.getSimpleEmbedIframeContent().within(() => {+ cy.findByText("Products with category filter").should(+ "be.visible",+ );+ });++ 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(() => {+ cy.findByLabelText("Category").click();++ cy.log(+ "ensure the token is refreshed after the filter values endpoint is called",+ );+ cy.wait("@guestTokenProvider");++ H.popover().within(() => {+ cy.findByRole("checkbox", {+ name: "Doohickey",+ }).click();+ cy.button("Add filter").click();+ });++ H.assertTableData({+ columns: ["ID", "TITLE", "CATEGORY"],+ firstRows: [["2", "Small Marble Shoes", "Doohickey"]],+ });+ });+ },+ );+ },+ );+ });+ });+ });+ });++ describe("question initial-token", () => {+ describe("happy path", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createStandaloneQuestion,+ });+ });++ it("calls guestEmbedProviderUri with { entityType: question, entityId } and loads question (initial token fetch)", () => {+ cy.get<number>("@questionId").then((questionId) => {+ signJwt({ questionId, 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: {+ "question-id": questionId,+ "custom-context": "test-custom-context",+ },+ },+ ],+ });++ cy.wait("@guestTokenProvider").then((interception) => {+ expect(interception.request.url).to.include("response=json");+ expect(interception.request.body).to.deep.include({+ entityType: "question",+ entityId: questionId,+ customContext: "test-custom-context",+ });+ });++ H.getSimpleEmbedIframeContent()+ .findByTestId("visualization-root")+ .should("exist");+ });+ });+ });+ });++ describe("provider error shows error state", () => {+ beforeEach(() => {+ H.prepareGuestEmbedSdkIframeEmbedTest({+ onPrepare: createStandaloneQuestion,+ });+ });++ it("shows an error when the provider returns an HTTP error", () => {+ cy.get<number>("@questionId").then((questionId) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({ statusCode: 500 });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-question",+ attributes: { "question-id": questionId },+ },+ ],+ });++ cy.wait("@guestTokenProvider");+ H.getSimpleEmbedIframeContent()+ .findByText(+ "Failed to fetch JWT token from /api/mock-guest-token-provider, status: 500.",+ )+ .should("be.visible");+ });+ });++ it("shows an error when the provider returns a wrong response shape", () => {+ cy.get<number>("@questionId").then((questionId) => {+ signJwt({ questionId, expirationSeconds: 600 }).then((freshToken) => {+ cy.intercept(PROVIDER_INTERCEPT, (req) => {+ req.reply({+ statusCode: 200,+ body: { token: freshToken },+ });+ }).as("guestTokenProvider");++ H.loadSdkIframeEmbedTestPage({+ metabaseConfig: {+ isGuest: true,+ guestEmbedProviderUri: PROVIDER_PATH,+ },+ elements: [+ {+ component: "metabase-question",+ attributes: { "question-id": questionId },+ },+ ],+ });++ cy.wait("@guestTokenProvider");+ H.getSimpleEmbedIframeContent()+ .findByText(+ /Your JWT server endpoint must return an object with the shape { jwt: string }, but instead received {"token":/,+ )+ .should("be.visible");+ });+ });+ });+ });+ });+});diff --git a/enterprise/frontend/src/embedding/auth-common/jwt.ts b/enterprise/frontend/src/embedding/auth-common/jwt.tsindex 8f17f30bf8e..7a8e7269aee 100644--- a/enterprise/frontend/src/embedding/auth-common/jwt.ts+++ b/enterprise/frontend/src/embedding/auth-common/jwt.ts@@ -73,7 +73,6 @@ const runFetchRequestToken = async (});}throw MetabaseError.DEFAULT_ENDPOINT_ERROR({- expected: "{ jwt: string }",actual: actualResponse,});}diff --git a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError.stories.tsx b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError.stories.tsxnew file mode 100644index 00000000000..69a29408d4e--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError.stories.tsx@@ -0,0 +1,83 @@+import type { StoryFn } from "@storybook/react";++import { CommonSdkStoryWrapper } from "embedding-sdk-bundle/test/CommonSdkStoryWrapper";+import type { SdkErrorComponentProps } from "embedding-sdk-bundle/types";++import {+ DashboardNotFoundError,+ QuestionNotFoundError,+ SdkError,+} from "./SdkError";++export default {+ title: "EmbeddingSDK/SdkError",+ component: SdkError,+ decorators: [CommonSdkStoryWrapper],+};++const Template: StoryFn<SdkErrorComponentProps> = (args) => (+ <SdkError {...args} />+);++export const Default = {+ render: Template,+ args: {+ message: "Something went wrong.",+ type: "relative",+ },+};++export const WithCloseButton = {+ render: Template,+ args: {+ message: "Something went wrong.",+ type: "relative",+ withCloseButton: true,+ },+};++export const WithDocLink = {+ render: Template,+ args: {+ message: "Something went wrong.",+ type: "relative",+ error: Object.assign(new Error("Existing user session failed."), {+ code: "EXISTING_USER_SESSION_FAILED",+ }),+ },+};++export const Fixed = {+ render: ((args) => {+ return (+ <>+ If you see nothing, refresh the page.+ <SdkError {...args} />+ </>+ );+ }) as StoryFn<SdkErrorComponentProps>,+ args: {+ message: "Something went wrong.",+ type: "fixed",+ withCloseButton: true,+ },+};++const LONG_MESSAGE =+ 'Your JWT server endpoint must return an object with the shape { jwt: string }, but instead received {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXNvdXJjZSI6eyJkYXNoYm9hcmQiOjF9LCJwYXJhbXMiOnt9LCJleHAiOjE3NzQ2MDkyMDksImlhdCI6MTc3NDYwOTE5OX0.-S3eLFi_XZeb9ltaorP7_k52fXW_jhtb1oG-BuOVSWw"}';++export const LongMessage = {+ render: Template,+ args: {+ message: LONG_MESSAGE,+ type: "relative",+ },+};++export const QuestionNotFound = {+ render: () => <QuestionNotFoundError id={1} />,+};++export const DashboardNotFound = {+ render: () => <DashboardNotFoundError id={42} />,+};diff --git a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError.tsx b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError.tsxindex b485e291cff..390096c6eda 100644--- a/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/PublicComponentWrapper/SdkError.tsx@@ -102,9 +102,19 @@ const FORCE_DARK_TEXT_COLOR = {} as CSSProperties;const DefaultErrorMessage = ({ message, onClose }: SdkErrorComponentProps) => (- <Box p="sm" style={FORCE_DARK_TEXT_COLOR}>+ <Box p="sm" style={FORCE_DARK_TEXT_COLOR} maw={600}><Alert variant="error" icon="warning" onClose={onClose}>- {message}+ <Box+ style={{+ WebkitLineClamp: 2,+ WebkitBoxOrient: "vertical",+ display: "-webkit-box",+ overflow: "hidden",+ wordBreak: "break-all",+ }}+ >+ {message}+ </Box></Alert></Box>);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 55c2bc66f26..ef247ab47c6 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@@ -4,6 +4,7 @@ import {useContext,useEffect,useMemo,+ useState,} from "react";import { t } from "ttag";@@ -14,11 +15,13 @@ import { QuestionAlertModalProvider } from "embedding-sdk-bundle/components/privimport { useExtractResourceIdFromJwtToken } from "embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token";import { useLoadQuestion } from "embedding-sdk-bundle/hooks/private/use-load-question";import { useSetupContentTranslations } from "embedding-sdk-bundle/hooks/private/use-setup-content-translations";-import { useSdkSelector } from "embedding-sdk-bundle/store";+import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";+import { setInitialGuestToken } from "embedding-sdk-bundle/store/guest-embed";import {getError,getIsGuestEmbed,getPlugins,+ getSessionTokenState,} from "embedding-sdk-bundle/store/selectors";import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";import { EmbeddingEntityContextProvider } from "metabase/embedding/context";@@ -75,7 +78,22 @@ export const SdkQuestionProvider = ({onVisualizationChange,}: SdkQuestionProviderProps) => {const isGuestEmbed = useSdkSelector(getIsGuestEmbed);+ const dispatch = useSdkDispatch();const navigation = useSdkInternalNavigationOptional();+ const [isFirstRender, setIsFirstRender] = useState(true);+ const { rawToken: tokenFromStore, error: tokenFetchError } =+ useSdkSelector(getSessionTokenState);++ // Store token so the refresh handler can check expiry. No need to await — not used here.+ useEffect(() => {+ if (rawToken && isGuestEmbed) {+ dispatch(setInitialGuestToken(rawToken));+ }+ }, [rawToken, isGuestEmbed, dispatch]);++ useEffect(() => {+ setIsFirstRender(false);+ }, []);const {resourceId: questionId,@@ -84,7 +102,9 @@ export const SdkQuestionProvider = ({} = useExtractResourceIdFromJwtToken({isGuestEmbed,resourceId: rawQuestionId,- token: rawToken ?? undefined,+ // Skip stale Redux token on first render (e.g. wizard re-issuing a token when toggling parameters); rawToken prop takes precedence.+ // From the next render onward, tokenFromStore is used and the value is from a refreshed token.+ token: (!isFirstRender ? tokenFromStore : null) ?? rawToken ?? undefined,});useSetupContentTranslations({ token });@@ -270,6 +290,10 @@ export const SdkQuestionProvider = ({return <SdkError message={tokenError} />;}+ if (tokenFetchError) {+ return <SdkError message={tokenFetchError.message} />;+ }+if (error) {return <SdkError message={error.message} />;}diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsxindex acff5fc0817..0d87da4c7a8 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/SdkDashboard.tsx@@ -31,7 +31,11 @@ import {} from "embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params";import { useSetupContentTranslations } from "embedding-sdk-bundle/hooks/private/use-setup-content-translations";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";-import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";+import { setInitialGuestToken } from "embedding-sdk-bundle/store/guest-embed";+import {+ getIsGuestEmbed,+ getSessionTokenState,+} from "embedding-sdk-bundle/store/selectors";import type { MetabaseQuestion } from "embedding-sdk-bundle/types";import type {DashboardEventHandlersProps,@@ -194,6 +198,21 @@ const SdkDashboardInner = ({onVisualizationChange,}: SdkDashboardInnerProps) => {const isGuestEmbed = useSdkSelector(getIsGuestEmbed);+ const dispatch = useSdkDispatch();+ const [isFirstRender, setIsFirstRender] = useState(true);+ const { rawToken: tokenFromStore, error: tokenFetchError } =+ useSdkSelector(getSessionTokenState);++ // Store token so the refresh handler can check expiry. No need to await — not used here.+ useEffect(() => {+ if (rawToken && isGuestEmbed) {+ dispatch(setInitialGuestToken(rawToken));+ }+ }, [rawToken, isGuestEmbed, dispatch]);++ useEffect(() => {+ setIsFirstRender(false);+ }, []);const {resourceId: dashboardId,@@ -202,7 +221,9 @@ const SdkDashboardInner = ({} = useExtractResourceIdFromJwtToken({isGuestEmbed,resourceId: rawDashboardId,- token: rawToken ?? undefined,+ // Skip stale Redux token on first render (e.g. wizard re-issuing a token when toggling parameters); rawToken prop takes precedence.+ // From the next render onward, tokenFromStore is used and the value is from a refreshed token.+ token: (!isFirstRender ? tokenFromStore : null) ?? rawToken ?? undefined,});useSetupContentTranslations({ token });@@ -275,7 +296,6 @@ const SdkDashboardInner = ({]);const errorPage = useSdkSelector(getErrorPage);- const dispatch = useSdkDispatch();useEffect(() => {if (dashboardId) {dispatch(resetErrorPage());@@ -357,6 +377,10 @@ const SdkDashboardInner = ({);}+ if (tokenFetchError) {+ return <SdkError message={tokenFetchError.message} />;+ }+if (isStaticEmbeddingEntityLoadingError(errorPage, { isGuestEmbed })) {return (<SdkDashboardStyledWrapper className={className} style={style}>diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/use-common-dashboard-params.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/use-common-dashboard-params.tsxindex c9d548aac6f..34ea762c8a9 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/use-common-dashboard-params.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/use-common-dashboard-params.tsx@@ -4,9 +4,9 @@ import { usePrevious, useUnmount } from "react-use";import { useSdkDispatch, useSdkStore } from "embedding-sdk-bundle/store";import { getNewCardUrl } from "metabase/dashboard/actions/getNewCardUrl";import type { NavigateToNewCardFromDashboardOpts } from "metabase/dashboard/components/DashCard/types";+import { isJWT } from "metabase/lib/jwt";import { parseNumber } from "metabase/lib/number";import * as Urls from "metabase/lib/urls";-import { isJWT } from "metabase/lib/utils";import {NAVIGATE_TO_NEW_CARD,reset as dashboardReset,diff --git a/frontend/src/embedding-sdk-bundle/errors/jwt.ts b/frontend/src/embedding-sdk-bundle/errors/jwt.tsindex 91d0256b88a..41fc9fd3cc9 100644--- a/frontend/src/embedding-sdk-bundle/errors/jwt.ts+++ b/frontend/src/embedding-sdk-bundle/errors/jwt.ts@@ -44,10 +44,7 @@ export function CUSTOM_FETCH_REQUEST_TOKEN_ERROR(params: {);}-export function DEFAULT_ENDPOINT_ERROR(params: {- expected?: string;- actual?: string;-}) {+export function DEFAULT_ENDPOINT_ERROR(params: { actual?: string }) {return new MetabaseError("DEFAULT_ENDPOINT_ERROR",`Your JWT server endpoint must return an object with the shape { jwt: string }${params.actual ? `, but instead received ${params.actual}` : ``}`,diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token.tsindex bd51729b5e5..6c0dd3e4f4d 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token.ts@@ -2,7 +2,7 @@ import { useMemo } from "react";import { t } from "ttag";import type { SdkEntityToken } from "embedding-sdk-bundle/types";-import { extractResourceIdFromJwtToken, isJWT } from "metabase/lib/utils";+import { extractResourceIdFromJwtToken, isJWT } from "metabase/lib/jwt";export const useExtractResourceIdFromJwtToken = <TEntityId>({isGuestEmbed,@@ -13,14 +13,11 @@ export const useExtractResourceIdFromJwtToken = <TEntityId>({resourceId: TEntityId | undefined;token: SdkEntityToken | undefined;}): {- resourceId: TEntityId | null;+ resourceId: TEntityId | number | null;token: SdkEntityToken | null;tokenError?: string;} => {- return useMemo<{- resourceId: TEntityId | null;- token: SdkEntityToken | null;- }>(() => {+ return useMemo(() => {if (isJWT(resourceId)) {return {resourceId: null,diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.tsindex 35de7d0bbd9..db481937a73 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts@@ -115,7 +115,7 @@ export const useInitDataInternal = ({}if (isGuestEmbed) {- dispatch(initGuestEmbed());+ dispatch(initGuestEmbed(authConfig));} else {dispatch(initAuth({ ...authConfig, isLocalHost }));}diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.tsindex 206c71ab955..f646354c456 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts@@ -82,6 +82,18 @@ export function useLoadQuestion({const isGuestEmbed = useSdkSelector(getIsGuestEmbed);+ /**+ * Token change isn't an indicator to re-run the query. When users are refreshing+ * the guest embeds token, the token will change, but not questionId. So we can+ * rely on questionId that will change the loadAndQueryQuestion value and trigger+ * the query again.+ *+ * As a reference, dashboards don't use this approach. It detects if the+ * dashboardId has changed before triggering the query. So, the idea is quite similar.+ */+ const tokenRef = useRef(token);+ tokenRef.current = token;+const deferredRef = useRef<Deferred>();function deferred() {@@ -115,7 +127,7 @@ export function useLoadQuestion({options,deserializedCard,questionId,- token,+ token: tokenRef.current,initialSqlParameters,targetDashboardId,}),@@ -126,7 +138,7 @@ export function useLoadQuestion({const results = await runQuestionQuerySdk({question: questionState.question,isGuestEmbed,- token,+ token: tokenRef.current,originalQuestion: questionState.originalQuestion,parameterValues: questionState.parameterValues,cancelDeferred: deferred(),@@ -169,7 +181,6 @@ export function useLoadQuestion({isGuestEmbed,sqlParameterKey,questionId,- token,targetDashboardId,]);diff --git a/frontend/src/embedding-sdk-bundle/store/guest-embed/auth.ts b/frontend/src/embedding-sdk-bundle/store/guest-embed/auth.tsnew file mode 100644index 00000000000..7191529c33c--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/store/guest-embed/auth.ts@@ -0,0 +1,113 @@+// This file reflects the structure in enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts+import type { AsyncThunkAction, SerializedError } from "@reduxjs/toolkit";+import { createAction } from "@reduxjs/toolkit";++import type { SdkStoreState } from "embedding-sdk-bundle/store/types";+import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";+import { requestSessionTokenFromEmbedJs } from "metabase/embedding/embedding-iframe-sdk/utils/request-session-token";+import { isEmbeddingEajs } from "metabase/embedding-sdk/config";+import { decodeJwt } from "metabase/lib/jwt";+import { createAsyncThunk } from "metabase/lib/redux";++import { getSessionTokenState } from "../selectors";++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",+);++export const setGuestTokenFetchError = createAction<SerializedError | null>(+ "sdk/guest-embed/SET_TOKEN_FETCH_ERROR",+);++/**+ * Fetches a new guest embed token from the configured refresh endpoint.+ * For iframe embeds, delegates to embed.js via postMessage (CSP-safe).+ * Returns the raw JWT string.+ */+export const refreshGuestSession = createAsyncThunk(+ "sdk/guest-embed/REFRESH_SESSION",+ async ({+ authConfig,+ expiredToken,+ }: {+ authConfig: MetabaseAuthConfig;+ expiredToken: string;+ }): Promise<string> => {+ if (authConfig.isGuest && !authConfig.guestEmbedProviderUri) {+ throw new Error(+ "guestEmbedProviderUri is required to refresh the guest embed token",+ );+ }++ if (isEmbeddingEajs()) {+ return await requestSessionTokenFromEmbedJs({ expiredToken });+ }++ throw new Error(+ "Guest embed token refresh is only supported in iframe embeds",+ );+ },+);++// Unlike the SSO counterpart, returns the raw JWT string, not the decoded session object.+export const getOrRefreshGuestSession = createAsyncThunk(+ "sdk/guest-embed/GET_OR_REFRESH_TOKEN",+ async (authConfig: MetabaseAuthConfig, { dispatch, getState }) => {+ const state = getState() as SdkStoreState;+ const tokenState = getSessionTokenState(state);+ const currentToken = tokenState.rawToken;++ // No token in Redux yet, so we can't check expiration.+ if (!currentToken) {+ return null;+ }++ const session = decodeJwt(currentToken);++ /**+ * Cypress can't mock time inside an iframe, so we support a window flag+ * that forces a token refresh for testing purposes.+ *+ * We also, couldn't check window.CYPRESS because that only exists in the parent window.+ */+ let forceRefreshForCypress;+ if (typeof window !== "undefined") {+ forceRefreshForCypress =+ window.FORCE_REFRESH_GUEST_EMBED_TOKEN_IN_CYPRESS === true;+ }+ if (forceRefreshForCypress) {+ window.FORCE_REFRESH_GUEST_EMBED_TOKEN_IN_CYPRESS = false;+ }++ const shouldRefreshToken =+ forceRefreshForCypress ||+ !session ||+ (typeof session?.exp === "number" && session.exp * 1000 < Date.now());++ if (!shouldRefreshToken) {+ return currentToken;+ }++ if (refreshGuestSessionPromise) {+ return refreshGuestSessionPromise.unwrap();+ }++ refreshGuestSessionPromise = dispatch(+ refreshGuestSession({+ authConfig,+ expiredToken: currentToken!,+ }),+ );++ refreshGuestSessionPromise.finally(() => {+ refreshGuestSessionPromise = null;+ });++ return refreshGuestSessionPromise.unwrap();+ },+);diff --git a/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts b/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.tsindex ad318e158c8..3e284d55a9c 100644--- a/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts+++ b/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts@@ -1,11 +1,63 @@+import { merge } from "icepick";++import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";import { overrideRequestsForGuestEmbeds } from "metabase/embedding/lib/override-requests-for-embeds";+import { isJWT } from "metabase/lib/jwt";import { createAsyncThunk } from "metabase/lib/redux";+import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";+import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";import { refreshSiteSettings } from "metabase/redux/settings";-export const initGuestEmbed = createAsyncThunk<void, undefined>(+import { getOrRefreshGuestSession } from "./auth";++export const initGuestEmbed = createAsyncThunk<void, MetabaseAuthConfig>("sdk/token/INIT_GUEST_EMBED",- async (_: any, { dispatch }) => {+ async (authConfig: MetabaseAuthConfig, { dispatch }) => {overrideRequestsForGuestEmbeds();++ if (authConfig.isGuest && authConfig.guestEmbedProviderUri) {+ // Replaces the request token with the newly refreshed guest embed token.+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshGuestSessionHandler =+ async (config: OnBeforeRequestHandlerConfig) => {+ const newToken = await dispatch(+ getOrRefreshGuestSession(authConfig),+ ).unwrap();++ // The URL is templated (e.g. /api/embed/card/:entityIdentifier/params/:paramId/values or /api/embed/card/:token/query)+ if (newToken && "entityIdentifier" in config.data) {+ return merge(config, {+ data: {+ entityIdentifier: newToken,+ },+ });+ }++ if (newToken && "token" in config.data) {+ return merge(config, {+ data: {+ token: newToken,+ },+ });+ }++ // The token value is inlined in the URL path (e.g. /api/embed/card/{jwt}/query).+ // Replace it with :entityIdentifier so the parameter substitution in api.js+ // can bake the refreshed token into the URL.+ if (newToken) {+ const jwtInUrl = config.url+ .split("/")+ .find((segment) => isJWT(segment));++ if (jwtInUrl) {+ return merge(config, {+ url: config.url.replace(jwtInUrl, ":entityIdentifier"),+ data: { entityIdentifier: newToken },+ });+ }+ }+ };+ }+await dispatch(refreshSiteSettings());},);diff --git a/frontend/src/embedding-sdk-bundle/store/guest-embed/index.ts b/frontend/src/embedding-sdk-bundle/store/guest-embed/index.tsindex ee73c896209..cb24e25fcec 100644--- a/frontend/src/embedding-sdk-bundle/store/guest-embed/index.ts+++ b/frontend/src/embedding-sdk-bundle/store/guest-embed/index.ts@@ -1 +1,2 @@export * from "./guest-embed";+export * from "./auth";diff --git a/frontend/src/embedding-sdk-bundle/store/reducer.ts b/frontend/src/embedding-sdk-bundle/store/reducer.tsindex 248b4a53796..6d8e08c651c 100644--- a/frontend/src/embedding-sdk-bundle/store/reducer.ts+++ b/frontend/src/embedding-sdk-bundle/store/reducer.ts@@ -11,7 +11,12 @@ import type { SdkUsageProblem } from "embedding-sdk-bundle/types/usage-problem";import type { MetabaseFetchRequestTokenFn } from "metabase/embedding-sdk/types/refresh-token";import { initAuth, refreshTokenAsync } from "./auth";-import { initGuestEmbed } from "./guest-embed";+import {+ initGuestEmbed,+ refreshGuestSession,+ setGuestTokenFetchError,+ setInitialGuestToken,+} from "./guest-embed";const SET_IS_GUEST_EMBED = "sdk/SET_IS_GUEST_EMBED";const SET_METABASE_INSTANCE_VERSION = "sdk/SET_METABASE_INSTANCE_VERSION";const SET_METABASE_CLIENT_URL = "sdk/SET_METABASE_CLIENT_URL";@@ -54,6 +59,7 @@ const initialState: SdkState = {metabaseInstanceVersion: null,token: {token: null,+ rawToken: null,loading: false,error: null,},@@ -74,6 +80,7 @@ export const sdk = createReducer(initialState, (builder) => {builder.addCase(refreshTokenAsync.fulfilled, (state, action) => {state.token = {token: action.payload,+ rawToken: null,loading: false,error: null,};@@ -148,4 +155,43 @@ export const sdk = createReducer(initialState, (builder) => {builder.addCase(setUsageProblem, (state, action) => {state.usageProblem = action.payload;});++ // Guest embed token management+ builder.addCase(setGuestTokenFetchError, (state, action) => {+ state.token = { ...state.token, loading: false, error: action.payload };+ });++ builder.addCase(setInitialGuestToken, (state, action) => {+ state.token = {+ ...state.token,+ rawToken: action.payload,+ loading: false,+ error: null,+ };+ });++ builder.addCase(refreshGuestSession.pending, (state) => {+ state.token = {+ ...state.token,+ loading: true,+ };+ });++ builder.addCase(refreshGuestSession.fulfilled, (state, action) => {+ state.token = {+ ...state.token,+ rawToken: action.payload,+ loading: false,+ error: null,+ };+ });++ builder.addCase(refreshGuestSession.rejected, (state, action) => {+ const error = action.error;+ state.token = {+ ...state.token,+ loading: false,+ error,+ };+ });});diff --git a/frontend/src/embedding-sdk-bundle/store/types.ts b/frontend/src/embedding-sdk-bundle/store/types.tsindex 92fcd44e869..faac2c9da10 100644--- a/frontend/src/embedding-sdk-bundle/store/types.ts+++ b/frontend/src/embedding-sdk-bundle/store/types.ts@@ -20,6 +20,7 @@ import type { State } from "metabase-types/store";export type EmbeddingSessionTokenState = {token: MetabaseEmbeddingSessionToken | null;+ rawToken: string | null; // Raw JWT string for guest embeds token refreshloading: 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 56e23a4e732..52cb334e65f 100644--- a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts+++ b/frontend/src/embedding-sdk-bundle/test/mocks/state.ts@@ -7,7 +7,7 @@ import type { LoginStatus } from "embedding-sdk-bundle/types/user";export const createMockTokenState = ({...opts}: Partial<EmbeddingSessionTokenState> = {}): EmbeddingSessionTokenState => {- return { error: null, loading: false, token: null, ...opts };+ return { error: null, loading: false, token: null, rawToken: null, ...opts };};export const createMockLoginStatusState = ({diff --git a/frontend/src/embedding-sdk-bundle/types/auth-config.ts b/frontend/src/embedding-sdk-bundle/types/auth-config.tsindex 23d85ad54a3..4ad15ca745a 100644--- a/frontend/src/embedding-sdk-bundle/types/auth-config.ts+++ b/frontend/src/embedding-sdk-bundle/types/auth-config.ts@@ -66,6 +66,15 @@ export type MetabaseIsGuestAuthConfig = BaseMetabaseAuthConfig & {* Defines if SDK should work in a Guest Embed mode*/isGuest: true;++ /**+ * URL endpoint for fetching and refreshing guest embed JWT tokens (iframe only, not applicable for SDK's guest mode).+ * Supports both token refresh on expiry and initial token fetch when no static token is provided.+ * In both cases, this works with guest embed components (metabase-dashboard and metabase-question).+ * The endpoint should return { jwt: string } with the new token.+ */+ guestEmbedProviderUri?: string;+apiKey?: never;preferredAuthMethod?: never;fetchRequestToken?: never;diff --git a/frontend/src/embedding-sdk-shared/types/globals.d.ts b/frontend/src/embedding-sdk-shared/types/globals.d.tsindex c184b270db1..3db73699efb 100644--- a/frontend/src/embedding-sdk-shared/types/globals.d.ts+++ b/frontend/src/embedding-sdk-shared/types/globals.d.ts@@ -12,4 +12,5 @@ interface Window {METABASE_EMBEDDING_SDK_BUNDLE_BUILD_INFO?: import("metabase/embedding-sdk/types/build-info").BuildInfo;METABASE_EMBEDDING_SDK_IS_HOST_APP_IN_DEV_MODE?: boolean; // Added in v59METABASE_EMBEDDING_SDK_AUTH_STATE?: import("embedding-sdk-shared/types/auth-state").SdkAuthState;+ FORCE_REFRESH_GUEST_EMBED_TOKEN_IN_CYPRESS?: boolean;}diff --git a/frontend/src/metabase/dashboard/components/DashCard/dashcard-ids.ts b/frontend/src/metabase/dashboard/components/DashCard/dashcard-ids.tsindex 35963a03b44..6caa25c2618 100644--- a/frontend/src/metabase/dashboard/components/DashCard/dashcard-ids.ts+++ b/frontend/src/metabase/dashboard/components/DashCard/dashcard-ids.ts@@ -1,4 +1,4 @@-import { isJWT } from "metabase/lib/utils";+import { isJWT } from "metabase/lib/jwt";import { isUuid } from "metabase/lib/uuid";import type { DashboardCard } from "metabase-types/api";diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsxindex 2c3891d2737..86ee70328ac 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx@@ -52,6 +52,7 @@ createTracker(store);export const SdkIframeEmbedRoute = () => {const { embedSettings } = useSdkIframeEmbedEventBus({onSettingsChanged,+ store,});const adjustedTheme = useMemo(@@ -94,6 +95,7 @@ export const SdkIframeEmbedRoute = () => {isGuest: embedSettings.isGuest,metabaseInstanceUrl: embedSettings.instanceUrl,apiKey: embedSettings.apiKey,+ guestEmbedProviderUri: embedSettings.guestEmbedProviderUri,} as MetabaseAuthConfig;return (@@ -165,6 +167,15 @@ const SdkIframeEmbedView = ({componentName: "metabase-dashboard",token: P.nonNullable,},+ /**+ * Need for initial token flow with JWT provider when the provider returns errors.+ * Without this, the InteractiveDashboard component will be rendered because+ * there is no `token`, so it won't match this pattern.+ */+ {+ componentName: "metabase-dashboard",+ guestEmbedProviderUri: P.nonNullable,+ },(settings) => {const entityProps: SdkDashboardEntityPublicProps = settings.token? {@@ -213,6 +224,14 @@ const SdkIframeEmbedView = ({/>),)+ // Exists solely to discriminate type from the pattern below when matching `guestEmbedProviderUri: P.nonNullable`+ .with(+ {+ componentName: "metabase-question",+ template: "exploration",+ },+ () => null,+ ).with(// Embedding based on a questionId (Metabase Account auth type) with disabled drills{@@ -229,6 +248,15 @@ const SdkIframeEmbedView = ({componentName: "metabase-question",token: P.nonNullable,},+ /**+ * Need for initial token flow with JWT provider when the provider returns errors.+ * Without this, nothing will be rendered because+ * there is no `token`, so it won't match this pattern.+ */+ {+ componentName: "metabase-question",+ guestEmbedProviderUri: P.nonNullable,+ },(settings) => {const entityProps: SdkQuestionEntityPublicProps = settings.token? {diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.tsindex 9cf1bfa6d98..8a0076247e2 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts@@ -28,6 +28,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {"isGuest","jwtProviderUri","pluginsConfig",+ "guestEmbedProviderUri",] satisfies (keyof SdkIframeEmbedBaseSettings)[],dashboard: ["dashboardId",@@ -39,6 +40,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {"hiddenParameters","drills","enableEntityNavigation",+ "customContext",] satisfies (keyof DashboardEmbedOptions)[],chart: ["questionId",@@ -50,6 +52,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {"hiddenParameters","drills","entityTypes",+ "customContext",] satisfies (keyof QuestionEmbedOptions)[],exploration: ["template",diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.tsindex 3b2eb9220e5..386edc2fcf9 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.ts@@ -1,10 +1,12 @@import { MetabaseError, SSO_NOT_ALLOWED } from "embedding-sdk-bundle/errors";+import * as MetabaseErrors from "embedding-sdk-bundle/errors";import { PLUGIN_EMBED_JS_EE } from "metabase/embedding/embedding-iframe-sdk/plugin";import type {EmbedAuthManager,EmbedAuthManagerContext,} from "metabase/embedding/embedding-iframe-sdk/types/auth-manager";import type { ComponentToAttributes } from "metabase/embedding/embedding-iframe-sdk/types/modular-embedding";+import { decodeJwt } from "metabase/lib/jwt";import { debouncedReportAnalytics } from "./analytics";import {@@ -157,6 +159,12 @@ export abstract class MetabaseEmbedElement<T extends string[] = string[]>Set<SdkIframeEmbedEventHandler>> = new Map();private _authManager: EmbedAuthManager | null = null;+ ["custom-context"]: unknown;++ constructor() {+ super();+ this["custom-context"] = undefined;+ }get globalSettings() {return (window as any).metabaseConfig || {};@@ -428,7 +436,16 @@ export abstract class MetabaseEmbedElement<T extends string[] = string[]>// this is used from tests to await the loading of the iframethis._iframe.setAttribute("data-iframe-loaded", "true");}- this._updateSettings(this.properties);++ const { guestEmbedProviderUri, token } = this.properties;++ // No static token provided — fetch initial guest token first, then send settings+ if (guestEmbedProviderUri && !token) {+ await this._fetchInitialGuestToken();+ } else {+ this._updateSettings(this.properties);+ }+this._emitEvent({ type: "ready" });}@@ -436,6 +453,10 @@ export abstract class MetabaseEmbedElement<T extends string[] = string[]>await this._authenticate();}+ if (event.data.type === "metabase.embed.requestGuestTokenRefresh") {+ await this._refreshGuestToken(event.data.data.expiredToken);+ }+// Note: if we wrap other functions like this, let's come up with a generic utility functionif (event.data.type === "metabase.embed.handleLink") {const { url, requestId } = event.data.data;@@ -488,17 +509,138 @@ export abstract class MetabaseEmbedElement<T extends string[] = string[]>}}+ private reportAuthenticationError(error: unknown) {+ this.sendMessage("metabase.embed.reportAuthenticationError", {+ error:+ error instanceof MetabaseError+ ? error+ : MetabaseErrors.CANNOT_FETCH_JWT_TOKEN({+ url: this.properties.guestEmbedProviderUri ?? "",+ message: error instanceof Error ? error.message : String(error),+ }),+ });+ }+private async _authenticate() {if (!this._authManager) {- this.sendMessage("metabase.embed.reportAuthenticationError", {- error: SSO_NOT_ALLOWED(),- });+ this.reportAuthenticationError(SSO_NOT_ALLOWED());return;}await this._authManager.authenticate();}++ private async _fetchInitialGuestToken(): Promise<void> {+ try {+ const token = await this._callGuestTokenProvider();+ this._updateSettings({+ token,+ /**+ * Clear these so SdkIframeEmbedRoute routes via the guest token branch, not the+ * other branches (which matches on dashboardId/questionId). This applies to the+ * call below too.+ */+ dashboardId: undefined,+ questionId: undefined,+ });+ } catch (error) {+ this.reportAuthenticationError(error);+ // Send settings without a token so ComponentProvider can mount and display the error.+ this._updateSettings({+ dashboardId: undefined,+ questionId: undefined,+ });+ }+ }++ private async _refreshGuestToken(expiredToken: string): Promise<void> {+ try {+ const token = await this._callGuestTokenProvider(expiredToken);+ this.sendMessage("metabase.embed.submitRefreshedGuestToken", {+ guestToken: token,+ });+ } catch (error) {+ this.reportAuthenticationError(error);+ }+ }++ /**+ * Handles token refresh, and the initial token fetch if no static token is provided.+ * Unlike the SSO counterpart which lives in the plugin system (AuthManager.ts),+ * guest embeds are OSS so this is implemented directly here in embed.ts.+ */+ private async _callGuestTokenProvider(+ expiredToken?: string,+ ): Promise<string> {+ const { guestEmbedProviderUri, componentName, dashboardId, questionId } =+ this.properties;++ if (!guestEmbedProviderUri) {+ throw MetabaseErrors.CANNOT_FETCH_JWT_TOKEN({+ url: String(guestEmbedProviderUri),+ message: "Guest embed provider URI is not configured.",+ });+ }++ const guestEmbedProviderUriFullPath = new URL(+ guestEmbedProviderUri,+ window.location.origin,+ );+ guestEmbedProviderUriFullPath.searchParams.set("response", "json");++ const entityType =+ componentName === "metabase-dashboard" ? "dashboard" : "question";++ const isRefreshingToken = expiredToken !== undefined;++ // Prefer the attribute resource ID; fall back to decoding the expired token+ // for the static token case (no dashboardId/questionId attribute).+ const attributeResourceId =+ componentName === "metabase-dashboard" ? dashboardId : questionId;+ const tokenResourceId = isRefreshingToken+ ? decodeJwt(expiredToken)?.resource?.[entityType]+ : undefined;+ const resourceId = attributeResourceId ?? tokenResourceId;++ // Only works in React 19+ const objectCustomContext = this["custom-context"];+ const stringCustomContext = this.getAttribute("custom-context");+ const customContext = objectCustomContext ?? stringCustomContext;+ const body = {+ entityType,+ entityId: resourceId,+ ...(customContext !== undefined && { customContext }),+ };++ const response = await fetch(guestEmbedProviderUriFullPath.toString(), {+ method: "POST",+ credentials: "include",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });++ if (!response.ok) {+ throw MetabaseErrors.CANNOT_FETCH_JWT_TOKEN({+ url: guestEmbedProviderUri,+ status: String(response.status),+ });+ }++ const data = await response.json();++ if (+ data == null ||+ typeof data !== "object" ||+ typeof data.jwt !== "string"+ ) {+ throw MetabaseErrors.DEFAULT_ENDPOINT_ERROR({+ actual: JSON.stringify(data),+ });+ }++ return data.jwt;+ }}function createCustomElement<diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.tsindex 8a565ae6b53..cf16421caa1 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/embed.unit.spec.ts@@ -1,6 +1,8 @@+import fetchMock from "fetch-mock";+import jwt from "jsonwebtoken";import { act } from "react-dom/test-utils";-import type { MetabaseEmbedElement } from "./embed";+import { MetabaseEmbedElement } from "./embed";const defineMetabaseConfig = (config: unknown) => {(window as any).metabaseConfig = config;@@ -205,4 +207,271 @@ describe("embed.js script tag for sdk iframe embedding", () => {/^https:\/\/example\.com\/embed\/sdk\/v1\?embed-js-identifier=\d+$/,);});++ describe("guest embed token provider", () => {+ // Wait for all fetch mocks, and async/await to finish+ const flushPromises = () =>+ new Promise<void>((resolve) => setTimeout(resolve, 0));++ function setupGuestEmbed({+ dashboardId,+ token,+ customContext,+ }: {+ dashboardId: string;+ token?: string;+ customContext?: string;+ }) {+ defineMetabaseConfig({+ instanceUrl: "http://localhost:3000",+ guestEmbedProviderUri: "/mock-provider",+ });++ const embed = document.createElement("metabase-dashboard");+ embed.setAttribute("dashboard-id", dashboardId);+ if (token) {+ embed.setAttribute("token", token);+ }+ if (customContext && embed instanceof MetabaseEmbedElement) {+ embed.setAttribute("custom-context", customContext);+ }+ document.body.appendChild(embed);++ const iframe = embed.querySelector("iframe") as HTMLIFrameElement;+ const iframePostMessageSpy = jest.spyOn(+ iframe.contentWindow!,+ "postMessage",+ );++ const triggerIframeMessage = (data: unknown) => {+ window.dispatchEvent(+ new MessageEvent("message", { data, source: iframe.contentWindow }),+ );+ };++ return { embed, iframe, iframePostMessageSpy, triggerIframeMessage };+ }++ describe("refresh token only (static token)", () => {+ it("skips provider fetch and sends setSettings directly with static token", async () => {+ const { triggerIframeMessage, iframePostMessageSpy } = setupGuestEmbed({+ dashboardId: "1",+ token: "static-jwt-token",+ });++ triggerIframeMessage({ type: "metabase.embed.iframeReady" });+ await flushPromises();++ expect(fetchMock.callHistory.calls("path:/mock-provider")).toHaveLength(+ 0,+ );+ expect(iframePostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "metabase.embed.setSettings",+ data: expect.objectContaining({ token: "static-jwt-token" }),+ }),+ "*",+ );+ });++ it("POSTs { entityType, entityId, customContext } to provider and sends submitRefreshedGuestToken", async () => {+ const expiredToken = jwt.sign(+ {+ resource: { dashboard: 1 },+ /**+ * 60 seconds ago. By the way, the expiration isn't verified here.+ * But why mock any other value when we're passing an expired token here.+ */+ exp: Math.floor(Date.now() / 1000) - 60,+ },+ "jwt-secret",+ );++ fetchMock.post("path:/mock-provider", { jwt: "refreshed-token" });++ const { triggerIframeMessage, iframePostMessageSpy } = setupGuestEmbed({+ dashboardId: "1",+ customContext: "my-context",+ });++ triggerIframeMessage({+ type: "metabase.embed.requestGuestTokenRefresh",+ data: { expiredToken },+ });+ await flushPromises();++ const call = fetchMock.callHistory.lastCall("path:/mock-provider");+ expect(call?.url).toContain("response=json");+ expect(call?.options).toMatchObject({+ method: "post",+ body: JSON.stringify({+ entityType: "dashboard",+ entityId: 1,+ customContext: "my-context",+ }),+ });++ expect(iframePostMessageSpy).toHaveBeenCalledWith(+ {+ type: "metabase.embed.submitRefreshedGuestToken",+ data: { guestToken: "refreshed-token" },+ },+ "*",+ );+ });++ it("sends reportAuthenticationError to iframe when provider returns HTTP error", async () => {+ fetchMock.post("path:/mock-provider", 403);++ const { triggerIframeMessage, iframePostMessageSpy } = setupGuestEmbed({+ dashboardId: "1",+ });++ triggerIframeMessage({+ type: "metabase.embed.requestGuestTokenRefresh",+ data: { expiredToken: "any.expired.token" },+ });+ await flushPromises();++ expect(iframePostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "metabase.embed.reportAuthenticationError",+ data: {+ error: expect.objectContaining({+ code: "CANNOT_FETCH_JWT_TOKEN",+ }),+ },+ }),+ "*",+ );+ });++ it("sends reportAuthenticationError to iframe when provider returns invalid JSON shape", async () => {+ fetchMock.post("path:/mock-provider", { token: "wrong-field-name" });++ const { triggerIframeMessage, iframePostMessageSpy } = setupGuestEmbed({+ dashboardId: "1",+ });++ triggerIframeMessage({+ type: "metabase.embed.requestGuestTokenRefresh",+ data: { expiredToken: "any.expired.token" },+ });+ await flushPromises();++ expect(iframePostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "metabase.embed.reportAuthenticationError",+ data: {+ error: expect.objectContaining({+ code: "DEFAULT_ENDPOINT_ERROR",+ }),+ },+ }),+ "*",+ );+ });+ });++ describe("initial token (no static token)", () => {+ it("fetches initial token from provider with { entityType, entityId, customContext } and sends setSettings", async () => {+ fetchMock.post("path:/mock-provider", { jwt: "initial-token" });++ const { triggerIframeMessage, iframePostMessageSpy } = setupGuestEmbed({+ dashboardId: "1",+ customContext: "my-context",+ });++ triggerIframeMessage({ type: "metabase.embed.iframeReady" });+ await flushPromises();++ const call = fetchMock.callHistory.lastCall("path:/mock-provider");+ expect(call?.url).toContain("response=json");+ expect(call?.options).toMatchObject({+ method: "post",+ body: JSON.stringify({+ entityType: "dashboard",+ entityId: 1,+ customContext: "my-context",+ }),+ });++ expect(iframePostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "metabase.embed.setSettings",+ data: {+ token: "initial-token",+ // The rest of the properties+ instanceUrl: "http://localhost:3000",+ guestEmbedProviderUri: "/mock-provider",+ // dashboardId and questionId are not sent — the token already encodes the resource+ dashboardId: undefined,+ questionId: undefined,+ componentName: "metabase-dashboard",+ _isLocalhost: true,+ },+ }),+ "*",+ );+ });++ it("sends reportAuthenticationError when initial token fetch returns HTTP error", async () => {+ fetchMock.post("path:/mock-provider", 500);++ const { triggerIframeMessage, iframePostMessageSpy } = setupGuestEmbed({+ dashboardId: "1",+ });++ triggerIframeMessage({ type: "metabase.embed.iframeReady" });+ await flushPromises();++ expect(iframePostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "metabase.embed.reportAuthenticationError",+ data: {+ error: expect.objectContaining({+ code: "CANNOT_FETCH_JWT_TOKEN",+ }),+ },+ }),+ "*",+ );++ expect(iframePostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "metabase.embed.setSettings",+ data: expect.objectContaining({+ // dashboardId and questionId are not sent on error path either+ dashboardId: undefined,+ questionId: undefined,+ }),+ }),+ "*",+ );+ });++ it("sends reportAuthenticationError when initial token fetch returns invalid JSON shape", async () => {+ fetchMock.post("path:/mock-provider", { token: "wrong-field" });++ const { triggerIframeMessage, iframePostMessageSpy } = setupGuestEmbed({+ dashboardId: "1",+ });++ triggerIframeMessage({ type: "metabase.embed.iframeReady" });+ await flushPromises();++ expect(iframePostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "metabase.embed.reportAuthenticationError",+ data: {+ error: expect.objectContaining({+ code: "DEFAULT_ENDPOINT_ERROR",+ }),+ },+ }),+ "*",+ );+ });+ });+ });});diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/hooks/use-sdk-iframe-embed-event-bus.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/hooks/use-sdk-iframe-embed-event-bus.tsindex 5e1c4d06547..56b90441717 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/hooks/use-sdk-iframe-embed-event-bus.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/hooks/use-sdk-iframe-embed-event-bus.ts@@ -1,6 +1,8 @@import { useEffect, useState } from "react";import { match } from "ts-pattern";+import { setGuestTokenFetchError } from "embedding-sdk-bundle/store/guest-embed";+import type { SdkStore } from "embedding-sdk-bundle/store/types";import { trackSchemaEvent } from "metabase/lib/analytics";import { isWithinIframe } from "metabase/lib/dom";import type { EmbeddedAnalyticsJsEventSchema } from "metabase-types/analytics/embedded-analytics-js";@@ -24,8 +26,10 @@ const sendMessage = (message: SdkIframeEmbedTagMessage) => {export function useSdkIframeEmbedEventBus({onSettingsChanged,+ store,}: {onSettingsChanged?: (settings: SdkIframeEmbedSettings) => void;+ store: SdkStore;}) {const [embedSettings, setEmbedSettings] =useState<SdkIframeEmbedSettings | null>(null);@@ -49,7 +53,21 @@ export function useSdkIframeEmbedEventBus({usage: data.usageAnalytics,embedHostUrl: data.embedHostUrl,});- });+ })++ /**+ * This handler is needed for the guest embed initial token flow. It also handles+ * the refresh flow, but `request-session-token.ts` handles that too — that file+ * covers both the SSO and the JWT refresh token flows.+ */+ .with(+ { type: "metabase.embed.reportAuthenticationError" },+ ({ data }) => {+ store.dispatch(+ setGuestTokenFetchError({ message: data.error?.message }),+ );+ },+ );};window.addEventListener("message", messageHandler);@@ -60,7 +78,7 @@ export function useSdkIframeEmbedEventBus({return () => {window.removeEventListener("message", messageHandler);};- }, [onSettingsChanged]);+ }, [onSettingsChanged, store]);useEffect(() => {if (embedSettings?.instanceUrl && usageAnalytics) {diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.tsindex 7353276fbb3..d6dda6b356a 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts@@ -26,7 +26,8 @@ import type { EmbeddingEntityType } from "metabase-types/store/embedding-data-piexport type SdkIframeEmbedTagMessage =| SdkIframeEmbedTagIframeReadyMessage| SdkIframeEmbedTagRequestSessionTokenMessage- | SdkIframeEmbedTagHandleLinkMessage;+ | SdkIframeEmbedTagHandleLinkMessage+ | SdkIframeEmbedTagRequestGuestTokenRefreshMessage;export type SdkIframeEmbedTagIframeReadyMessage = {type: "metabase.embed.iframeReady";@@ -38,6 +39,12 @@ export type SdkIframeEmbedTagHandleLinkMessage = {type: "metabase.embed.handleLink";data: { url: string; requestId: string };};+export type SdkIframeEmbedTagRequestGuestTokenRefreshMessage = {+ type: "metabase.embed.requestGuestTokenRefresh";+ data: {+ expiredToken: string;+ };+};/** Events that the sdk embed route listens for */export type SdkIframeEmbedMessage =@@ -45,7 +52,8 @@ export type SdkIframeEmbedMessage =| SdkIframeEmbedSubmitSessionTokenMessage| SdkIframeEmbedReportAuthenticationError| SdkIframeEmbedReportAnalytics- | SdkIframeEmbedHandleLinkResponse;+ | SdkIframeEmbedHandleLinkResponse+ | SdkIframeEmbedSubmitRefreshedGuestTokenMessage;export type SdkIframeEmbedSetSettingsMessage = {type: "metabase.embed.setSettings";@@ -75,6 +83,12 @@ export type SdkIframeEmbedHandleLinkResponse = {type: "metabase.embed.handleLinkResponse";data: { requestId: string; handled: boolean };};+export type SdkIframeEmbedSubmitRefreshedGuestTokenMessage = {+ type: "metabase.embed.submitRefreshedGuestToken";+ data: {+ guestToken: string;+ };+};// --- Embed Option Interfaces ---@@ -94,6 +108,8 @@ export type DashboardEmbedOptions = StrictUnion<hiddenParameters?: string[];enableEntityNavigation?: boolean;+ customContext?: string | Record<string, unknown>;+// incompatible optionstemplate?: never;questionId?: never;@@ -116,6 +132,8 @@ export type QuestionEmbedOptions = StrictUnion<initialSqlParameters?: SqlParameterValues;hiddenParameters?: string[];+ customContext?: string | Record<string, unknown>;+// incompatible optionstemplate?: never;dashboardId?: never;@@ -213,6 +231,14 @@ export type SdkIframeEmbedBaseSettings = {/** Whether we should use the existing user session (i.e. admin user's cookie) */useExistingUserSession?: boolean;+ /**+ * URL endpoint for fetching and refreshing guest embed JWT tokens (iframe only, not applicable for SDK's guest mode).+ * Supports both token refresh on expiry and initial token fetch when no static token is provided.+ * In both cases, this works with guest embed components (metabase-dashboard and metabase-question).+ * The endpoint should return { jwt: string } with the new token.+ */+ guestEmbedProviderUri?: string;+// Whether the embed is running on localhost. Cannot be set by the user._isLocalhost?: boolean;diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.tsindex b332430451d..eaebfbd4456 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/modular-embedding.ts@@ -90,6 +90,13 @@ export interface MetabaseDashboardAttributes {* @remarks Pro/Enterprise*/"enable-entity-navigation"?: boolean;++ /**+ * Optional custom context string passed through to the guest token endpoint.+ *+ * @remarks Guest embed+ */+ "custom-context"?: string;}/**@@ -186,6 +193,13 @@ export interface MetabaseQuestionAttributes {* @remarks Pro/Enterprise, Guest embed*/"entity-types"?: ("model" | "table")[];++ /**+ * Optional custom context string passed through to the guest token endpoint.+ *+ * @remarks Guest embed+ */+ "custom-context"?: string;}/**diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/request-session-token.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/request-session-token.tsindex a39f8e0a2b2..d6f1bc85ff3 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/request-session-token.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/request-session-token.ts@@ -11,50 +11,80 @@ import type {/*** Requests a refresh token from the embed.js script which lives in the parent window.+ * Supports both SSO authentication and guest token refresh.*/-export function requestSessionTokenFromEmbedJs(): Promise<MetabaseEmbeddingSessionToken> {- return new Promise<MetabaseEmbeddingSessionToken>((resolve, reject) => {- const timeout = setTimeout(() => {- window.removeEventListener("message", handler);- reject(AUTH_TIMEOUT());- }, WAIT_FOR_SESSION_TOKEN_TIMEOUT);-- const handler = (event: MessageEvent<SdkIframeEmbedMessage>) => {- if (!isWithinIframe() || !event.data) {- return;- }+export function requestSessionTokenFromEmbedJs(): Promise<MetabaseEmbeddingSessionToken>;+export function requestSessionTokenFromEmbedJs(options: {+ expiredToken: string;+}): Promise<string>;+export function requestSessionTokenFromEmbedJs(options?: {+ expiredToken: string;+}): Promise<MetabaseEmbeddingSessionToken | string> {+ return new Promise<MetabaseEmbeddingSessionToken | string>(+ (resolve, reject) => {+ const timeout = setTimeout(() => {+ window.removeEventListener("message", handler);+ reject(AUTH_TIMEOUT());+ }, WAIT_FOR_SESSION_TOKEN_TIMEOUT);++ const handler = (event: MessageEvent<SdkIframeEmbedMessage>) => {+ if (!isWithinIframe() || !event.data) {+ return;+ }++ const action = event.data;- const action = event.data;+ // Handle SSO session token response+ if (action.type === "metabase.embed.submitSessionToken") {+ const { authMethod, sessionToken } = action.data;- if (action.type === "metabase.embed.submitSessionToken") {- const { authMethod, sessionToken } = action.data;+ // Persist the session token to the iframe's local storage,+ // so we don't show the popup again.+ if (authMethod === "saml") {+ samlTokenStorage.set(sessionToken);+ }- // Persist the session token to the iframe's local storage,- // so we don't show the popup again.- if (authMethod === "saml") {- samlTokenStorage.set(sessionToken);+ window.removeEventListener("message", handler);+ clearTimeout(timeout);+ resolve(sessionToken);}- window.removeEventListener("message", handler);- clearTimeout(timeout);- resolve(sessionToken);- }+ // Handle guest token refresh response+ if (action.type === "metabase.embed.submitRefreshedGuestToken") {+ const { guestToken } = action.data;- if (action.type === "metabase.embed.reportAuthenticationError") {- const { error } = action.data;+ window.removeEventListener("message", handler);+ clearTimeout(timeout);+ resolve(guestToken);+ }- window.removeEventListener("message", handler);- clearTimeout(timeout);- reject(error);- }- };+ // Handle errors from both flows+ if (action.type === "metabase.embed.reportAuthenticationError") {+ const { error } = action.data;- window.addEventListener("message", handler);+ window.removeEventListener("message", handler);+ clearTimeout(timeout);+ reject(error);+ }+ };- const requestTokenMessage: SdkIframeEmbedTagMessage = {- type: "metabase.embed.requestSessionToken",- };+ window.addEventListener("message", handler);- window.parent.postMessage(requestTokenMessage, "*");- });+ // Send appropriate request message based on flow+ if (options?.expiredToken) {+ // is guest embed token refresh flow+ const guestEmbedSessionRefreshMessage: SdkIframeEmbedTagMessage = {+ type: "metabase.embed.requestGuestTokenRefresh",+ data: { expiredToken: options.expiredToken },+ };+ window.parent.postMessage(guestEmbedSessionRefreshMessage, "*");+ } else {+ // SSO flow+ const requestTokenMessage: SdkIframeEmbedTagMessage = {+ type: "metabase.embed.requestSessionToken",+ };+ window.parent.postMessage(requestTokenMessage, "*");+ }+ },+ );}diff --git a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.tsindex f9f94e632de..31dd4df7abc 100644--- a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts@@ -4,7 +4,7 @@ import {PLUGIN_CONTENT_TRANSLATION,PLUGIN_EMBEDDING_SDK,} from "metabase/plugins";-import type { OnBeforeRequestHandlerData } from "metabase/plugins/oss/api";+import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";import { getEmbedBase, internalBase, publicBase } from "metabase/services";import type { CardId, DashboardId, ParameterId } from "metabase-types/api";@@ -187,7 +187,8 @@ const overrideRequests = async ({method,url,options,-}: OnBeforeRequestHandlerData & {+ data,+}: OnBeforeRequestHandlerConfig & {embedType: EmbedType;}) => {const transformation = getRequestTransformation({@@ -198,7 +199,7 @@ const overrideRequests = async ({});if (!transformation) {- return { method, url, options };+ return { method, url, options, data };}if (!options.headers) {@@ -214,6 +215,7 @@ const overrideRequests = async ({method: transformation.method,url: replaceWithEmbedBase({ embedType, url: transformation.url }),options: transformation.options,+ data,};};diff --git a/frontend/src/metabase/lib/api.js b/frontend/src/metabase/lib/api.jsindex 3f6ba628ec5..636c99af80b 100644--- a/frontend/src/metabase/lib/api.js+++ b/frontend/src/metabase/lib/api.js@@ -125,15 +125,15 @@ export class Api extends EventEmitter {};return async (rawData, invocationOptions = {}) => {- let { url, method, options } =+ let { url, method, options, data } =await this.apiRequestManipulationMiddleware({url: urlTemplate,method: methodTemplate,options: { ...defaultOptions, ...invocationOptions },+ // this will transform arrays to objects with numeric keys+ // we shouldn't be using top level-arrays in the API+ data: { ...rawData },});- // this will transform arrays to objects with numeric keys- // we shouldn't be using top level-arrays in the API- const data = { ...rawData };for (const tag of url.match(/:\w+/g) || []) {const paramName = tag.slice(1);let value = data[paramName];@@ -376,16 +376,16 @@ export class Api extends EventEmitter {}/**- * @param data {import('metabase/plugins').OnBeforeRequestHandlerData}- * @return data {Promise<import('metabase/plugins').OnBeforeRequestHandlerData>}+ * @param {import('metabase/plugins/oss/api').OnBeforeRequestHandlerConfig} data+ * @return {Promise<import('metabase/plugins/oss/api').OnBeforeRequestHandlerConfig>}*/- async apiRequestManipulationMiddleware(data) {- let { method, url, options } = data;+ async apiRequestManipulationMiddleware(requestConfig) {+ let { method, url, options, data } = requestConfig;/*** Handlers order is important.* Handlers are executed in order and each handler uses the data returned by a previous handler.- * @type {import('metabase/plugins').OnBeforeRequestHandler[]}+ * @type {import('metabase/plugins/oss/api').OnBeforeRequestHandler[]}*/const handlers = [];@@ -394,6 +394,8 @@ export class Api extends EventEmitter {...[PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler,+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers+ .getOrRefreshGuestSessionHandler,PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.overrideRequestsForGuestEmbeds,],@@ -413,6 +415,7 @@ export class Api extends EventEmitter {method,url,options,+ data,});if (onBeforeRequestHandlerResult) {@@ -430,11 +433,18 @@ export class Api extends EventEmitter {...onBeforeRequestHandlerResult.options,};}++ if (onBeforeRequestHandlerResult.data) {+ data = {+ ...data,+ ...onBeforeRequestHandlerResult.data,+ };+ }}}}- return { method, url, options };+ return { method, url, options, data };}}diff --git a/frontend/src/metabase/lib/dashboard.ts b/frontend/src/metabase/lib/dashboard.tsindex 51a69b82c56..d04e13b7ec3 100644--- a/frontend/src/metabase/lib/dashboard.ts+++ b/frontend/src/metabase/lib/dashboard.ts@@ -1,6 +1,6 @@import _ from "underscore";-import { isJWT } from "metabase/lib/utils";+import { isJWT } from "metabase/lib/jwt";import { isUuid } from "metabase/lib/uuid";import type {ActionDashboardCard,diff --git a/frontend/src/metabase/lib/jwt.ts b/frontend/src/metabase/lib/jwt.tsnew file mode 100644index 00000000000..f8c8d633b4a--- /dev/null+++ b/frontend/src/metabase/lib/jwt.ts@@ -0,0 +1,83 @@+import type { EntityToken } from "metabase-types/api/entity";++const JWT_REGEX = /[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/;++export function isJWT(string: unknown): string is string {+ if (typeof string !== "string") {+ return false;+ }+ const match = JWT_REGEX.exec(string);+ return match !== null && match[0] === string;+}++/**+ * Decodes a JWT token and returns its payload.+ * Uses Uint8Array/TextDecoder instead of manual decodeURIComponent for safer UTF-8 decoding.+ *+ * @param jwtToken - JWT token string+ * @returns Decoded payload object or null if decoding fails+ */+export const decodeJwt = (+ jwtToken: string | null | undefined,+): Record<string, any> | null => {+ if (!jwtToken) {+ return null;+ }++ try {+ const parts = jwtToken.split(".");+ if (parts.length !== 3) {+ return null;+ }++ const payloadPart = parts[1];++ // Convert base64url to base64+ let base64 = payloadPart.replace(/-/g, "+").replace(/_/g, "/");++ // Add padding if needed+ const padding = base64.length % 4;+ if (padding === 2) {+ base64 += "==";+ } else if (padding === 3) {+ base64 += "=";+ } else if (padding !== 0) {+ throw new Error("Invalid base64url payload");+ }++ // Decode base64 to binary string, then to Uint8Array+ const binaryString = window.atob(base64);+ const bytes = new Uint8Array(binaryString.length);+ for (let i = 0; i < binaryString.length; i++) {+ bytes[i] = binaryString.charCodeAt(i);+ }++ // Decode UTF-8 bytes to string using TextDecoder (safer than manual decoding)+ const jsonString = new TextDecoder().decode(bytes);++ // Parse JSON payload+ const payload = JSON.parse(jsonString);+ return payload;+ } catch (error) {+ console.error("Failed to decode JWT:", error);+ return null;+ }+};++/**+ * Extract resource id from signed JWT token used in Static Embedding.+ */+export const extractResourceIdFromJwtToken = (+ jwtToken: EntityToken,+): number | null => {+ const payload = decodeJwt(jwtToken);++ if (!payload?.resource) {+ return null;+ }++ const resource = payload.resource;+ const entityId = resource.dashboard || resource.question;++ return entityId ?? null;+};diff --git a/frontend/src/metabase/lib/utils.unit.spec.ts b/frontend/src/metabase/lib/jwt.unit.spec.tssimilarity index 94%rename from frontend/src/metabase/lib/utils.unit.spec.tsrename to frontend/src/metabase/lib/jwt.unit.spec.tsindex 7ad60f5b6de..8d45e3f511d 100644--- a/frontend/src/metabase/lib/utils.unit.spec.ts+++ b/frontend/src/metabase/lib/jwt.unit.spec.ts@@ -1,6 +1,6 @@import { SignJWT } from "jose";-import { extractResourceIdFromJwtToken } from "metabase/lib/utils";+import { extractResourceIdFromJwtToken } from "metabase/lib/jwt";const SECRET = new TextEncoder().encode("test-secret-key-for-jwt-signing");@@ -54,7 +54,7 @@ describe("extractResourceIdFromJwtToken", () => {resource: { other: "value" },});- expect(extractResourceIdFromJwtToken(token)).toBeUndefined();+ expect(extractResourceIdFromJwtToken(token)).toBeNull();});it("should return null for invalid base64 payload", () => {diff --git a/frontend/src/metabase/lib/utils.ts b/frontend/src/metabase/lib/utils.tsindex 4a500507554..2ddb3e4185f 100644--- a/frontend/src/metabase/lib/utils.ts+++ b/frontend/src/metabase/lib/utils.ts@@ -2,7 +2,6 @@ import { t } from "ttag";import _ from "underscore";import { PLUGIN_IS_EE_BUILD } from "metabase/plugins";-import type { EntityToken } from "metabase-types/api/entity";export function isEmpty(str: string | null) {if (str != null) {@@ -33,13 +32,6 @@ export function numberToWord(num: number) {}}-export function isJWT(string: unknown): string is string {- return (- typeof string === "string" &&- /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(string)- );-}-export function equals(a: unknown, b: unknown) {return _.isEqual(a, b);}@@ -155,35 +147,3 @@ export function versionIsLatest({* ie: "Switch binary" vs "Put a valid token in the settings"*/export const isEEBuild = () => PLUGIN_IS_EE_BUILD.isEEBuild();--// Extract resource id from signed JWT token used in Static Embedding-export const extractResourceIdFromJwtToken = (jwtToken: EntityToken) => {- try {- const parts = jwtToken.split(".");- const payloadPart = parts[1];-- let base64 = payloadPart.replace(/-/g, "+").replace(/_/g, "/");- const padding = base64.length % 4;-- if (padding === 2) {- base64 += "==";- } else if (padding === 3) {- base64 += "=";- } else if (padding !== 0) {- throw new Error("Invalid base64url payload");- }-- const jsonString = decodeURIComponent(- Array.from(window.atob(base64))- .map((c) => "%" + c.charCodeAt(0).toString(16).padStart(2, "0"))- .join(""),- );- const payload = JSON.parse(jsonString);- const resource = payload.resource;- const entityId = resource.dashboard || resource.question;-- return entityId;- } catch {- return null;- }-};diff --git a/frontend/src/metabase/plugins/oss/api.ts b/frontend/src/metabase/plugins/oss/api.tsindex 91bb76d35b2..3037fc31ad5 100644--- a/frontend/src/metabase/plugins/oss/api.ts+++ b/frontend/src/metabase/plugins/oss/api.ts@@ -1,26 +1,27 @@import type { CardId, DashboardId, ParameterId } from "metabase-types/api";-export type OnBeforeRequestHandlerData = {+export type OnBeforeRequestHandlerConfig = {method: "GET" | "POST";url: string;options: {headers?: Record<string, string>;hasBody: boolean;} & Record<string, unknown>;+ data: Record<string, unknown>;};export type OnBeforeRequestHandler = (- data: OnBeforeRequestHandlerData,-) => Promise<void | OnBeforeRequestHandlerData>;+ data: OnBeforeRequestHandlerConfig,+) => Promise<void | OnBeforeRequestHandlerConfig>;const getDefaultPluginApi = () => ({onBeforeRequestHandlers: {overrideRequestsForPublicEmbeds: async (- _data: OnBeforeRequestHandlerData,- ): Promise<OnBeforeRequestHandlerData | void> => {},+ _data: OnBeforeRequestHandlerConfig,+ ): Promise<OnBeforeRequestHandlerConfig | void> => {},overrideRequestsForStaticEmbeds: async (- _data: OnBeforeRequestHandlerData,- ): Promise<OnBeforeRequestHandlerData | void> => {},+ _data: OnBeforeRequestHandlerConfig,+ ): Promise<OnBeforeRequestHandlerConfig | void> => {},},getRemappedCardParameterValueUrl: (cardId: CardId | string | undefined,diff --git a/frontend/src/metabase/plugins/oss/embedding-sdk.ts b/frontend/src/metabase/plugins/oss/embedding-sdk.tsindex f25ae74eeb8..27505983310 100644--- a/frontend/src/metabase/plugins/oss/embedding-sdk.ts+++ b/frontend/src/metabase/plugins/oss/embedding-sdk.ts@@ -1,12 +1,15 @@-import type { OnBeforeRequestHandlerData } from "metabase/plugins/oss/api";+import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";const getDefaultPluginEmbeddingSdk = () => ({isEnabled: () => false,onBeforeRequestHandlers: {getOrRefreshSessionHandler: async () => {},+ getOrRefreshGuestSessionHandler: async (+ _data: OnBeforeRequestHandlerConfig,+ ): Promise<OnBeforeRequestHandlerConfig | void> => {},overrideRequestsForGuestEmbeds: async (- _data: OnBeforeRequestHandlerData,- ): Promise<OnBeforeRequestHandlerData | void> => {},+ _data: OnBeforeRequestHandlerConfig,+ ): Promise<OnBeforeRequestHandlerConfig | void> => {},},});diff --git a/frontend/src/metabase/redux/downloads.ts b/frontend/src/metabase/redux/downloads.tsindex a03171f839d..07a1c436eb1 100644--- a/frontend/src/metabase/redux/downloads.ts+++ b/frontend/src/metabase/redux/downloads.ts@@ -14,10 +14,10 @@ import { DASHBOARD_PDF_EXPORT_ROOT_ID } from "metabase/dashboard/constants";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import api, { GET, POST } from "metabase/lib/api";import { isWithinIframe, openSaveDialog } from "metabase/lib/dom";+import { isJWT } from "metabase/lib/jwt";import { createAsyncThunk } from "metabase/lib/redux";import { checkNotNull } from "metabase/lib/types";import * as Urls from "metabase/lib/urls";-import { isJWT } from "metabase/lib/utils";import { isUuid } from "metabase/lib/uuid";import { getTokenFeature } from "metabase/setup/selectors";import { saveChartImage } from "metabase/visualizations/lib/save-chart-image";diff --git a/frontend/src/metabase/visualizations/lib/map.ts b/frontend/src/metabase/visualizations/lib/map.tsindex 4b0ef2b88a8..27a30c4befe 100644--- a/frontend/src/metabase/visualizations/lib/map.ts+++ b/frontend/src/metabase/visualizations/lib/map.ts@@ -1,5 +1,5 @@import { IS_EMBED_PREVIEW } from "metabase/lib/embed";-import { isJWT } from "metabase/lib/utils";+import { isJWT } from "metabase/lib/jwt";import { isUuid } from "metabase/lib/uuid";import type { DashboardId, JsonQuery, Parameter } from "metabase-types/api";import type { EntityToken } from "metabase-types/api/entity";diff --git a/mage/resources/token_scanner/token_whitelist.txt b/mage/resources/token_scanner/token_whitelist.txtindex 06e22023a47..4f32c1d980d 100644--- a/mage/resources/token_scanner/token_whitelist.txt+++ b/mage/resources/token_scanner/token_whitelist.txt@@ -18,3 +18,6 @@ eyJkYXRhc2V0X3F1ZXJ5Ijp7ImxpYi90eXBlIjoibWJxbC9xdWVyeSIsInN0YWdlcyI6W3sic291cmNl# invalid jwt token for testseyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIn0.invalid-signature++# Used in storybook SdkError.stories.tsx+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZXNvdXJjZSI6eyJkYXNoYm9hcmQiOjF9LCJwYXJhbXMiOnt9LCJleHAiOjE3NzQ2MDkyMDksImlhdCI6MTc3NDYwOTE5OX0.-S3eLFi_XZeb9ltaorP7_k52fXW_jhtb1oG-BuOVSWw