Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Consolidate modular embedding auth and token e2e specs (#84061)

Chris Vandoodewaard64b2167ae9cb
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.ts
index ab004897c11..23eee6b2b31 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
@@ -8,6 +8,11 @@ import {
const { H } = cy;
+const ORDERS_DASHBOARD_ELEMENT = {
+ component: "metabase-dashboard",
+ attributes: { dashboardId: ORDERS_DASHBOARD_ID },
+} as const;
+
describe("scenarios > embedding > sdk iframe embedding > authentication", () => {
describe("jwtProviderUri", () => {
beforeEach(() => {
@@ -25,7 +30,8 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
);
});
- it("should not skip the first auth request if jwtProviderUri is not given", () => {
+ it("skips the first auth request only if jwtProviderUri is given", () => {
+ cy.log("jwtProviderUri is given");
H.visitCustomHtmlPage(`
<!DOCTYPE html>
<html>
@@ -39,6 +45,7 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
<script>
defineMetabaseConfig({
"instanceUrl": "http://localhost:4000",
+ "jwtProviderUri": "http://auth-provider/sso?response=json",
});
</script>
<metabase-dashboard dashboard-id='${ORDERS_DASHBOARD_ID}' />
@@ -46,19 +53,19 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
</html>
`);
- cy.wait("@sso");
cy.wait("@ssoProvider");
cy.wait("@tokenInSessionOut");
+ cy.get("@sso.all").should("have.length", 0);
+
cy.wait("@getDashboard");
H.getSimpleEmbedIframeContent().should(
"contain",
"Orders in a dashboard",
);
- });
- it("should skip the first auth request if jwtProviderUri is given", () => {
+ cy.log("jwtProviderUri is not given");
H.visitCustomHtmlPage(`
<!DOCTYPE html>
<html>
@@ -72,7 +79,6 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
<script>
defineMetabaseConfig({
"instanceUrl": "http://localhost:4000",
- "jwtProviderUri": "http://auth-provider/sso?response=json",
});
</script>
<metabase-dashboard dashboard-id='${ORDERS_DASHBOARD_ID}' />
@@ -80,11 +86,10 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
</html>
`);
+ cy.wait("@sso");
cy.wait("@ssoProvider");
cy.wait("@tokenInSessionOut");
- cy.get("@sso.all").should("have.length", 0);
-
cy.wait("@getDashboard");
H.getSimpleEmbedIframeContent().should(
@@ -94,62 +99,23 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
});
});
- it("cannot login if no auth methods are enabled", () => {
+ it("shows auth errors when no auth methods are enabled and there is no session", () => {
H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: true });
- const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
- });
-
- frame.within(() => {
+ cy.log("no auth method is available");
+ H.loadSdkIframeEmbedTestPage({
+ elements: [ORDERS_DASHBOARD_ELEMENT],
+ }).within(() => {
cy.findByTestId("sdk-error-container")
.should("be.visible")
.and("contain", "SSO has not been enabled and/or configured");
});
- });
-
- it("can use existing user session when useExistingUserSession is true", () => {
- H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: false });
-
- const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
- metabaseConfig: {
- useExistingUserSession: true,
- },
- });
-
- assertDashboardLoaded(frame);
- });
-
- it("cannot use existing user session when there is no session", () => {
- H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: true });
-
- const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: { dashboardId: ORDERS_DASHBOARD_ID },
- },
- ],
+ cy.log("useExistingUserSession is true but there is no session");
+ H.loadSdkIframeEmbedTestPage({
+ elements: [ORDERS_DASHBOARD_ELEMENT],
metabaseConfig: { useExistingUserSession: true },
- });
-
- frame.within(() => {
+ }).within(() => {
cy.findByTestId("sdk-error-container")
.findByText(
"Failed to authenticate using an existing Metabase user session.",
@@ -162,88 +128,82 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
"include",
"https://www.metabase.com/docs/latest/embedding/authentication#configure-session-cookies-when-testing-locally",
);
-
- cy.findByTestId("sdk-error-container").should("be.visible");
});
- });
- it("cannot use existing user session when useExistingUserSession is false", () => {
- H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: false });
+ cy.log("restore the current page's domain");
+ cy.visit("http://localhost:4000");
+ cy.log(
+ "visit a test page with an origin of example.com using the existing user session",
+ );
const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
+ elements: [ORDERS_DASHBOARD_ELEMENT],
+ origin: "http://example.com",
metabaseConfig: {
- useExistingUserSession: false,
+ useExistingUserSession: true,
},
});
+ frame
+ .findByText(
+ "Using the existing user's session in production is not allowed.",
+ )
+ .should("exist");
+
+ frame.findByText("Orders in a dashboard").should("not.exist");
+ });
+
+ it("uses the existing user session only when useExistingUserSession is true", () => {
+ H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: false });
+
cy.log(
"when no auth methods are enabled and the existing user session is not used, it should fail to login",
);
-
- frame.within(() => {
+ H.loadSdkIframeEmbedTestPage({
+ elements: [ORDERS_DASHBOARD_ELEMENT],
+ metabaseConfig: {
+ useExistingUserSession: false,
+ },
+ }).within(() => {
cy.findByTestId("sdk-error-container")
.should("be.visible")
.and("contain", "SSO has not been enabled and/or configured");
});
- });
-
- it("can login via JWT", () => {
- H.prepareSdkIframeEmbedTest({ enabledAuthMethods: ["jwt"], signOut: true });
+ cy.log("useExistingUserSession is true");
const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
+ elements: [ORDERS_DASHBOARD_ELEMENT],
+ metabaseConfig: {
+ useExistingUserSession: true,
+ },
});
assertDashboardLoaded(frame);
});
- it("can login via JWT and a custom fetch request token function", () => {
+ it("can login via JWT with a custom fetch request token function, and shows an error if it fails", () => {
H.prepareSdkIframeEmbedTest({ enabledAuthMethods: ["jwt"], signOut: true });
- const frame = H.loadSdkIframeEmbedTestPage({
+ cy.log("fetchRequestToken returns an empty token");
+ H.loadSdkIframeEmbedTestPage({
onVisitPage: (win) => {
// Unjustified type cast. FIXME
(win as any).metabaseConfig = {
// Unjustified type cast. FIXME
...(win as any).metabaseConfig,
fetchRequestToken: async () => {
- const jwt = await getSignedJwtForUser({ user: USERS.admin });
-
- return { jwt };
+ return { jwt: "" };
},
};
},
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
+ elements: [ORDERS_DASHBOARD_ELEMENT],
+ }).within(() => {
+ cy.findByTestId("sdk-error-container")
+ .findByText(/Failed to fetch JWT token/)
+ .should("exist");
});
- assertDashboardLoaded(frame);
- });
-
- it("shows error message if login via JWT and a custom fetch request token is failing", () => {
- H.prepareSdkIframeEmbedTest({ enabledAuthMethods: ["jwt"], signOut: true });
-
+ cy.log("fetchRequestToken returns a valid token");
const frame = H.loadSdkIframeEmbedTestPage({
onVisitPage: (win) => {
// Unjustified type cast. FIXME
@@ -251,63 +211,27 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
// Unjustified type cast. FIXME
...(win as any).metabaseConfig,
fetchRequestToken: async () => {
- return { jwt: "" };
+ const jwt = await getSignedJwtForUser({ user: USERS.admin });
+
+ 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 });
-
- const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
- onVisitPage: () => stubWindowOpenForSamlPopup(),
+ elements: [ORDERS_DASHBOARD_ELEMENT],
});
assertDashboardLoaded(frame);
});
- it("shows an error if the SAML login results in an invalid user", () => {
+ it("can login via SAML, and shows an error if the SAML login results in an invalid user", () => {
mockAuthSsoEndpointForSamlAuthProvider();
H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: true });
- const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
+ cy.log("SAML login results in an invalid user");
+ H.loadSdkIframeEmbedTestPage({
+ elements: [ORDERS_DASHBOARD_ELEMENT],
onVisitPage: () => stubWindowOpenForSamlPopup({ isUserValid: false }),
- });
-
- frame.within(() => {
+ }).within(() => {
cy.findByTestId("sdk-error-container")
.should("be.visible")
.and(
@@ -315,147 +239,69 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
"Failed to fetch the user, the session might be invalid.",
);
});
- });
-
- it("shows an error if we are using an API key in production", () => {
- H.prepareSdkIframeEmbedTest({
- enabledAuthMethods: ["api-key"],
- signOut: true,
- });
- cy.log("restore the current page's domain");
- cy.visit("http://localhost:4000");
-
- cy.log("visit a test page with an origin of example.com using api keys");
- cy.get<string>("@apiKey").then((apiKey) => {
- const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
- origin: "http://example.com",
- metabaseConfig: {
- apiKey,
- },
- });
-
- frame
- .findByText("Using an API key in production is not allowed.")
- .should("exist");
-
- cy.findByText("Orders in a dashboard").should("not.exist");
- });
- });
-
- it("shows an error if we are using the existing user session in production", () => {
- H.prepareSdkIframeEmbedTest({ enabledAuthMethods: [], signOut: true });
-
- cy.log("restore the current page's domain");
- cy.visit("http://localhost:4000");
-
- cy.log(
- "visit a test page with an origin of example.com using the existing user session",
- );
+ cy.log("SAML login results in a valid user");
const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
- origin: "http://example.com",
- metabaseConfig: {
- useExistingUserSession: true,
- },
+ elements: [ORDERS_DASHBOARD_ELEMENT],
+ onVisitPage: () => stubWindowOpenForSamlPopup(),
});
- frame
- .findByText(
- "Using the existing user's session in production is not allowed.",
- )
- .should("exist");
-
- frame.findByText("Orders in a dashboard").should("not.exist");
+ assertDashboardLoaded(frame);
});
- it("does not show an error if we are using an API key in development", () => {
+ it("allows an API key in development but not in production", () => {
H.prepareSdkIframeEmbedTest({
enabledAuthMethods: ["api-key"],
signOut: true,
});
cy.get<string>("@apiKey").then((apiKey) => {
- const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
+ cy.log("development");
+ const developmentFrame = H.loadSdkIframeEmbedTestPage({
+ elements: [ORDERS_DASHBOARD_ELEMENT],
metabaseConfig: {
apiKey,
},
});
- assertDashboardLoaded(frame);
+ assertDashboardLoaded(developmentFrame);
- frame
+ developmentFrame
.findByText("Using an API key in production is not allowed.")
.should("not.exist");
- });
- });
- it("uses JWT when authMethod is set to 'jwt' and both SAML and JWT are enabled", () => {
- cy.intercept("GET", "/auth/sso?preferred_method=jwt").as("authSso");
+ cy.log("restore the current page's domain");
+ cy.visit("http://localhost:4000");
- H.prepareSdkIframeEmbedTest({
- enabledAuthMethods: ["jwt", "saml"],
- signOut: true,
- });
-
- const frame = H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
+ cy.log("visit a test page with an origin of example.com using api keys");
+ const productionFrame = H.loadSdkIframeEmbedTestPage({
+ elements: [ORDERS_DASHBOARD_ELEMENT],
+ origin: "http://example.com",
+ metabaseConfig: {
+ apiKey,
},
- ],
- metabaseConfig: {
- preferredAuthMethod: "jwt",
- },
- });
+ });
- cy.wait("@authSso").its("response.body.method").should("eq", "jwt");
- assertDashboardLoaded(frame);
+ productionFrame
+ .findByText("Using an API key in production is not allowed.")
+ .should("exist");
+
+ productionFrame.findByText("Orders in a dashboard").should("not.exist");
+ });
});
- it("uses SAML when authMethod is set to 'saml' and both SAML and JWT are enabled", () => {
- cy.intercept("GET", "/auth/sso?preferred_method=saml").as("authSso");
+ it("uses the auth method set in preferredAuthMethod when both SAML and JWT are enabled", () => {
+ cy.intercept("GET", "/auth/sso?preferred_method=saml").as("samlAuthSso");
+ cy.intercept("GET", "/auth/sso?preferred_method=jwt").as("jwtAuthSso");
H.prepareSdkIframeEmbedTest({
enabledAuthMethods: ["jwt", "saml"],
signOut: true,
});
+ cy.log("preferredAuthMethod is saml");
H.loadSdkIframeEmbedTestPage({
- elements: [
- {
- component: "metabase-dashboard",
- attributes: {
- dashboardId: ORDERS_DASHBOARD_ID,
- },
- },
- ],
+ elements: [ORDERS_DASHBOARD_ELEMENT],
metabaseConfig: {
preferredAuthMethod: "saml",
},
@@ -472,10 +318,21 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
// preferredAuthMethod: "saml" must route to the SAML initiate endpoint. It now
// returns a 200 with the AuthnRequest redirect (the RelayState is stored
// server-side and only a short key is sent to the IdP).
- cy.wait("@authSso").then(({ response }) => {
+ cy.wait("@samlAuthSso").then(({ response }) => {
expect(response?.statusCode).to.eq(200);
expect(response?.body?.method).to.eq("saml");
});
+
+ cy.log("preferredAuthMethod is jwt");
+ const frame = H.loadSdkIframeEmbedTestPage({
+ elements: [ORDERS_DASHBOARD_ELEMENT],
+ metabaseConfig: {
+ preferredAuthMethod: "jwt",
+ },
+ });
+
+ cy.wait("@jwtAuthSso").its("response.body.method").should("eq", "jwt");
+ assertDashboardLoaded(frame);
});
});
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-embed.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-embed.cy.spec.ts
index a2c83f8cd7b..85633e9e51a 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-embed.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-embed.cy.spec.ts
@@ -25,36 +25,23 @@ function guestEmbedSuite() {
});
});
- it("shows a static question", () => {
- cy.get("@questionId").then(async (questionId) => {
- const token = await getSignedJwtForResource({
- // Unjustified type cast. FIXME
- resourceId: questionId as unknown as number,
- resourceType: "question",
- });
-
- const frame = H.loadSdkIframeEmbedTestPage({
- metabaseConfig: { isGuest: true },
- elements: [
- {
- component: "metabase-question",
- attributes: {
- token,
- },
- },
- ],
- });
-
- cy.wait("@getCardQuery");
-
- frame.within(() => {
- cy.findByText("Product ID").should("be.visible");
- cy.findByText("Max of Quantity").should("be.visible");
- });
+ it("shows an error for a component without guest embed support, and shows and downloads a static question", () => {
+ cy.log("component without guest embed support shows an error");
+ H.loadSdkIframeEmbedTestPage({
+ metabaseConfig: { isGuest: true },
+ elements: [
+ {
+ component: "metabase-browser",
+ attributes: {},
+ },
+ ],
+ }).within(() => {
+ cy.findByText("This component does not support guest embeds").should(
+ "be.visible",
+ );
});
- });
- it("allows to download a static question as CSV", () => {
+ cy.log("static question shows and downloads as CSV");
cy.get("@questionId").then(async (questionId) => {
const token = await getSignedJwtForResource({
// Unjustified type cast. FIXME
@@ -78,6 +65,9 @@ function guestEmbedSuite() {
cy.wait("@getCardQuery");
frame.within(() => {
+ cy.findByText("Product ID").should("be.visible");
+ cy.findByText("Max of Quantity").should("be.visible");
+
H.downloadAndAssert({
isDashboard: false,
isEmbed: true,
@@ -91,24 +81,6 @@ function guestEmbedSuite() {
});
});
});
-
- it("shows an error for a component without guest embed support", () => {
- const frame = H.loadSdkIframeEmbedTestPage({
- metabaseConfig: { isGuest: true },
- elements: [
- {
- component: "metabase-browser",
- attributes: {},
- },
- ],
- });
-
- frame.within(() => {
- cy.findByText("This component does not support guest embeds").should(
- "be.visible",
- );
- });
- });
}
describe(
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.ts
index 34db5ea5c5e..1d3eb32eeb5 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-token-refresh.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/guest-token-refresh.cy.spec.ts
@@ -9,32 +9,175 @@ 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", {
+const HTTP_ERROR_MESSAGE =
+ "Failed to fetch JWT token from /api/mock-guest-token-provider, status: 500.";
+const WRONG_SHAPE_MESSAGE =
+ /Your JWT server endpoint must return an object with the shape { jwt: string }, but instead received {"token":/;
+
+type Resource = { type: "dashboard" | "question"; id: number };
+type TokenMode = "refresh-only" | "initial-token";
+
+const COMPONENT_BY_TYPE = {
+ dashboard: "metabase-dashboard",
+ question: "metabase-question",
+} as const;
+
+function signJwt(
+ resource: Resource,
+ expirationSeconds: number,
+): Cypress.Chainable<string> {
+ return cy.then(() =>
+ cy.task<string>("signJwt", {
payload: {
- resource,
- params,
+ resource: { [resource.type]: resource.id },
+ params: {},
exp: Math.round(Date.now() / 1000) + expirationSeconds,
},
secret: JWT_SHARED_SECRET,
- })
- .then((token) => token);
+ }),
+ );
+}
+
+function mockTokenProvider(
+ alias: string,
+ reply: { statusCode: number; body?: Record<string, unknown> },
+) {
+ cy.intercept(PROVIDER_INTERCEPT, (req) => {
+ req.reply(reply);
+ }).as(alias);
+}
+
+function loadGuestEmbed(
+ resource: Resource,
+ attributes: Record<string, unknown>,
+) {
+ H.loadSdkIframeEmbedTestPage({
+ metabaseConfig: {
+ isGuest: true,
+ guestEmbedProviderUri: PROVIDER_PATH,
+ },
+ elements: [{ component: COMPONENT_BY_TYPE[resource.type], attributes }],
+ });
+}
+
+function loadGuestEmbedForMode(resource: Resource, mode: TokenMode) {
+ if (mode === "initial-token") {
+ loadGuestEmbed(resource, { [`${resource.type}-id`]: resource.id });
+ return;
+ }
+
+ signJwt(resource, -60).then((expiredToken) => {
+ loadGuestEmbed(resource, { token: expiredToken });
+ });
+}
+
+function forceTokenRefreshOnNextRequest() {
+ cy.get("iframe[data-metabase-embed]")
+ .its("0.contentWindow")
+ .should("exist")
+ .then((contentWindow) => {
+ contentWindow.FORCE_REFRESH_GUEST_EMBED_TOKEN_IN_CYPRESS = true;
+ });
+}
+
+function checkProviderErrors(resource: Resource, mode: TokenMode) {
+ cy.log("the provider returns an HTTP error");
+ mockTokenProvider(`${mode}HttpErrorProvider`, { statusCode: 500 });
+ loadGuestEmbedForMode(resource, mode);
+ cy.wait(`@${mode}HttpErrorProvider`);
+ H.getSimpleEmbedIframeContent()
+ .findByText(HTTP_ERROR_MESSAGE)
+ .should("be.visible");
+
+ cy.log("the provider returns a wrong response shape");
+ signJwt(resource, 600).then((freshToken) => {
+ mockTokenProvider(`${mode}WrongShapeProvider`, {
+ statusCode: 200,
+ body: { token: freshToken },
+ });
+ });
+ loadGuestEmbedForMode(resource, mode);
+ cy.wait(`@${mode}WrongShapeProvider`);
+ H.getSimpleEmbedIframeContent()
+ .findByText(WRONG_SHAPE_MESSAGE)
+ .should("be.visible");
+}
+
+function loadWithShortLivedToken(resource: Resource, alias: string) {
+ signJwt(resource, 5).then((shortLivedToken) => {
+ signJwt(resource, 600).then((freshToken) => {
+ mockTokenProvider(alias, {
+ statusCode: 200,
+ body: { jwt: freshToken },
+ });
+ loadGuestEmbed(resource, { token: shortLivedToken });
+ });
+ });
+}
+
+type FilterCheckOptions = {
+ resource: Resource;
+ columns: string[];
+ waitForLoad: () => void;
+};
+
+function checkNumberFilterAfterRefresh({
+ resource,
+ columns,
+ waitForLoad,
+}: FilterCheckOptions) {
+ cy.log("number filter after a token refresh");
+ loadWithShortLivedToken(resource, "numberFilterProvider");
+
+ H.getSimpleEmbedIframeContent().within(waitForLoad);
+
+ forceTokenRefreshOnNextRequest();
+
+ 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("@numberFilterProvider");
+
+ H.assertTableData({
+ columns,
+ firstRows: [["2", "Small Marble Shoes", "70.08"]],
+ });
+ });
+}
+
+function checkCategoryFilterAfterRefresh({
+ resource,
+ columns,
+ waitForLoad,
+}: FilterCheckOptions) {
+ cy.log("category filter after a token refresh");
+ loadWithShortLivedToken(resource, "categoryFilterProvider");
+
+ H.getSimpleEmbedIframeContent().within(waitForLoad);
+
+ forceTokenRefreshOnNextRequest();
+
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.findByLabelText("Category").click();
+
+ cy.log(
+ "ensure the token is refreshed after the filter values endpoint is called",
+ );
+ cy.wait("@categoryFilterProvider");
+
+ H.popover().within(() => {
+ cy.findByRole("checkbox", { name: "Doohickey" }).click();
+ cy.button("Add filter").click();
+ });
+
+ H.assertTableData({
+ columns,
+ firstRows: [["2", "Small Marble Shoes", "Doohickey"]],
+ });
+ });
}
const PRICE_DASHBOARD_PARAMETER = {
@@ -94,7 +237,7 @@ describe("scenarios > embedding > sdk iframe embedding > guest token refresh", (
name: "Guest Token Refresh Dashboard with Price Filter",
parameters: [PRICE_DASHBOARD_PARAMETER],
}).then(({ body: dashboard }) => {
- cy.wrap(dashboard.id).as("dashboardId");
+ cy.wrap(dashboard.id).as("priceDashboardId");
cy.request("PUT", `/api/dashboard/${dashboard.id}`, {
enable_embedding: true,
@@ -146,7 +289,7 @@ describe("scenarios > embedding > sdk iframe embedding > guest token refresh", (
name: "Guest Token Refresh Dashboard with Category Filter",
parameters: [CATEGORY_DASHBOARD_PARAMETER],
}).then(({ body: dashboard }) => {
- cy.wrap(dashboard.id).as("dashboardId");
+ cy.wrap(dashboard.id).as("categoryDashboardId");
cy.request("PUT", `/api/dashboard/${dashboard.id}`, {
enable_embedding: true,
@@ -220,7 +363,7 @@ describe("scenarios > embedding > sdk iframe embedding > guest token refresh", (
embedding_params: { price: "enabled" },
embedding_type: "guest-embed",
}).then(({ body: question }) => {
- cy.wrap(question.id).as("questionId");
+ cy.wrap(question.id).as("priceQuestionId");
});
}
@@ -246,872 +389,257 @@ describe("scenarios > embedding > sdk iframe embedding > guest token refresh", (
embedding_params: { category: "enabled" },
embedding_type: "guest-embed",
}).then(({ body: question }) => {
- cy.wrap(question.id).as("questionId");
+ cy.wrap(question.id).as("categoryQuestionId");
});
}
- 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":
- '{"param":"value","nested":{"a":1}}',
- },
- },
- ],
- });
-
- cy.wait("@guestTokenProvider").then((interception) => {
- expect(interception.request.body).to.deep.include({
- entityType: "dashboard",
- entityId: dashboardId,
- customContext: { param: "value", nested: { a: 1 } },
- });
- });
-
- H.getSimpleEmbedIframeContent().should("contain", "Orders");
- },
- );
- },
- );
- });
+ describe("dashboard", () => {
+ beforeEach(() => {
+ H.prepareGuestEmbedSdkIframeEmbedTest({
+ onPrepare: () => {
+ createDashboardWithQuestion();
+ createDashboardWithPriceFilter();
+ createDashboardWithCategoryFilter();
+ },
});
});
- describe("provider error shows error state", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createDashboardWithQuestion,
- });
- });
+ it("refreshes an expired token, fetches the first token, shows provider errors, and keeps filters working after a refresh", () => {
+ cy.get<number>("@dashboardId").then((dashboardId) => {
+ const resource: Resource = { type: "dashboard", id: dashboardId };
+
+ cy.log("refresh-only");
+ cy.log("the provider returns a fresh token");
+ signJwt(resource, -60).then((expiredToken) => {
+ signJwt(resource, 600).then((freshToken) => {
+ mockTokenProvider("refreshOnlyProvider", {
+ statusCode: 200,
+ body: { jwt: freshToken },
+ });
- 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");
- },
- );
+ loadGuestEmbed(resource, {
+ token: expiredToken,
+ "custom-context": '{"param":"value","nested":{"a":1}}',
+ });
+ });
});
- });
- 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");
- },
- );
- },
- );
+ cy.wait("@refreshOnlyProvider").then((interception) => {
+ expect(interception.request.body).to.deep.include({
+ entityType: "dashboard",
+ entityId: dashboardId,
+ customContext: { param: "value", nested: { a: 1 } },
+ });
});
- });
- });
- describe("number filter interaction after token refresh", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createDashboardWithPriceFilter,
- });
- });
+ H.getSimpleEmbedIframeContent().should("contain", "Orders");
- 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"]],
- });
- });
- },
- );
- },
- );
- });
- });
- });
+ checkProviderErrors(resource, "refresh-only");
- describe("category filter interaction after token refresh", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createDashboardWithCategoryFilter,
+ cy.log("initial-token");
+ cy.log("the provider returns a fresh token");
+ signJwt(resource, 600).then((freshToken) => {
+ mockTokenProvider("initialTokenProvider", {
+ statusCode: 200,
+ body: { jwt: freshToken },
+ });
});
- });
- 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"]],
- });
- });
- },
- );
- },
- );
+ loadGuestEmbed(resource, {
+ "dashboard-id": dashboardId,
+ "custom-context": "test-custom-context",
});
- });
- });
- });
- describe("dashboard initial-token", () => {
- describe("happy path", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createDashboardWithQuestion,
+ cy.wait("@initialTokenProvider").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",
+ });
});
- });
-
- 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");
- },
- );
- });
- });
- });
+ H.getSimpleEmbedIframeContent().should("contain", "Orders");
- describe("provider error shows error state", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createDashboardWithQuestion,
- });
+ checkProviderErrors(resource, "initial-token");
});
- 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");
+ cy.get<number>("@priceDashboardId").then((priceDashboardId) => {
+ checkNumberFilterAfterRefresh({
+ resource: { type: "dashboard", id: priceDashboardId },
+ columns: ["ID", "Title", "Price"],
+ waitForLoad: () => {
+ cy.findByLabelText("Price greater than").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");
- },
- );
+ cy.get<number>("@categoryDashboardId").then((categoryDashboardId) => {
+ checkCategoryFilterAfterRefresh({
+ resource: { type: "dashboard", id: categoryDashboardId },
+ columns: ["ID", "Title", "Category"],
+ waitForLoad: () => {
+ cy.findByLabelText("Category").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("question", () => {
+ beforeEach(() => {
+ H.prepareGuestEmbedSdkIframeEmbedTest({
+ onPrepare: () => {
+ createStandaloneQuestion();
+ createOtherStandaloneQuestion();
+ createQuestionWithPriceFilter();
+ createQuestionWithCategoryFilter();
+ },
});
});
- describe("provider returns a different resource", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: () => {
- createQuestionWithCategoryFilter();
- createOtherStandaloneQuestion();
- },
- });
- });
+ it("refreshes an expired token, fetches the first token, shows provider errors, keeps filters working after a refresh, and switches to the question the refreshed token names", () => {
+ cy.get<number>("@questionId").then((questionId) => {
+ const resource: Resource = { type: "question", id: questionId };
+
+ cy.log("refresh-only");
+ cy.log("the provider returns a fresh token");
+ signJwt(resource, -60).then((expiredToken) => {
+ signJwt(resource, 600).then((freshToken) => {
+ mockTokenProvider("refreshOnlyProvider", {
+ statusCode: 200,
+ body: { jwt: freshToken },
+ });
- it("switches to the question the refreshed token names", () => {
- cy.get<number>("@questionId").then((questionId) => {
- cy.get<number>("@otherQuestionId").then((otherQuestionId) => {
- signJwt({ questionId, expirationSeconds: 600 }).then(
- (initialToken) => {
- signJwt({
- questionId: otherQuestionId,
- expirationSeconds: 600,
- }).then((freshToken) => {
- cy.intercept(PROVIDER_INTERCEPT, (req) => {
- req.reply({ statusCode: 200, body: { jwt: freshToken } });
- }).as("guestTokenProvider");
-
- H.loadSdkIframeEmbedTestPage({
- metabaseConfig: {
- isGuest: true,
- guestEmbedProviderUri: PROVIDER_PATH,
- },
- elements: [
- {
- component: "metabase-question",
- attributes: { token: initialToken },
- },
- ],
- });
-
- // Apply a filter value so the question runs with a parameter
- // set, which is the state that has to survive the swap.
- H.getSimpleEmbedIframeContent().within(() => {
- cy.findByLabelText("Category").click();
- H.popover().within(() => {
- cy.findByRole("checkbox", { name: "Doohickey" }).click();
- cy.button("Add filter").click();
- });
-
- H.assertTableData({
- columns: ["ID", "TITLE", "CATEGORY"],
- });
- });
-
- cy.get("iframe[data-metabase-embed]")
- .its("0.contentWindow")
- .should("exist")
- .then((contentWindow) => {
- contentWindow.FORCE_REFRESH_GUEST_EMBED_TOKEN_IN_CYPRESS = true;
- });
-
- H.getSimpleEmbedIframeContent().within(() => {
- // The refresh only fires on the next request, so re-running
- // the query with a new filter value is what triggers it.
- cy.findByLabelText("Category").click();
- H.popover().within(() => {
- cy.findByRole("checkbox", { name: "Gadget" }).click();
- cy.button("Update filter").click();
- });
-
- cy.wait("@guestTokenProvider");
- });
-
- // The refreshed token names a question that takes no
- // parameters, so the old filter value must not be sent along
- // with it.
- H.getSimpleEmbedIframeContent()
- .findByText(/Unknown parameter/)
- .should("not.exist");
-
- // "Vendor" is only on the question the refreshed token names.
- H.getSimpleEmbedIframeContent()
- .findByText("Vendor")
- .should("exist");
- });
- },
- );
+ loadGuestEmbed(resource, {
+ token: expiredToken,
+ "custom-context": "test-custom-context",
+ });
});
});
- });
- });
- describe("provider error shows error state", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createStandaloneQuestion,
+ cy.wait("@refreshOnlyProvider").then((interception) => {
+ expect(interception.request.body).to.deep.include({
+ entityType: "question",
+ entityId: questionId,
+ customContext: "test-custom-context",
+ });
});
- });
- 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");
- },
- );
- });
- });
+ H.getSimpleEmbedIframeContent()
+ .findByTestId("visualization-root")
+ .should("exist");
- 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");
- },
- );
- },
- );
- });
- });
- });
+ checkProviderErrors(resource, "refresh-only");
- describe("number filter interaction after token refresh", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createQuestionWithPriceFilter,
+ cy.log("initial-token");
+ cy.log("the provider returns a fresh token");
+ signJwt(resource, 600).then((freshToken) => {
+ mockTokenProvider("initialTokenProvider", {
+ statusCode: 200,
+ body: { jwt: freshToken },
+ });
});
- });
- 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"]],
- });
- });
- },
- );
- },
- );
+ loadGuestEmbed(resource, {
+ "question-id": questionId,
+ "custom-context": "test-custom-context",
});
- });
- });
- describe("category filter interaction after token refresh", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createQuestionWithCategoryFilter,
+ cy.wait("@initialTokenProvider").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");
+
+ checkProviderErrors(resource, "initial-token");
});
- 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"]],
- });
- });
- },
- );
- },
- );
+ cy.get<number>("@priceQuestionId").then((priceQuestionId) => {
+ checkNumberFilterAfterRefresh({
+ resource: { type: "question", id: priceQuestionId },
+ columns: ["ID", "TITLE", "PRICE"],
+ waitForLoad: () => {
+ cy.findByText("Products with price filter").should("be.visible");
+ },
});
});
- });
- });
- describe("question initial-token", () => {
- describe("happy path", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createStandaloneQuestion,
+ cy.get<number>("@categoryQuestionId").then((categoryQuestionId) => {
+ checkCategoryFilterAfterRefresh({
+ resource: { type: "question", id: categoryQuestionId },
+ columns: ["ID", "TITLE", "CATEGORY"],
+ waitForLoad: () => {
+ cy.findByText("Products with category filter").should("be.visible");
+ },
});
});
- 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.log("switches to the question the refreshed token names");
+ cy.get<number>("@categoryQuestionId").then((categoryQuestionId) => {
+ cy.get<number>("@otherQuestionId").then((otherQuestionId) => {
+ const resource: Resource = {
+ type: "question",
+ id: categoryQuestionId,
+ };
- 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",
- });
- });
+ signJwt(resource, 600).then((initialToken) => {
+ signJwt({ type: "question", id: otherQuestionId }, 600).then(
+ (freshToken) => {
+ mockTokenProvider("switchQuestionProvider", {
+ statusCode: 200,
+ body: { jwt: freshToken },
+ });
- H.getSimpleEmbedIframeContent()
- .findByTestId("visualization-root")
- .should("exist");
+ loadGuestEmbed(resource, { token: initialToken });
+ },
+ );
});
- });
- });
- });
- describe("provider error shows error state", () => {
- beforeEach(() => {
- H.prepareGuestEmbedSdkIframeEmbedTest({
- onPrepare: createStandaloneQuestion,
- });
- });
+ // Apply a filter value so the question runs with a parameter
+ // set, which is the state that has to survive the swap.
+ H.getSimpleEmbedIframeContent().within(() => {
+ cy.findByLabelText("Category").click();
+ H.popover().within(() => {
+ cy.findByRole("checkbox", { name: "Doohickey" }).click();
+ cy.button("Add filter").click();
+ });
- 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 },
- },
- ],
+ H.assertTableData({
+ columns: ["ID", "TITLE", "CATEGORY"],
+ });
});
- cy.wait("@guestTokenProvider");
- H.getSimpleEmbedIframeContent()
- .findByText(
- "Failed to fetch JWT token from /api/mock-guest-token-provider, status: 500.",
- )
- .should("be.visible");
- });
- });
+ forceTokenRefreshOnNextRequest();
- 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 },
- },
- ],
+ H.getSimpleEmbedIframeContent().within(() => {
+ // The refresh only fires on the next request, so re-running
+ // the query with a new filter value is what triggers it.
+ cy.findByLabelText("Category").click();
+ H.popover().within(() => {
+ cy.findByRole("checkbox", { name: "Gadget" }).click();
+ cy.button("Update filter").click();
});
- cy.wait("@guestTokenProvider");
- H.getSimpleEmbedIframeContent()
- .findByText(
- /Your JWT server endpoint must return an object with the shape { jwt: string }, but instead received {"token":/,
- )
- .should("be.visible");
+ cy.wait("@switchQuestionProvider");
});
+
+ // The refreshed token names a question that takes no
+ // parameters, so the old filter value must not be sent along
+ // with it.
+ H.getSimpleEmbedIframeContent()
+ .findByText(/Unknown parameter/)
+ .should("not.exist");
+
+ // "Vendor" is only on the question the refreshed token names.
+ H.getSimpleEmbedIframeContent().findByText("Vendor").should("exist");
});
});
});
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/missing-tokens.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/missing-tokens.cy.spec.ts
index cc446f8b089..2f5f55a5568 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/missing-tokens.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/missing-tokens.cy.spec.ts
@@ -53,6 +53,7 @@ describe("scenarios > embedding > sdk iframe embedding > without token features"
},
});
+ frame.findByText("Pick your starting data").should("be.visible");
frame
.findByText("A valid license is required for embedding.")
.should("not.exist");