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
fix(sdk): Allow token without`exp`, but raise a warning (#64238)
Mahatthana (Kelvin) Nomsawadi02cec9f38d24
diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemBanner.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemBanner.tsxindex c6d6f7cb116..e9ddd605ee7 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemBanner.tsx+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemBanner.tsx@@ -109,7 +109,9 @@ export const SdkUsageProblemBanner = ({<ExternalLink role="link" href={problem.documentationUrl}><Buttonfz="sm"- rightSection={<Icon name="external" size="1rem" />}+ rightSection={+ <Icon aria-hidden name="external" size="1rem" />+ }ff={fontFamily}className={S.DocsButton}size="md"diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay-simple-embedding.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay-simple-embedding.unit.spec.tsxindex 15ed1c00928..d47e0f6e517 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay-simple-embedding.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay-simple-embedding.unit.spec.tsx@@ -8,7 +8,10 @@ import { mockSettings } from "__support__/settings";import { screen, within } from "__support__/ui";import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";-import { createMockSdkState } from "embedding-sdk-bundle/test/mocks/state";+import {+ createMockSdkState,+ createMockTokenState,+} from "embedding-sdk-bundle/test/mocks/state";import {createMockSettings,createMockTokenFeatures,@@ -55,10 +58,18 @@ const setup = (options: Options) => {"enable-embedding-simple": options.isSimpleEmbeddingEnabled ?? true,});+ const MINUTE = 60;const state = createMockState({settings: mockSettings(settingValues),currentUser: TEST_USER,- sdk: createMockSdkState(),+ sdk: createMockSdkState({+ token: createMockTokenState({+ token: {+ id: "123",+ exp: Math.round(Date.now() / 1000) + 10 * MINUTE,+ },+ }),+ }),});setupSettingsEndpoints([]);diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay.unit.spec.tsxindex 77d4c6ba9af..ac5895a2105 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/SdkUsageProblemDisplay.unit.spec.tsx@@ -13,7 +13,10 @@ import {createMockApiKeyConfig,createMockSdkConfig,} from "embedding-sdk-bundle/test/mocks/config";-import { createMockSdkState } from "embedding-sdk-bundle/test/mocks/state";+import {+ createMockSdkState,+ createMockTokenState,+} from "embedding-sdk-bundle/test/mocks/state";import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types";import {createMockSettings,@@ -37,9 +40,10 @@ interface Options {hasEmbeddingFeature?: boolean;isEmbeddingSdkEnabled?: boolean;isDevelopmentMode?: boolean;+ hasExpirationClaim?: boolean;}-const setup = (options: Options) => {+const setup = ({ hasExpirationClaim = true, ...options }: Options) => {const tokenFeatures = createMockTokenFeatures({embedding_sdk: options.hasEmbeddingFeature ?? true,development_mode: options.isDevelopmentMode ?? false,@@ -50,10 +54,20 @@ const setup = (options: Options) => {"enable-embedding-sdk": options.isEmbeddingSdkEnabled ?? true,});+ const MINUTE = 60;const state = createMockState({settings: mockSettings(settingValues),currentUser: TEST_USER,- sdk: createMockSdkState(),+ sdk: createMockSdkState({+ token: createMockTokenState({+ token: {+ id: "123",+ exp: hasExpirationClaim+ ? Math.round(Date.now() / 1000) + 10 * MINUTE+ : null,+ },+ }),+ }),});setupSettingsEndpoints([]);@@ -98,7 +112,7 @@ describe("SdkUsageProblemDisplay", () => {).toBeInTheDocument();const docsLink = within(card).getByRole("link", {- name: /Documentation/,+ name: "Documentation",});expect(docsLink).toHaveAttribute(@@ -127,12 +141,12 @@ describe("SdkUsageProblemDisplay", () => {).toBeInTheDocument();const docsLink = within(card).getByRole("link", {- name: /Documentation/,+ name: "Documentation",});expect(docsLink).toHaveAttribute("href",- "https://www.metabase.com/docs/latest/embedding/sdk/authentication#authenticating-people-from-your-server",+ "https://www.metabase.com/docs/latest/embedding/sdk/authentication#2-add-a-new-endpoint-to-your-backend-to-handle-authentication",);});@@ -180,7 +194,7 @@ describe("SdkUsageProblemDisplay", () => {).toBeInTheDocument();const docsLink = within(card).getByRole("link", {- name: /Documentation/,+ name: "Documentation",});expect(docsLink).toHaveAttribute(@@ -211,7 +225,7 @@ describe("SdkUsageProblemDisplay", () => {).toBeInTheDocument();const docsLink = within(card).getByRole("link", {- name: /Documentation/,+ name: "Documentation",});expect(docsLink).toHaveAttribute(@@ -220,6 +234,38 @@ describe("SdkUsageProblemDisplay", () => {);});+ it('should show a warning when JWT token does not contain the "exp" claim', async () => {+ setup({+ authConfig: createMockSdkConfig(),+ isEmbeddingSdkEnabled: true,+ isDevelopmentMode: false,+ hasExpirationClaim: false,+ });++ await userEvent.click(screen.getByTestId(PROBLEM_INDICATOR_TEST_ID));++ const card = screen.getByTestId(PROBLEM_CARD_TEST_ID);++ expect(+ within(card).getByText("This embed is powered by the Metabase SDK."),+ ).toBeInTheDocument();++ expect(+ within(card).getByText(+ `The JWT token is missing the "exp" (expiration) claim. We will disallow tokens without "exp" in a future release. Please add "exp" to the token payload.`,+ ),+ ).toBeInTheDocument();++ const docsLink = within(card).getByRole("link", {+ name: "Documentation",+ });++ expect(docsLink).toHaveAttribute(+ "href",+ "https://www.metabase.com/docs/latest/embedding/sdk/authentication#2-add-a-new-endpoint-to-your-backend-to-handle-authentication",+ );+ });+it("hides the problem when 'hide' is clicked", async () => {setup({authConfig: createMockSdkConfig(),diff --git a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/index.tsx b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/index.tsxindex 5acde019ee7..28565b7f1a8 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/index.tsx+++ b/enterprise/frontend/src/embedding-sdk-bundle/components/private/SdkUsageProblem/index.tsx@@ -1,4 +1,6 @@import { useSdkUsageProblem } from "embedding-sdk-bundle/hooks/private/use-sdk-usage-problem";+import { getSessionTokenState } from "embedding-sdk-bundle/store/selectors";+import { useSdkSelector } from "embedding-sdk-bundle/store/use-sdk-selector";import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types";import { EMBEDDING_SDK_PORTAL_ROOT_ELEMENT_ID } from "metabase/embedding-sdk/config";import { Box, Portal } from "metabase/ui";@@ -15,7 +17,13 @@ export const SdkUsageProblemDisplay = ({authConfig,allowConsoleLog,}: Props) => {- const usageProblem = useSdkUsageProblem({ authConfig, allowConsoleLog });+ const session = useSdkSelector((state) => getSessionTokenState(state).token);++ const usageProblem = useSdkUsageProblem({+ authConfig,+ allowConsoleLog,+ session,+ });if (!usageProblem) {return null;diff --git a/enterprise/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-usage-problem.ts b/enterprise/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-usage-problem.tsindex d7c680f834f..0d44c371c79 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-usage-problem.ts+++ b/enterprise/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-usage-problem.ts@@ -5,6 +5,7 @@ import { getSdkUsageProblem } from "embedding-sdk-bundle/lib/usage-problem";import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";import { setUsageProblem } from "embedding-sdk-bundle/store/reducer";import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";+import type { MetabaseEmbeddingSessionToken } from "embedding-sdk-package";import { useSetting } from "metabase/common/hooks";import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";import { getTokenFeature } from "metabase/setup/selectors";@@ -12,9 +13,11 @@ import { getTokenFeature } from "metabase/setup/selectors";export function useSdkUsageProblem({authConfig,allowConsoleLog = true,+ session,}: {authConfig: MetabaseAuthConfig;allowConsoleLog?: boolean;+ session: MetabaseEmbeddingSessionToken | null;}) {const hasLoggedRef = useRef(false);@@ -51,8 +54,9 @@ export function useSdkUsageProblem({hasTokenFeature,isEnabled,isDevelopmentMode,+ session,});- }, [authConfig, hasTokenFeature, isEnabled, isDevelopmentMode]);+ }, [authConfig, hasTokenFeature, isEnabled, isDevelopmentMode, session]);useEffect(() => {// SDK components will stop rendering if a license error is detected.diff --git a/enterprise/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts b/enterprise/frontend/src/embedding-sdk-bundle/lib/usage-problem.tsindex 6edf1e35941..d4011a7ea8b 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts+++ b/enterprise/frontend/src/embedding-sdk-bundle/lib/usage-problem.ts@@ -1,10 +1,11 @@-import { match } from "ts-pattern";+import { P, match } from "ts-pattern";import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types";import type {SdkUsageProblem,SdkUsageProblemKey,} from "embedding-sdk-bundle/types/usage-problem";+import type { MetabaseEmbeddingSessionToken } from "embedding-sdk-package";import { EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG } from "metabase/embedding-sdk/config";import { getIsLocalhost } from "./is-localhost";@@ -14,6 +15,7 @@ interface SdkProblemOptions {isEnabled: boolean;hasTokenFeature: boolean;isDevelopmentMode?: boolean;+ session: MetabaseEmbeddingSessionToken | null;}export const USAGE_PROBLEM_MESSAGES = {@@ -26,11 +28,12 @@ export const USAGE_PROBLEM_MESSAGES = {// eslint-disable-next-line no-literal-metabase-strings -- only shown in development.DEVELOPMENT_MODE_CLOUD_INSTANCE: `This Metabase is in development mode intended exclusively for testing. Using this Metabase for everyday BI work or when embedding in production is considered unfair usage.`,+ JWT_EXP_NULL: `The JWT token is missing the "exp" (expiration) claim. We will disallow tokens without "exp" in a future release. Please add "exp" to the token payload.`,} as const;export const SDK_AUTH_DOCS_URL =// eslint-disable-next-line no-unconditional-metabase-links-render -- these links are used in the SDK banner which is only shown to developers- "https://www.metabase.com/docs/latest/embedding/sdk/authentication#authenticating-people-from-your-server";+ "https://www.metabase.com/docs/latest/embedding/sdk/authentication#2-add-a-new-endpoint-to-your-backend-to-handle-authentication";export const METABASE_UPGRADE_URL = "https://www.metabase.com/upgrade";@@ -45,6 +48,7 @@ export const USAGE_PROBLEM_DOC_URLS: Record<SdkUsageProblemKey, string> = {SSO_WITHOUT_LICENSE: METABASE_UPGRADE_URL,EMBEDDING_SDK_NOT_ENABLED: SDK_INTRODUCTION_DOCS_URL,DEVELOPMENT_MODE_CLOUD_INSTANCE: METABASE_UPGRADE_URL,+ JWT_EXP_NULL: SDK_AUTH_DOCS_URL,} as const;/**@@ -54,7 +58,8 @@ export const USAGE_PROBLEM_DOC_URLS: Record<SdkUsageProblemKey, string> = {export function getSdkUsageProblem(options: SdkProblemOptions,): SdkUsageProblem | null {- const { isEnabled, hasTokenFeature, authConfig, isDevelopmentMode } = options;+ const { isEnabled, hasTokenFeature, authConfig, isDevelopmentMode, session } =+ options;const { apiKey } = authConfig;const isSSO = !apiKey;@@ -77,6 +82,7 @@ export function getSdkUsageProblem(isLocalhost,isEnabled,isDevelopmentMode,+ session,}).with({ isDevelopmentMode: true }, () =>toWarning("DEVELOPMENT_MODE_CLOUD_INSTANCE"),@@ -105,6 +111,7 @@ export function getSdkUsageProblem(.with({ isApiKey: true, hasTokenFeature: true }, () =>toError("API_KEYS_WITH_LICENSE"),)+ .with({ session: { exp: P.nullish } }, () => toWarning("JWT_EXP_NULL")).otherwise(() => null));}diff --git a/enterprise/frontend/src/embedding-sdk-bundle/store/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-bundle/store/auth/auth.tsindex 50cdfb1b3a6..68be7f61eb0 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/store/auth/auth.ts+++ b/enterprise/frontend/src/embedding-sdk-bundle/store/auth/auth.ts@@ -4,7 +4,7 @@ import {jwtDefaultRefreshTokenFunction,openSamlLoginPopup,samlTokenStorage,- validateSessionToken,+ validateSession,} from "embedding/auth-common";import * as MetabaseError from "embedding-sdk-bundle/errors";import { getIsLocalhost } from "embedding-sdk-bundle/lib/is-localhost";@@ -114,7 +114,7 @@ export const refreshTokenAsync = createAsyncThunk(preferredAuthMethod,fetchRequestToken: customGetRefreshToken,});- validateSessionToken(session);+ validateSession(session);return session;},diff --git a/enterprise/frontend/src/embedding-sdk-bundle/store/reducer.ts b/enterprise/frontend/src/embedding-sdk-bundle/store/reducer.tsindex cb4563bb52e..41aadbc901d 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/store/reducer.ts+++ b/enterprise/frontend/src/embedding-sdk-bundle/store/reducer.ts@@ -59,12 +59,18 @@ export const getOrRefreshSession = createAsyncThunk(// refreshes the pageconst storedAuthToken = samlTokenStorage.get();const state = getSessionTokenState(getState() as SdkStoreState);- const token = storedAuthToken ?? state?.token;-- const isTokenValid = token && token.exp * 1000 >= Date.now();-- if (isTokenValid) {- return token;+ /**+ * @see {@link https://github.com/metabase/metabase/pull/64238#discussion_r2394229266}+ *+ * TODO: I think this should be called session overall e.g. state.session+ */+ const session = storedAuthToken ?? state?.token;++ const shouldRefreshToken =+ !session ||+ (typeof session?.exp === "number" && session.exp * 1000 < Date.now());+ if (!shouldRefreshToken) {+ return session;}if (refreshTokenPromise) {diff --git a/enterprise/frontend/src/embedding-sdk-bundle/test/auth-flow/jwt.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-bundle/test/auth-flow/jwt.unit.spec.tsxindex 80a6aa837a1..4c95b6fd094 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/test/auth-flow/jwt.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-bundle/test/auth-flow/jwt.unit.spec.tsx@@ -125,6 +125,24 @@ describe("Auth Flow - JWT", () => {);});+ it('should not render usage problem popover saying JWT is missing "exp" claim when then token is being fetched', async () => {+ const customFetchFunction = jest.fn().mockImplementation(() => ({+ jwt: MOCK_VALID_JWT_RESPONSE,+ }));++ const authConfig = defineMetabaseAuthConfig({+ metabaseInstanceUrl: MOCK_INSTANCE_URL,+ preferredAuthMethod: "jwt",+ fetchRequestToken: customFetchFunction,+ });++ setup({ authConfig });++ expect(+ screen.queryByTestId("sdk-usage-problem-indicator"),+ ).not.toBeInTheDocument();+ });+it("should include the subpath when requesting the SSO endpoint", async () => {// we can't use the usual mocks here as they use mocks that don't expect the subpathconst instanceUrlWithSubpath = `${MOCK_INSTANCE_URL}/subpath`;diff --git a/enterprise/frontend/src/embedding-sdk-bundle/test/mocks/state.ts b/enterprise/frontend/src/embedding-sdk-bundle/test/mocks/state.tsindex ad6f7a107d1..8ec0a7ba391 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/test/mocks/state.ts+++ b/enterprise/frontend/src/embedding-sdk-bundle/test/mocks/state.ts@@ -6,7 +6,7 @@ import type { LoginStatus } from "embedding-sdk-bundle/types/user";export const createMockTokenState = ({...opts-}: Partial<LoginStatus> = {}): EmbeddingSessionTokenState => {+}: Partial<EmbeddingSessionTokenState> = {}): EmbeddingSessionTokenState => {return { error: null, loading: false, token: null, ...opts };};diff --git a/enterprise/frontend/src/embedding-sdk-bundle/types/refresh-token.ts b/enterprise/frontend/src/embedding-sdk-bundle/types/refresh-token.tsindex bceee506951..3c5191fb23c 100644--- a/enterprise/frontend/src/embedding-sdk-bundle/types/refresh-token.ts+++ b/enterprise/frontend/src/embedding-sdk-bundle/types/refresh-token.ts@@ -1,6 +1,10 @@export type MetabaseEmbeddingSessionToken = {id: string;- exp: number;+ /**+ * (EMB-829) This is a temporary type. After we disallowed token without expiration,+ * we will remove make it a non-optional number again.+ */+ exp?: number | null;};/**diff --git a/enterprise/frontend/src/embedding/auth-common/index.ts b/enterprise/frontend/src/embedding/auth-common/index.tsindex 23d8805d24f..9740c31db44 100644--- a/enterprise/frontend/src/embedding/auth-common/index.ts+++ b/enterprise/frontend/src/embedding/auth-common/index.ts@@ -1,5 +1,5 @@export { connectToInstanceAuthSso } from "./connect-to-instance-auth-sso";export { jwtDefaultRefreshTokenFunction } from "./jwt";export { openSamlLoginPopup } from "./saml";-export { validateSessionToken } from "./validate-session-token";+export { validateSession } from "./validate-session-token";export { samlTokenStorage } from "./saml-token-storage";diff --git a/enterprise/frontend/src/embedding/auth-common/validate-session-token.ts b/enterprise/frontend/src/embedding/auth-common/validate-session-token.tsindex abd4de86ab9..a0657de1bc9 100644--- a/enterprise/frontend/src/embedding/auth-common/validate-session-token.ts+++ b/enterprise/frontend/src/embedding/auth-common/validate-session-token.ts@@ -1,6 +1,6 @@import * as MetabaseError from "embedding-sdk-bundle/errors";-export function validateSessionToken(session: any) {+export function validateSession(session: any) {if (!session || typeof session !== "object") {throw MetabaseError.INVALID_SESSION_OBJECT({expected: "{ jwt: string }",@@ -26,7 +26,12 @@ export function validateSessionToken(session: any) {// We should also receive `iat` and `status` in the response, but we don't actually need them// as we don't use them, so we don't throw an error if they are missing- if (typeof session.id !== "string" || typeof session.exp !== "number") {++ /**+ * (EMB-829) Temporarily allow `exp` to be null or undefined while we're deprecating token without it+ * after we disallow token without expiration, we will re-add this check.+ */+ if (typeof session.id !== "string") {throw MetabaseError.INVALID_SESSION_SCHEMA({expected: "{ id: string, exp: number, iat: number }",actual: JSON.stringify(session, null, 2),diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.tsindex baf00dbf750..01d30899044 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts@@ -2,7 +2,7 @@ import {connectToInstanceAuthSso,jwtDefaultRefreshTokenFunction,openSamlLoginPopup,- validateSessionToken,+ validateSession,} from "embedding/auth-common";import {INVALID_AUTH_METHOD,@@ -450,7 +450,7 @@ export abstract class MetabaseEmbedElement extends HTMLElement {try {const { method, sessionToken } = await this._getMetabaseSessionToken();- validateSessionToken(sessionToken);+ validateSession(sessionToken);if (sessionToken) {this.sendMessage("metabase.embed.submitSessionToken", {