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
Check embedding saml popup source (#80494)
Phoomparin Mano485241325825
diff --git a/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts b/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.tsindex bd6f1b4910b..63db2110465 100644--- a/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts+++ b/e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers.ts@@ -135,12 +135,8 @@ export function stubWindowOpenForSamlPopup({isUserValid?: boolean;} = {}) {cy.window().then((win) => {- const popup = {- closed: false,- close: () => {- popup.closed = true;- },- };+ const popup = win;+ cy.stub(popup, "close");// stub `window.open(IDP_URI, ...)` for the SAML popupcy.stub(win, "open")@@ -162,10 +158,10 @@ export function stubWindowOpenForSamlPopup({exp: Math.floor(Date.now() / 1000) + 600, // 10 minutes},},- origin: "*",+ origin: win.location.origin,+ source: popup,}),);- popup.close();}, 100); // simulate async delayreturn popup;diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.cljindex c2272dbae54..ed1946f764f 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj@@ -123,7 +123,8 @@(if embedding?{:status 200:body {:url (:redirect-url auth-result)- :method "saml"}+ :method "saml"+ :saml-popup-url (acs-url)}:headers {"Content-Type" "application/json"}}(response/redirect (:redirect-url auth-result))))diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.cljindex 0ba2d35036e..73c049f46f8 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj@@ -844,6 +844,8 @@:body {:method "saml"}:headers {"Content-Type" "application/json"}}result))+ (is (= (str (system/site-url) "/auth/sso")+ (get-in result [:body :saml-popup-url])))(is (str/starts-with? (-> result :body :url) default-idp-uri)))))))(deftest saml-embedding-sdk-integration-includes-origin-testsdiff --git a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.tsindex 5033405c8b8..58e14f92f0c 100644--- a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts+++ b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts@@ -277,12 +277,23 @@ const getRefreshToken = async ({headers: getSdkRequestHeaders(),});- const { method, url: responseUrl, hash } = urlResponseJson || {};+ const {+ method,+ url: responseUrl,+ hash,+ "saml-popup-url": samlPopupUrl,+ } = urlResponseJson || {};+if (method === "saml") {- const token = await openSamlLoginPopup(responseUrl);- samlTokenStorage.set(token);+ const sessionToken = await openSamlLoginPopup(+ responseUrl,+ metabaseInstanceUrl,+ samlPopupUrl,+ );++ samlTokenStorage.set(sessionToken);- return token;+ return sessionToken;}if (method === "jwt" && responseUrl) {return jwtDefaultRefreshTokenFunction(diff --git a/enterprise/frontend/src/embedding/auth-common/saml.ts b/enterprise/frontend/src/embedding/auth-common/saml.tsindex 74d61b2171b..93362613262 100644--- a/enterprise/frontend/src/embedding/auth-common/saml.ts+++ b/enterprise/frontend/src/embedding/auth-common/saml.ts@@ -17,8 +17,17 @@ import type { MetabaseEmbeddingSessionToken } from "metabase/embedding-sdk/types* */export const openSamlLoginPopup = async (idpUrl: string,+ instanceUrl: string,+ popupUrl = instanceUrl,): Promise<MetabaseEmbeddingSessionToken> => {return new Promise((resolve, reject) => {+ const expectedOrigin = new URL(instanceUrl).origin;++ if (new URL(popupUrl).origin !== expectedOrigin) {+ reject(MetabaseError.SAML_SITE_URL_MISMATCH());+ return;+ }+const width = 600;const height = 700;const left = window.screenX + (window.outerWidth - width) / 2;@@ -40,13 +49,21 @@ export const openSamlLoginPopup = async (authData: MetabaseEmbeddingSessionToken;}>,) => {- if (event.data && event.data.type === "SAML_AUTH_COMPLETE") {- window.removeEventListener("message", messageHandler);- if (!popup.closed) {- popup.close();- }- resolve(event.data.authData);+ if (event.source !== popup || event.data?.type !== "SAML_AUTH_COMPLETE") {+ return;+ }++ if (event.origin !== expectedOrigin) {+ return;}++ window.removeEventListener("message", messageHandler);++ if (!popup.closed) {+ popup.close();+ }++ resolve(event.data.authData);};window.addEventListener("message", messageHandler);@@ -56,6 +73,7 @@ export const openSamlLoginPopup = async (if (popup.closed) {clearInterval(checkClosed);window.removeEventListener("message", messageHandler);+reject(MetabaseError.SAML_POPUP_CLOSED());}}, 1000);diff --git a/enterprise/frontend/src/embedding/auth-common/saml.unit.spec.ts b/enterprise/frontend/src/embedding/auth-common/saml.unit.spec.tsnew file mode 100644index 00000000000..6928800bb7c--- /dev/null+++ b/enterprise/frontend/src/embedding/auth-common/saml.unit.spec.ts@@ -0,0 +1,103 @@+import { openSamlLoginPopup } from "./saml";++const instanceUrl = "https://metabase.example.com";+const idpUrl = "https://idp.example.com/login";+const mismatchedPopupUrl = "https://saml.metabase.example.com/auth/sso";++const authData = { id: "session-id", iat: 0, exp: 0 };++describe("openSamlLoginPopup", () => {+ const popup = { closed: false, close: jest.fn() };++ // The mock is used as the browser popup.+ const popupWindow = popup as unknown as Window;++ beforeEach(() => {+ jest.useFakeTimers();+ jest.clearAllMocks();++ popup.closed = false;++ jest.spyOn(window, "open").mockReturnValue(popupWindow);+ });++ afterEach(() => {+ jest.clearAllTimers();+ jest.useRealTimers();+ jest.restoreAllMocks();+ });++ it("completes the saml popup when origin and source matches", async () => {+ const login = openSamlLoginPopup(idpUrl, instanceUrl);++ let completed = false;++ login.then(() => {+ completed = true;+ });++ window.dispatchEvent(+ new MessageEvent("message", {+ data: { type: "SAML_AUTH_COMPLETE", authData },+ origin: "https://other.example.com",+ source: popupWindow,+ }),+ );++ await Promise.resolve();+ expect(completed).toBe(false);+ expect(popup.close).not.toHaveBeenCalled();++ window.dispatchEvent(+ new MessageEvent("message", {+ data: { type: "SAML_AUTH_COMPLETE", authData },+ origin: instanceUrl,+ source: window,+ }),+ );++ await Promise.resolve();+ expect(completed).toBe(false);+ expect(popup.close).not.toHaveBeenCalled();++ window.dispatchEvent(+ new MessageEvent("message", {+ data: { type: "SAML_AUTH_COMPLETE", authData },+ origin: instanceUrl,+ source: popupWindow,+ }),+ );++ await expect(login).resolves.toEqual(authData);+ expect(popup.close).toHaveBeenCalledTimes(1);+ });++ it("ignores message events from a different origin", async () => {+ const login = openSamlLoginPopup(idpUrl, instanceUrl);++ window.dispatchEvent(+ new MessageEvent("message", {+ data: { type: "SAML_AUTH_COMPLETE", authData },+ origin: "https://other.example.com",+ source: popupWindow,+ }),+ );++ popup.closed = true;+ jest.advanceTimersByTime(1000);++ await expect(login).rejects.toMatchObject({+ code: "SAML_POPUP_CLOSED",+ });+ });++ it("reports a Site URL origin mismatch before opening the popup", async () => {+ await expect(+ openSamlLoginPopup(idpUrl, instanceUrl, mismatchedPopupUrl),+ ).rejects.toMatchObject({+ code: "SAML_SITE_URL_MISMATCH",+ });++ expect(window.open).not.toHaveBeenCalled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/auth-manager/AuthManager.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/auth-manager/AuthManager.tsindex 54b92bcf26b..0c19d8c5564 100644--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/auth-manager/AuthManager.ts+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/auth-manager/AuthManager.ts@@ -53,7 +53,7 @@ export class EmbedAuthManager {sessionToken: MetabaseEmbeddingSessionToken;}> {const {- instanceUrl,+ instanceUrl: metabaseInstanceUrl,preferredAuthMethod,fetchRequestToken,jwtProviderUri,@@ -63,15 +63,24 @@ export class EmbedAuthManager {const urlResponseJson = shouldSkipSsoDiscovery? { method: "jwt", url: jwtProviderUri }- : await connectToInstanceAuthSso(instanceUrl, {+ : await connectToInstanceAuthSso(metabaseInstanceUrl, {headers: this.getAuthRequestHeader(),preferredAuthMethod,});- const { method, url: responseUrl, hash } = urlResponseJson || {};+ const {+ method,+ url: responseUrl,+ hash,+ "saml-popup-url": samlPopupUrl,+ } = urlResponseJson || {};if (method === "saml") {- const sessionToken = await openSamlLoginPopup(responseUrl);+ const sessionToken = await openSamlLoginPopup(+ responseUrl,+ metabaseInstanceUrl,+ samlPopupUrl,+ );return { method, sessionToken };}@@ -79,7 +88,7 @@ export class EmbedAuthManager {if (method === "jwt" && responseUrl) {const sessionToken = await jwtDefaultRefreshTokenFunction(responseUrl,- instanceUrl,+ metabaseInstanceUrl,this.getAuthRequestHeader(hash),fetchRequestToken,);diff --git a/frontend/src/embedding-sdk-bundle/test/mocks/sso.ts b/frontend/src/embedding-sdk-bundle/test/mocks/sso.tsindex 8017fdb8da7..87604cc8775 100644--- a/frontend/src/embedding-sdk-bundle/test/mocks/sso.ts+++ b/frontend/src/embedding-sdk-bundle/test/mocks/sso.ts@@ -78,6 +78,7 @@ export const setupMockSamlEndpoints = ({return {url: providerUri,method: "saml",+ "saml-popup-url": instanceUrl,};});@@ -117,15 +118,12 @@ export const setupMockSamlEndpoints = ({* Returns the mocked popup object so you can verify it was closed, etc.*/export const setupSamlPopup = () => {- const popupMock = {- closed: false,- close: jest.fn(),- };+ const popupMock = { closed: false, close: jest.fn() };++ // The mock is used as the browser popup.+ const popupWindow = popupMock as unknown as Window;- jest- .spyOn(window, "open")- // Unjustified type cast. FIXME- .mockImplementation(() => popupMock as unknown as Window);+ jest.spyOn(window, "open").mockImplementation(() => popupWindow);// Wait until the next tick to simulate popup messageprocess.nextTick(() => {@@ -137,6 +135,8 @@ export const setupSamlPopup = () => {type: "SAML_AUTH_COMPLETE",authData,},+ origin: MOCK_INSTANCE_URL,+ source: popupWindow,}),);});diff --git a/frontend/src/embedding-sdk-shared/errors/error-code.ts b/frontend/src/embedding-sdk-shared/errors/error-code.tsindex da37ec171f4..3101328d457 100644--- a/frontend/src/embedding-sdk-shared/errors/error-code.ts+++ b/frontend/src/embedding-sdk-shared/errors/error-code.ts@@ -9,6 +9,7 @@ export type MetabaseErrorCode =| "CANNOT_FETCH_JWT_TOKEN"| "SAML_POPUP_BLOCKED"| "SAML_POPUP_CLOSED"+ | "SAML_SITE_URL_MISMATCH"| "SAML_TIMEOUT"| "USER_FETCH_FAILED"| "CANNOT_CONNECT_TO_INSTANCE"diff --git a/frontend/src/embedding-sdk-shared/errors/saml.ts b/frontend/src/embedding-sdk-shared/errors/saml.tsindex f6fad608ec9..8ec3e4e7ac7 100644--- a/frontend/src/embedding-sdk-shared/errors/saml.ts+++ b/frontend/src/embedding-sdk-shared/errors/saml.ts@@ -10,7 +10,14 @@ export function SAML_POPUP_BLOCKED() {export function SAML_POPUP_CLOSED() {return new MetabaseError("SAML_POPUP_CLOSED",- "Authentication was canceled by the user (popup closed).",+ "Authentication did not complete before the popup was closed.",+ );+}++export function SAML_SITE_URL_MISMATCH() {+ return new MetabaseError(+ "SAML_SITE_URL_MISMATCH",+ "SAML authentication requires metabaseInstanceUrl to use the same origin as the configured Site URL.",);}