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
feat(embed-js): Add support of fetchRequestToken for embed-js (#64004)
Timofey Kachalov1d2fc06b60ee
diff --git a/docs/embedding/embedded-analytics-js.md b/docs/embedding/embedded-analytics-js.mdindex 36ad6bd4244..c8bb03821b3 100644--- a/docs/embedding/embedded-analytics-js.md+++ b/docs/embedding/embedded-analytics-js.md@@ -146,6 +146,8 @@ To define the configuration that applies to every embed on the page, use the `de- `apiKey: mb_YourAPIKey` (optional, for development only) - another way to preview embeds locally using an API key.+- `fetchRequestToken: () => Promise<{ jwt: string }>` (optional) - you can customize how the SDK fetches the refresh token for JWT authentication by specifying the `fetchRequestToken` function. See [customizing JWT authentication](./sdk/authentication.md#customizing-jwt-authentication).+### ThemingYou can specify colors, fonts, spacing, and other appearance options using the `theme` parameter in your embed configuration.diff --git a/docs/embedding/sdk/authentication.md b/docs/embedding/sdk/authentication.mdindex d6beca62381..0328de5c7e6 100644--- a/docs/embedding/sdk/authentication.md+++ b/docs/embedding/sdk/authentication.md@@ -89,7 +89,7 @@ You can add some middleware in your backend to handle cross-domain requests.## Customizing JWT authentication-You can customize how the SDK fetches the refresh token by specifying the `fetchRefreshToken` function with the `defineMetabaseAuthConfig` function:+You can customize how the SDK fetches the request token by specifying the `fetchRequestToken` function with the `defineMetabaseAuthConfig` function:```typescript{% include_file "{{ dirname }}/snippets/authentication/auth-config-jwt.tsx" snippet="example" %}diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.tsindex 4e428e16b21..935ac031f5a 100644--- a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts@@ -24,6 +24,7 @@ export interface BaseEmbedTestPageOptions {instanceUrl?: string;apiKey?: string;useExistingUserSession?: boolean;+ fetchRequestToken?: () => Promise<{ jwt: string }>;theme?: MetabaseTheme;preferredAuthMethod?: "jwt" | "saml";locale?: string;@@ -39,7 +40,7 @@ export interface BaseEmbedTestPageOptions {afterEmbed?: string;};- onVisitPage?(): void;+ onVisitPage?(win: Cypress.AUTWindow): void;}export interface MetabaseElement {@@ -267,14 +268,7 @@ export const getNewEmbedConfigurationScript = ({useExistingUserSession,preferredAuthMethod,locale,-}: {- instanceUrl?: string;- theme?: MetabaseTheme;- apiKey?: string;- useExistingUserSession?: boolean;- preferredAuthMethod?: "jwt" | "saml";- locale?: string;-} = {}) => {+}: BaseEmbedTestPageOptions["metabaseConfig"] = {}) => {const config = {instanceUrl,apiKey,diff --git a/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts b/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.tsindex da611f9199a..119062e3aa5 100644--- a/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts+++ b/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts@@ -11,6 +11,19 @@ import {} from "e2e/support/helpers";import { enableJwtAuth } from "e2e/support/helpers/e2e-jwt-helpers";+export const getSignedJwtForUser = async (user = USERS.admin) => {+ const secret = new TextEncoder().encode(JWT_SHARED_SECRET);++ return new jose.SignJWT({+ email: user.email,+ first_name: user.first_name,+ last_name: user.last_name,+ exp: Math.round(Date.now() / 1000) + 60 * 10, // 10 minutes expiration+ })+ .setProtectedHeader({ alg: "HS256" })+ .sign(secret);+};+export const mockAuthProviderAndJwtSignIn = (user = USERS.admin) => {cy.intercept("GET", `${AUTH_PROVIDER_URL}**`, async (req) => {try {@@ -26,15 +39,7 @@ export const mockAuthProviderAndJwtSignIn = (user = USERS.admin) => {return;}- const secret = new TextEncoder().encode(JWT_SHARED_SECRET);- const jwt = await new jose.SignJWT({- email: user.email,- first_name: user.first_name,- last_name: user.last_name,- exp: Math.round(Date.now() / 1000) + 60 * 10, // 10 minutes expiration- })- .setProtectedHeader({ alg: "HS256" })- .sign(secret);+ const jwt = await getSignedJwtForUser(user);req.reply({statusCode: 200,diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.tsindex 8f76dc43d40..154b4fc5ff7 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts@@ -1,5 +1,7 @@+import { USERS } from "e2e/support/cypress_data";import { ORDERS_DASHBOARD_ID } from "e2e/support/cypress_sample_instance_data";import {+ getSignedJwtForUser,mockAuthSsoEndpointForSamlAuthProvider,stubWindowOpenForSamlPopup,} from "e2e/support/helpers/embedding-sdk-testing";@@ -124,6 +126,62 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>assertDashboardLoaded(frame);});+ it("can login via JWT and a custom fetch request token function", () => {+ H.prepareSdkIframeEmbedTest({ enabledAuthMethods: ["jwt"], signOut: true });++ const frame = H.loadSdkIframeEmbedTestPage({+ onVisitPage: (win) => {+ (win as any).metabaseConfig = {+ ...(win as any).metabaseConfig,+ fetchRequestToken: async () => {+ const jwt = await getSignedJwtForUser(USERS.admin);++ return { jwt };+ },+ };+ },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],+ });++ assertDashboardLoaded(frame);+ });++ it("shows error message if login via JWT and a custom fetch request token is failing", () => {+ H.prepareSdkIframeEmbedTest({ enabledAuthMethods: ["jwt"], signOut: true });++ const frame = H.loadSdkIframeEmbedTestPage({+ onVisitPage: (win) => {+ (win as any).metabaseConfig = {+ ...(win as any).metabaseConfig,+ fetchRequestToken: async () => {+ return { jwt: "" };+ },+ };+ },+ elements: [+ {+ component: "metabase-dashboard",+ attributes: {+ dashboardId: ORDERS_DASHBOARD_ID,+ },+ },+ ],+ });++ frame.within(() => {+ cy.findByTestId("sdk-error-container")+ .findByText(/Failed to fetch JWT token/)+ .should("exist");+ });+ });+it("can login via SAML", () => {mockAuthSsoEndpointForSamlAuthProvider();H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: true });diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/constants.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/constants.tsindex 2fa78ef4f58..a0a06bdd891 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/constants.ts@@ -22,6 +22,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {"theme","locale","preferredAuthMethod",+ "fetchRequestToken","useExistingUserSession",] satisfies (keyof SdkIframeEmbedBaseSettings)[],dashboard: [@@ -78,4 +79,5 @@ export type AllowedEmbedSettingKey =export const DISABLE_UPDATE_FOR_KEYS = ["instanceUrl","useExistingUserSession",+ "fetchRequestToken",] as const satisfies AllowedEmbedSettingKey[];diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.tsindex 08462fd5f46..6de34378bdd 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts@@ -412,7 +412,24 @@ export abstract class MetabaseEmbedElement extends HTMLElement {data: Message["data"],) {if (this._iframe?.contentWindow) {- this._iframe.contentWindow.postMessage({ type, data }, "*");+ const normalizedData = Object.entries(data).reduce(+ (acc, [key, value]) => {+ // Functions are not serializable, so we ignore them.+ if (typeof value === "function") {+ return acc;+ }++ acc[key as keyof typeof acc] = value;++ return acc;+ },+ {} as Message["data"],+ );++ this._iframe.contentWindow.postMessage(+ { type, data: normalizedData },+ "*",+ );}}@@ -446,7 +463,8 @@ export abstract class MetabaseEmbedElement extends HTMLElement {* @returns {{ method: "saml" | "jwt", sessionToken: {jwt: string} }}*/private async _getMetabaseSessionToken() {- const { instanceUrl, preferredAuthMethod } = this.properties;+ const { instanceUrl, preferredAuthMethod, fetchRequestToken } =+ this.properties;const urlResponseJson = await connectToInstanceAuthSso(instanceUrl, {headers: this._getAuthRequestHeader(),@@ -466,6 +484,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {responseUrl,instanceUrl,this._getAuthRequestHeader(hash),+ fetchRequestToken,);return { method, sessionToken };diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.tsindex 4df1593067b..1e6cc656382 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/types/embed.ts@@ -1,7 +1,10 @@import type { MetabaseError } from "embedding-sdk-bundle/errors";import type { MetabaseErrorCode } from "embedding-sdk-bundle/errors/error-code";import type { MetabaseAuthMethod } from "embedding-sdk-bundle/types";-import type { MetabaseEmbeddingSessionToken } from "embedding-sdk-bundle/types/refresh-token";+import type {+ MetabaseEmbeddingSessionToken,+ MetabaseFetchRequestTokenFn,+} from "embedding-sdk-bundle/types/refresh-token";import type {CollectionBrowserListColumns,EmbeddingEntityType,@@ -140,6 +143,7 @@ export type SdkIframeEmbedBaseSettings = {theme?: MetabaseTheme;locale?: string;preferredAuthMethod?: MetabaseAuthMethod;+ fetchRequestToken?: MetabaseFetchRequestTokenFn;/** Whether we should use the existing user session (i.e. admin user's cookie) */useExistingUserSession?: boolean;@@ -155,7 +159,10 @@ export type SdkIframeEmbedTemplateSettings =| BrowserEmbedOptions;/** Settings used by the sdk embed route */-export type SdkIframeEmbedSettings = SdkIframeEmbedBaseSettings &+export type SdkIframeEmbedSettings = Omit<+ SdkIframeEmbedBaseSettings,+ "fetchRequestToken"+> &SdkIframeEmbedTemplateSettings;export type SdkIframeEmbedElementSettings = SdkIframeEmbedBaseSettings &