Skip to content

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

Consolidate custom viz e2e tests (#83928)

Nemanja Glumace82452762f48
diff --git a/e2e/test/scenarios/data-apps/custom-viz.cy.spec.ts b/e2e/test/scenarios/data-apps/custom-viz.cy.spec.ts
index a5ec3590cfa..70e9fd199c1 100644
--- a/e2e/test/scenarios/data-apps/custom-viz.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/custom-viz.cy.spec.ts
@@ -34,12 +34,6 @@ describe("scenarios > data apps > custom visualizations", () => {
visitAppRoute("custom-viz");
H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
- // The InteractiveQuestion (a single-column count) must render before its
- // toolbar — `demo-viz` requires exactly one result column.
- cy.findByTestId("data-app-custom-viz", { timeout: 30000 }).should(
- "exist",
- );
-
// Switch the visualization to the custom viz through the chart-type selector.
cy.findByTestId("chart-type-selector-button", { timeout: 30000 }).click();
cy.findByText("demo-viz").click();
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-viz.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-viz.cy.spec.ts
index 24db2099fb6..6a4cbbd949e 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-viz.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-viz.cy.spec.ts
@@ -39,7 +39,7 @@ describe(
cy.signOut();
});
- it("renders the custom visualization when allowedCustomVisualizations includes the display", () => {
+ it("renders the custom visualization when allowedCustomVisualizations includes the display, and falls back to the default display when the allowlist is not set", () => {
cy.log(
"EAJS has no eval-permissive page CSP, so the plugin sandbox loads the hosted donor document",
);
@@ -48,7 +48,7 @@ describe(
);
cy.get<CardId>("@questionId").then((questionId) => {
- const frame = H.loadSdkIframeEmbedTestPage({
+ const allowlistedFrame = H.loadSdkIframeEmbedTestPage({
elements: [
{
component: "metabase-question",
@@ -65,17 +65,14 @@ describe(
cy.log("The sandbox loads the donor document as its iframe src");
cy.wait("@getSandboxHost").its("response.statusCode").should("eq", 200);
- frame.within(() => {
+ allowlistedFrame.within(() => {
cy.findByText("Custom viz rendered successfully").should(
"be.visible",
);
});
- });
- });
- it("falls back to the default display when the allowlist is not set", () => {
- cy.get<CardId>("@questionId").then((questionId) => {
- const frame = H.loadSdkIframeEmbedTestPage({
+ cy.log("Without the allowlist, the question uses its default display");
+ const defaultFrame = H.loadSdkIframeEmbedTestPage({
elements: [
{
component: "metabase-question",
@@ -86,7 +83,7 @@ describe(
cy.wait("@getCardQuery");
- frame.within(() => {
+ defaultFrame.within(() => {
// The count question renders with its sensible default (a scalar)
// when the custom viz is not allowlisted.
cy.findByTestId("scalar-container").should("be.visible");
diff --git a/e2e/test/scenarios/visualizations/custom-viz/custom-viz.cy.spec.ts b/e2e/test/scenarios/visualizations/custom-viz/custom-viz.cy.spec.ts
index 53dacdbec52..122e9a30f27 100644
--- a/e2e/test/scenarios/visualizations/custom-viz/custom-viz.cy.spec.ts
+++ b/e2e/test/scenarios/visualizations/custom-viz/custom-viz.cy.spec.ts
@@ -62,25 +62,22 @@ function buildDocumentWithCustomVizCard(cardId: CardId): DocumentContent {
describe("admin > custom visualizations", () => {
beforeEach(() => {
- H.restore("postgres-writable");
+ H.restore();
cy.signInAsAdmin();
});
describe("feature gating", () => {
describe("EE", () => {
- it("should show upsell when feature is locked", () => {
- // No token activation — feature is locked
+ it("should show upsell when feature is locked, then enable and disable custom visualizations", () => {
+ cy.log("No token activation — feature is locked");
H.visitCustomVizSettings();
cy.findByRole("heading", {
name: /Build your own visualizations/,
}).should("be.visible");
H.getAddVisualizationLink().should("not.exist");
- });
- it("should enable and disable custom visualizations", () => {
H.activateToken("bleeding-edge");
-
H.visitCustomVizSettings();
cy.log(
@@ -110,12 +107,10 @@ describe("admin > custom visualizations", () => {
.click();
H.popover().findByText("Deactivate custom visualizations").click();
- H.main()
- .findByRole("heading", { name: "Add a new visualization" })
- .should("not.exist");
H.main()
.findByRole("heading", { name: "Enable custom visualizations" })
.should("be.visible");
+ H.getAddVisualizationLink().should("not.exist");
});
it('should not show custom visualizations page to non-admins with "Settings access" permission', () => {
@@ -132,6 +127,9 @@ describe("admin > custom visualizations", () => {
);
H.goToAdmin();
+ cy.findByTestId("admin-layout-sidebar")
+ .findByText("Maps")
+ .should("be.visible");
cy.findByTestId("admin-layout-sidebar")
.findByText("Custom visualizations")
.should("not.exist");
@@ -150,15 +148,15 @@ describe("admin > custom visualizations", () => {
H.visitCustomVizSettings();
H.getAddVisualizationLink().click();
+ cy.findByTestId("admin-layout-sidebar")
+ .findByRole("link", { name: /Custom visualizations/ })
+ .should("have.attr", "data-active", "true");
cy.findByTestId("admin-layout-sidebar")
.findByRole("link", { name: /Development/ })
.should("not.exist");
cy.findByTestId("admin-layout-sidebar")
.findByRole("link", { name: /Manage visualizations/ })
.should("not.exist");
- cy.findByTestId("admin-layout-sidebar")
- .findByRole("link", { name: /Custom visualizations/ })
- .should("have.attr", "data-active", "true");
H.dropCustomVizBundle(H.CUSTOM_VIZ_FIXTURE_TGZ);
cy.findByRole("button", { name: "Add visualization" }).click();
@@ -193,57 +191,9 @@ describe("admin > custom visualizations", () => {
H.updateSetting("custom-viz-enabled", true);
});
- it("should add a plugin via the form and show it in the list", () => {
+ it("should reject an invalid bundle inline, then add a plugin via the form and show it in the list", () => {
H.resetSnowplow();
H.enableTracking();
- H.visitCustomVizSettings();
-
- H.getAddVisualizationLink().click();
-
- cy.log("Submit is disabled until a file is selected");
- cy.findByRole("button", { name: "Add visualization" }).should(
- "be.disabled",
- );
-
- H.dropCustomVizBundle(H.CUSTOM_VIZ_FIXTURE_TGZ);
- cy.findByRole("button", { name: "Add visualization" }).should(
- "be.enabled",
- );
-
- H.interceptPluginCreate();
- cy.findByRole("button", { name: "Add visualization" }).click();
- cy.wait("@pluginCreate");
-
- cy.log("Should redirect to the list and show the plugin");
- H.main().findByText("demo-viz").should("be.visible");
- H.expectUnstructuredSnowplowEvent({
- event: "custom_viz_plugin_created",
- result: "success",
- });
- H.expectNoBadSnowplowEvents();
- });
-
- it("should display manifest information and bundle hash after upload", () => {
- H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);
- H.visitCustomVizSettings();
- H.getCustomVizPluginIcon("demo-viz").should("be.visible");
- H.main().findByText("demo-viz").should("be.visible");
-
- cy.log(
- "Bundle hash chip is the first 8 chars of the fixture's deterministic SHA-256",
- );
- H.getCustomVizFixtureHash(H.CUSTOM_VIZ_FIXTURE_TGZ).then((hash) => {
- H.main()
- .findByText(`Bundle: ${hash.slice(0, 8)}`)
- .should("be.visible");
- });
-
- H.main()
- .findByText(/^Requires Metabase /)
- .should("be.visible");
- });
-
- it("should surface an inline error for an invalid bundle", () => {
H.visitCustomVizNewForm();
cy.findByRole("link", { name: /Manage visualizations/ }).should(
@@ -251,6 +201,12 @@ describe("admin > custom visualizations", () => {
"data-active",
"true",
);
+ cy.findByRole("link", { name: /Development/ }).should("be.visible");
+
+ cy.log("Submit is disabled until a file is selected");
+ cy.findByRole("button", { name: "Add visualization" }).should(
+ "be.disabled",
+ );
cy.log("Upload a non-tar.gz file so the BE rejects it.");
H.dropCustomVizBundle({
@@ -279,16 +235,55 @@ describe("admin > custom visualizations", () => {
"eq",
"/admin/settings/custom-visualizations/new",
);
+
+ cy.log("Reopen the form from the list and upload a valid bundle");
+ cy.findByTestId("admin-layout-sidebar")
+ .findByRole("link", { name: /Manage visualizations/ })
+ .click();
+ H.getAddVisualizationLink().click();
+ cy.findByRole("button", { name: "Add visualization" }).should(
+ "be.disabled",
+ );
+ H.dropCustomVizBundle(H.CUSTOM_VIZ_FIXTURE_TGZ);
+ cy.findByRole("button", { name: "Add visualization" }).should(
+ "be.enabled",
+ );
+
+ H.interceptPluginCreate();
+ cy.findByRole("button", { name: "Add visualization" }).click();
+ cy.wait("@pluginCreate");
+
+ cy.log("Should redirect to the list and show the plugin");
+ H.main().findByText("demo-viz").should("be.visible");
+ H.expectUnstructuredSnowplowEvent({
+ event: "custom_viz_plugin_created",
+ result: "success",
+ });
+ H.expectNoBadSnowplowEvents();
});
- it("should support multiple plugins", () => {
+ it("should support multiple plugins and display their manifest information and bundle hash", () => {
H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);
H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ_2);
H.visitCustomVizSettings();
+ H.getCustomVizPluginIcon("demo-viz").should("be.visible");
H.main().findByText("demo-viz").should("be.visible");
H.main().findByText("demo-viz-2").should("be.visible");
+ cy.log(
+ "Bundle hash chip is the first 8 chars of the fixture's deterministic SHA-256",
+ );
+ H.getCustomVizFixtureHash(H.CUSTOM_VIZ_FIXTURE_TGZ).then((hash) => {
+ H.main()
+ .findByText(`Bundle: ${hash.slice(0, 8)}`)
+ .should("be.visible");
+ });
+
+ H.main()
+ .findAllByText(/^Requires Metabase /)
+ .should("have.length", 2);
+
// Both plugins should be available in chart type selector
H.openOrdersTable({ limit: 1 });
cy.findByTestId("viz-type-button").click();
@@ -297,243 +292,194 @@ describe("admin > custom visualizations", () => {
H.main().findByText("demo-viz-2").should("be.visible");
});
- describe("with an installed plugin", () => {
- beforeEach(() => {
- H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);
- H.visitCustomVizSettings();
- });
-
- it("should display plugin details in the list", () => {
- H.main().findByText("demo-viz").should("be.visible");
- H.getCustomVizFixtureHash(H.CUSTOM_VIZ_FIXTURE_TGZ).then((hash) => {
- H.main()
- .findByText(`Bundle: ${hash.slice(0, 8)}`)
- .should("be.visible");
- });
- });
- });
-
- describe("updating a plugin", () => {
- beforeEach(() => {
- H.activateToken("bleeding-edge");
- });
-
- it("should replace the bundle via the edit form", () => {
- H.resetSnowplow();
- H.enableTracking();
- H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ).then(
- (plugin: CustomVizPlugin) => {
- H.visitCustomVizSettings();
-
- cy.log(
- "Replace bundle is reachable only via the row's Plugin actions menu — clicking the row itself does not navigate",
- );
- H.main().findByText("demo-viz").click();
- cy.findByRole("heading", {
- name: /Replace bundle for/,
- }).should("not.exist");
-
- // Actions menu is only visible on row hover
- H.main().findByText("demo-viz").realHover();
- cy.findByRole("button", { name: "Plugin actions" }).click();
- H.popover().findByText("Replace bundle").click();
-
- cy.findByRole("heading", {
- name: "Replace bundle for demo-viz",
- }).should("be.visible");
-
- H.dropCustomVizBundle(H.CUSTOM_VIZ_FIXTURE_TGZ);
-
- cy.intercept(
- "PUT",
- `/api/ee/custom-viz-plugin/${plugin.id}/bundle`,
- ).as("pluginBundleReplace");
- cy.findByRole("button", { name: /Replace$/ }).click();
-
- cy.wait("@pluginBundleReplace")
- .its("response.statusCode")
- .should("eq", 200);
-
- cy.log("Should redirect back to the list page");
- cy.location("pathname").should(
- "eq",
- "/admin/settings/custom-visualizations",
- );
- H.main().findByText("demo-viz").should("be.visible");
- H.expectUnstructuredSnowplowEvent({
- event: "custom_viz_plugin_updated",
- result: "success",
- });
- H.expectNoBadSnowplowEvents();
- },
- );
- });
+ it("should reject a non-matching bundle inline, then replace the bundle via the edit form", () => {
+ H.resetSnowplow();
+ H.enableTracking();
+ H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ).then(
+ (plugin: CustomVizPlugin) => {
+ H.visitCustomVizEditForm(plugin.id);
+
+ cy.findByRole("link", { name: /Manage visualizations/ }).should(
+ "have.attr",
+ "data-active",
+ "true",
+ );
- it("should surface an inline error when replacing with a non-matching bundle", () => {
- H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ).then(
- (plugin: CustomVizPlugin) => {
- H.visitCustomVizEditForm(plugin.id);
+ cy.log(
+ 'The 2nd fixture has manifest.name = "demo-viz-2" — BE rejects because it does not match the existing identifier',
+ );
+ H.dropCustomVizBundle(H.CUSTOM_VIZ_FIXTURE_TGZ_2);
- cy.findByRole("link", { name: /Manage visualizations/ }).should(
- "have.attr",
- "data-active",
- "true",
- );
+ cy.intercept(
+ "PUT",
+ `/api/ee/custom-viz-plugin/${plugin.id}/bundle`,
+ ).as("pluginBundleReplace");
+ cy.findByRole("button", { name: /Replace$/ }).click();
- cy.log(
- 'The 2nd fixture has manifest.name = "demo-viz-2" — BE rejects because it does not match the existing identifier',
- );
- H.dropCustomVizBundle(H.CUSTOM_VIZ_FIXTURE_TGZ_2);
-
- cy.intercept(
- "PUT",
- `/api/ee/custom-viz-plugin/${plugin.id}/bundle`,
- ).as("pluginBundleReplaceInvalid");
- cy.findByRole("button", { name: /Replace$/ }).click();
-
- cy.wait("@pluginBundleReplaceInvalid")
- .its("response.statusCode")
- .should("eq", 400);
-
- cy.findByTestId("custom-viz-settings-form").within(() => {
- cy.findByText(/does not match the plugin's identifier/).should(
- "be.visible",
- );
- });
+ cy.wait("@pluginBundleReplace")
+ .its("response.statusCode")
+ .should("eq", 400);
- cy.location("pathname").should(
- "eq",
- `/admin/settings/custom-visualizations/edit/${plugin.id}`,
+ cy.findByTestId("custom-viz-settings-form").within(() => {
+ cy.findByText(/does not match the plugin's identifier/).should(
+ "be.visible",
);
- },
- );
- });
- });
-
- describe("disabling a plugin", () => {
- beforeEach(() => {
- H.activateToken("bleeding-edge");
- });
+ });
- it("disabled plugin should fall back to default display and hide from chart type selector", () => {
- H.resetSnowplow();
- H.enableTracking();
- H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ).then(() => {
- // Single-value question (Count of Orders) — demo-viz requires
- // exactly one row with one numeric column.
- H.createQuestion(
- {
- name: "Custom Viz Disable Test",
- query: {
- "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,
- aggregation: [["count"]],
- },
- display: H.CUSTOM_VIZ_DISPLAY,
- },
- { wrapId: true, idAlias: "disableCardId", visitQuestion: true },
+ cy.location("pathname").should(
+ "eq",
+ `/admin/settings/custom-visualizations/edit/${plugin.id}`,
);
- H.main()
- .findByText("Custom viz rendered successfully")
- .should("be.visible");
- H.getProfileLink().click();
- H.popover().findByText(adminAppLinkText).click();
-
- cy.findByTestId("admin-layout-sidebar")
- .findByText("Custom visualizations")
- .click();
+ H.visitCustomVizSettings();
- cy.findByTestId("admin-layout-sidebar")
- .findByText("Manage visualizations")
- .should("be.visible")
- .click();
+ cy.log(
+ "Replace bundle is reachable only via the row's Plugin actions menu — clicking the row itself does not navigate",
+ );
+ H.main().findByText("demo-viz").click();
+ cy.location("pathname").should(
+ "eq",
+ "/admin/settings/custom-visualizations",
+ );
+ cy.findByRole("heading", {
+ name: /Replace bundle for/,
+ }).should("not.exist");
// Actions menu is only visible on row hover
H.main().findByText("demo-viz").realHover();
cy.findByRole("button", { name: "Plugin actions" }).click();
- H.popover().findByText("Disable").click();
- H.expectUnstructuredSnowplowEvent({
- event: "custom_viz_plugin_toggled",
- event_detail: "disabled",
- });
+ H.popover().findByText("Replace bundle").click();
- // Menu should now show "Enable" instead of "Disable"
- H.main().findByText("demo-viz").realHover();
- cy.findByRole("button", { name: "Plugin actions" }).click();
- H.popover().findByText("Enable").should("be.visible");
+ cy.findByRole("heading", {
+ name: "Replace bundle for demo-viz",
+ }).should("be.visible");
+
+ H.dropCustomVizBundle(H.CUSTOM_VIZ_FIXTURE_TGZ);
+ cy.findByRole("button", { name: /Replace$/ }).click();
- H.getProfileLink().click();
- H.popover().findByText(mainAppLinkText).click();
+ cy.wait("@pluginBundleReplace")
+ .its("response.statusCode")
+ .should("eq", 200);
- cy.get("main").within(() => {
- cy.contains("Custom Viz Disable Test").click();
+ cy.log("Should redirect back to the list page");
+ cy.location("pathname").should(
+ "eq",
+ "/admin/settings/custom-visualizations",
+ );
+ H.main().findByText("demo-viz").should("be.visible");
+ H.expectUnstructuredSnowplowEvent({
+ event: "custom_viz_plugin_updated",
+ result: "success",
});
- // Reload the question — plugin is disabled, should fall back
+ H.expectNoBadSnowplowEvents();
+ },
+ );
+ });
- cy.log("make sure viz is table - fallback");
- cy.findByTestId("table-root").should("be.visible");
+ it("question should fall back when its plugin is disabled, and when it is removed", () => {
+ H.resetSnowplow();
+ H.enableTracking();
+ H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ).then(() => {
+ // Single-value question (Count of Orders) — demo-viz requires
+ // exactly one row with one numeric column.
+ H.createQuestion(
+ {
+ name: "Custom Viz Disable Test",
+ query: {
+ "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,
+ aggregation: [["count"]],
+ },
+ display: H.CUSTOM_VIZ_DISPLAY,
+ },
+ { wrapId: true, idAlias: "disableCardId", visitQuestion: true },
+ );
+ H.main()
+ .findByText("Custom viz rendered successfully")
+ .should("be.visible");
- // Custom viz section should not appear in chart type selector
- cy.findByTestId("viz-type-button").click();
- cy.findByText("Custom visualizations").should("not.exist");
- H.expectNoBadSnowplowEvents();
+ H.getProfileLink().click();
+ H.popover().findByText(adminAppLinkText).click();
+
+ cy.findByTestId("admin-layout-sidebar")
+ .findByText("Custom visualizations")
+ .click();
+
+ cy.findByTestId("admin-layout-sidebar")
+ .findByText("Manage visualizations")
+ .should("be.visible")
+ .click();
- cy.log("make sure fallback is used after reload");
- cy.reload();
- cy.findByText("Custom visualizations").should("not.exist");
+ // Actions menu is only visible on row hover
+ H.main().findByText("demo-viz").realHover();
+ cy.findByRole("button", { name: "Plugin actions" }).click();
+ H.popover().findByText("Disable").click();
+ H.expectUnstructuredSnowplowEvent({
+ event: "custom_viz_plugin_toggled",
+ event_detail: "disabled",
});
- });
- });
- describe("deleting a plugin", () => {
- beforeEach(() => {
- H.activateToken("bleeding-edge");
- });
+ // Menu should now show "Enable" instead of "Disable"
+ H.main().findByText("demo-viz").realHover();
+ cy.findByRole("button", { name: "Plugin actions" }).click();
+ H.popover().findByText("Enable").should("be.visible");
- it("question should fall back when plugin is deleted", () => {
- H.resetSnowplow();
- H.enableTracking();
- H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ).then(() => {
- H.createQuestion(
- {
- name: "Custom Viz Delete Test",
- query: {
- "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,
- aggregation: [["count"]],
- },
- display: H.CUSTOM_VIZ_DISPLAY,
- },
- { wrapId: true, idAlias: "deleteCardId" },
- );
+ H.getProfileLink().click();
+ H.popover().findByText(mainAppLinkText).click();
- H.visitCustomVizSettings();
+ cy.get("main").within(() => {
+ cy.contains("Custom Viz Disable Test").click();
+ });
- // Delete the plugin (actions menu is only visible on row hover)
- H.main().findByText("demo-viz").realHover();
- cy.findByRole("button", { name: "Plugin actions" }).click();
- H.popover().findByText("Remove").click();
+ cy.log("make sure viz is table - fallback");
+ cy.findByTestId("table-root").should("be.visible");
- H.modal().within(() => {
- cy.findByText("Remove this visualization?").should("be.visible");
- cy.findByRole("button", { name: "Remove" }).click();
- });
+ // Custom viz section should not appear in chart type selector
+ cy.findByTestId("viz-type-button").click();
+ cy.findByTestId("Number-button").should("be.visible");
+ cy.findByText("Custom visualizations").should("not.exist");
- H.main()
- .findByText("You don't have any custom visualizations.")
- .should("be.visible");
- H.expectUnstructuredSnowplowEvent({
- event: "custom_viz_plugin_deleted",
- });
+ cy.log("make sure fallback is used after reload");
+ cy.reload();
+ cy.findByTestId("table-root").should("be.visible");
+ cy.findByTestId("viz-type-button").click();
+ cy.findByTestId("Number-button").should("be.visible");
+ cy.findByText("Custom visualizations").should("not.exist");
- // Visit the question — should fall back to table
- H.visitQuestion("@deleteCardId");
- cy.findByTestId("table-root").should("be.visible");
+ cy.log("Enable the plugin again, then remove it");
+ H.visitCustomVizSettings();
+ H.main().findByText("demo-viz").realHover();
+ cy.findByRole("button", { name: "Plugin actions" }).click();
+ H.popover().findByText("Enable").click();
+ H.expectUnstructuredSnowplowEvent({
+ event: "custom_viz_plugin_toggled",
+ event_detail: "enabled",
+ });
- // Custom viz section should not appear in chart type selector
- cy.findByTestId("viz-type-button").click();
- cy.findByText("Custom visualizations").should("not.exist");
- H.expectNoBadSnowplowEvents();
+ H.main().findByText("demo-viz").realHover();
+ cy.findByRole("button", { name: "Plugin actions" }).click();
+ H.popover().findByText("Remove").click();
+
+ H.modal().within(() => {
+ cy.findByText("Remove this visualization?").should("be.visible");
+ cy.findByRole("button", { name: "Remove" }).click();
+ });
+
+ H.main()
+ .findByText("You don't have any custom visualizations.")
+ .should("be.visible");
+ H.expectUnstructuredSnowplowEvent({
+ event: "custom_viz_plugin_deleted",
});
+
+ // Visit the question — should fall back to table
+ H.visitQuestion("@disableCardId");
+ cy.findByTestId("table-root").should("be.visible");
+
+ // Custom viz section should not appear in chart type selector
+ cy.findByTestId("viz-type-button").click();
+ cy.findByTestId("Number-button").should("be.visible");
+ cy.findByText("Custom visualizations").should("not.exist");
+ H.expectNoBadSnowplowEvents();
});
});
});
@@ -544,9 +490,11 @@ describe("admin > custom visualizations", () => {
H.updateSetting("csp-img-enabled", true);
H.updateSetting("custom-viz-enabled", true);
H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);
+ });
- // Default-view (table) Count-of-Orders card — demo-viz requires
- // exactly one row with one numeric column.
+ // Default-view (table) Count-of-Orders card — demo-viz requires
+ // exactly one row with one numeric column.
+ function createCountQuestion() {
H.createQuestion(
{
name: "Custom Viz Question Test",
@@ -558,7 +506,7 @@ describe("admin > custom visualizations", () => {
},
{ wrapId: true, idAlias: "questionId" },
);
- });
+ }
function switchToDemoViz() {
cy.findByTestId("viz-type-button").click();
@@ -568,7 +516,8 @@ describe("admin > custom visualizations", () => {
cy.findByTestId("viz-type-button").click();
}
- it("renders the selected custom viz for the question", () => {
+ it("renders the selected custom viz and persists its settings, pinned and across reloads", () => {
+ createCountQuestion();
H.resetSnowplow();
H.enableTracking();
H.visitQuestion("@questionId");
@@ -606,40 +555,142 @@ describe("admin > custom visualizations", () => {
H.expectUnstructuredSnowplowEvent({ event: "custom_viz_selected" });
H.expectNoBadSnowplowEvents();
- });
- it("persists the selected custom viz and its settings across reloads", () => {
- H.visitQuestion("@questionId");
- switchToDemoViz();
+ cy.log("onHover renders a tooltip");
+ cy.findByTestId("demo-viz-hover-target").realHover();
+ H.tooltip().should("contain.text", AGGREGATED_VALUE_FORMATTED);
+ H.queryBuilderHeader().realHover();
+ H.tooltip().should("not.exist");
+
+ cy.log(
+ "The plugin gets its own array-valued settings, including edits made in the session",
+ );
+ cy.findByTestId("demo-viz-columns").should("have.text", "Columns: count");
cy.findByTestId("viz-settings-button").click();
cy.findByTestId("chartsettings-sidebar")
- .findByPlaceholderText("Set threshold")
- .clear()
- .type("42")
- .blur();
+ .findByRole("button", { name: "Add column from plugin" })
+ .click();
+ cy.findByTestId("demo-viz-columns").should(
+ "have.text",
+ "Columns: count, extra",
+ );
+ cy.findByTestId("chartsettings-sidebar")
+ .findByRole("button", { name: "Add column from plugin" })
+ .should("be.visible");
+ cy.log("Plugin writes to Metabase settings stay inside its namespace");
+ cy.findByTestId("chartsettings-sidebar")
+ .findByRole("button", { name: "Rename question from plugin" })
+ .click();
+ H.main().findByText("Threshold: 7").should("be.visible");
H.saveSavedQuestion();
- cy.log("plugin settings are stored under the plugin's namespace");
cy.get("@questionId").then((id) => {
cy.request("GET", `/api/card/${id}`).then(({ body }) => {
expect(body.visualization_settings).to.have.property(
`custom:${H.CUSTOM_VIZ_IDENTIFIER}:threshold`,
- 42,
+ 7,
);
- expect(body.visualization_settings).not.to.have.property("threshold");
});
});
- H.interceptPluginBundle();
- cy.reload();
+ cy.findByTestId("chartsettings-sidebar")
+ .findByPlaceholderText("Set threshold")
+ .clear()
+ .type("42")
+ .blur();
+ H.main().findByText("Threshold: 42").should("be.visible");
+
+ cy.log(
+ "The column formatting popover opens from a field setting (metabase#78039)",
+ );
+ cy.findByTestId("chartsettings-sidebar")
+ .findByTestId("settings-count")
+ .click();
+
+ cy.findByTestId("chart-settings-widget-popover-content").within(() => {
+ cy.findByText("Add a prefix").should("be.visible");
+ cy.findByPlaceholderText("$").type("foo").blur();
+ });
+
+ H.main()
+ .findByTestId("demo-viz-formatted-value")
+ .should("contain", "foo");
+ cy.findByTestId("chartsettings-sidebar").findByText("Threshold").click();
+ cy.findByTestId("chart-settings-widget-popover-content").should(
+ "not.exist",
+ );
+
+ H.saveSavedQuestion();
+
+ cy.log("plugin settings are stored under the plugin's namespace");
+ cy.get("@questionId").then((id) => {
+ cy.request("GET", `/api/card/${id}`).then(({ body }) => {
+ expect(body.visualization_settings).to.have.property(
+ `custom:${H.CUSTOM_VIZ_IDENTIFIER}:threshold`,
+ 42,
+ );
+ expect(body.visualization_settings).to.have.property(
+ `custom:${H.CUSTOM_VIZ_IDENTIFIER}:card.title`,
+ "Plugin title",
+ );
+ expect(body.visualization_settings).to.have.deep.property(
+ `custom:${H.CUSTOM_VIZ_IDENTIFIER}:columns`,
+ ["count", "extra"],
+ );
+ expect(body.visualization_settings).not.to.have.property("threshold");
+ expect(body.visualization_settings).not.to.have.property(
+ "card.title",
+ );
+ });
+ });
+
+ cy.log("Reload only after the app leaves the unsaved question URL");
+ cy.location("hash").should("be.empty");
+ cy.location("pathname").should("match", /^\/question\/\d+/);
+ H.interceptPluginBundle();
+ cy.reload();
cy.wait("@pluginBundle");
H.main()
.findByText("Custom viz rendered successfully")
.should("be.visible");
H.main().findByText("Threshold: 42").should("be.visible");
+
+ // Default user locale is "en"
+ cy.findByTestId("demo-viz-locale").should("have.text", "Locale: en");
+
+ cy.log("A pinned custom-viz question renders in the collection view");
+ cy.get("@questionId").then((id) => {
+ cy.request("PUT", `/api/card/${id}`, { collection_position: 1 });
+ });
+
+ // Navigate to the collection via the question header's collection badge
+ cy.findByRole("link", { name: /Our analytics/ }).click();
+
+ H.getPinnedSection().within(() => {
+ cy.findByText("Custom Viz Question Test").should("be.visible");
+ cy.findByText("A question").should("be.visible");
+ });
+
+ cy.log(
+ "The plugin gets the user's locale and updates when the user changes it",
+ );
+ H.getPinnedSection().findByText("Custom Viz Question Test").click();
+ cy.findByTestId("demo-viz-locale").should("have.text", "Locale: en");
+
+ // Change the current user's locale to German. The plugin factory runs
+ // again on the next full page load with the new locale value.
+ cy.request("GET", "/api/user/current").then(({ body: user }) => {
+ cy.request("PUT", `/api/user/${user.id}`, { locale: "de" });
+ });
+
+ H.interceptPluginBundle();
+ cy.reload();
+ cy.wait("@pluginBundle");
+
+ cy.findByTestId("demo-viz-locale").should("have.text", "Locale: de");
});
it("reads and migrates plugin settings saved before namespacing", () => {
@@ -678,64 +729,6 @@ describe("admin > custom visualizations", () => {
});
});
- it("keeps plugin writes to Metabase settings inside the plugin's namespace", () => {
- H.visitQuestion("@questionId");
- switchToDemoViz();
-
- cy.findByTestId("viz-settings-button").click();
- cy.findByTestId("chartsettings-sidebar")
- .findByRole("button", { name: "Rename question from plugin" })
- .click();
- H.main().findByText("Threshold: 7").should("be.visible");
- H.saveSavedQuestion();
-
- cy.get("@questionId").then((id) => {
- cy.request("GET", `/api/card/${id}`).then(({ body }) => {
- expect(body.visualization_settings).to.have.property(
- `custom:${H.CUSTOM_VIZ_IDENTIFIER}:threshold`,
- 7,
- );
- expect(body.visualization_settings).to.have.property(
- `custom:${H.CUSTOM_VIZ_IDENTIFIER}:card.title`,
- "Plugin title",
- );
- expect(body.visualization_settings).not.to.have.property(
- "card.title",
- );
- });
- });
- });
-
- it("hands the plugin its own array-valued settings, including edits made in the session", () => {
- H.visitQuestion("@questionId");
- switchToDemoViz();
-
- cy.log("the default the plugin computes is an array");
- cy.findByTestId("demo-viz-columns").should("have.text", "Columns: count");
-
- cy.findByTestId("viz-settings-button").click();
- cy.findByTestId("chartsettings-sidebar")
- .findByRole("button", { name: "Add column from plugin" })
- .click();
- cy.findByTestId("demo-viz-columns").should(
- "have.text",
- "Columns: count, extra",
- );
- cy.findByTestId("chartsettings-sidebar")
- .findByRole("button", { name: "Add column from plugin" })
- .should("be.visible");
- H.saveSavedQuestion();
-
- cy.get("@questionId").then((id) => {
- cy.request("GET", `/api/card/${id}`).then(({ body }) => {
- expect(body.visualization_settings).to.have.deep.property(
- `custom:${H.CUSTOM_VIZ_IDENTIFIER}:columns`,
- ["count", "extra"],
- );
- });
- });
- });
-
it("keeps an unsaved question's custom viz after a browser reload (metabase#76065)", () => {
H.visitQuestionAdhoc({
dataset_query: {
@@ -748,6 +741,7 @@ describe("admin > custom visualizations", () => {
},
});
+ cy.findByTestId("scalar-value").should("be.visible");
switchToDemoViz();
H.main()
.findByText("Custom viz rendered successfully")
@@ -769,25 +763,6 @@ describe("admin > custom visualizations", () => {
cy.findByTestId("scalar-value").should("not.exist");
});
- it("opens the column formatting popover from a field setting (metabase#78039)", () => {
- H.visitQuestion("@questionId");
- switchToDemoViz();
-
- cy.findByTestId("viz-settings-button").click();
- cy.findByTestId("chartsettings-sidebar")
- .findByTestId("settings-count")
- .click();
-
- cy.findByTestId("chart-settings-widget-popover-content").within(() => {
- cy.findByText("Add a prefix").should("be.visible");
- cy.findByPlaceholderText("$").type("foo").blur();
- });
-
- H.main()
- .findByTestId("demo-viz-formatted-value")
- .should("contain", "foo");
- });
-
describe("errors", () => {
it("renders errors thrown by the plugin component", () => {
// Multi-column question — checkRenderable throws
@@ -809,30 +784,6 @@ describe("admin > custom visualizations", () => {
.should("be.visible");
});
- it("shows an error state when the plugin bundle fails to load", () => {
- cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", {
- statusCode: 500,
- body: "boom",
- }).as("failedBundle");
-
- H.createQuestion(
- {
- name: "Custom Viz — Failing Bundle",
- query: {
- "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,
- aggregation: [["count"]],
- },
- display: H.CUSTOM_VIZ_DISPLAY,
- },
- { visitQuestion: true },
- );
- cy.wait("@failedBundle");
-
- H.undoToastList()
- .findByText(/"demo-viz" visualization is currently unavailable/)
- .should("be.visible");
- });
-
it("shows a single combined toast when multiple plugin bundles fail to load (metabase#GDGT-3076)", () => {
H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ_2);
H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ_3_SECURITY);
@@ -843,6 +794,7 @@ describe("admin > custom visualizations", () => {
body: "boom",
}).as("failedBundle");
+ createCountQuestion();
H.visitQuestion("@questionId");
cy.findByTestId("viz-type-button").click();
cy.wait([
@@ -894,7 +846,7 @@ describe("admin > custom visualizations", () => {
.should("be.visible");
H.undoToastList()
- .findByText(/visualization is currently unavailable/i)
+ .findByText(/"demo-viz" visualization is currently unavailable/)
.should("be.visible");
cy.intercept(bundleMatcher, (req) => req.continue()).as(
@@ -909,7 +861,7 @@ describe("admin > custom visualizations", () => {
});
});
- it("falls back to the default viz on a public question (metabase#GDGT-2234)", () => {
+ it("falls back to the default viz on a public and an embedded question (metabase#GDGT-2234)", () => {
H.updateSetting("enable-public-sharing", true);
H.createQuestion(
@@ -924,27 +876,33 @@ describe("admin > custom visualizations", () => {
{ wrapId: true, idAlias: "publicQuestionId" },
);
- cy.get<CardId>("@publicQuestionId").then(H.visitPublicQuestion);
-
- cy.findByTestId("table-root").should("be.visible");
- });
-
- it("falls back to the default viz on an embedded question", () => {
- cy.get<CardId>("@questionId").then((questionId) => {
+ cy.get<CardId>("@publicQuestionId").then((questionId) => {
cy.request("PUT", `/api/card/${questionId}`, {
enable_embedding: true,
});
+ H.visitPublicQuestion(questionId);
+ });
+ cy.findByTestId("embed-frame").within(() => {
+ cy.findByTestId("table-root").should("be.visible");
+ cy.findByText("Custom viz rendered successfully").should("not.exist");
+ });
+
+ cy.get<CardId>("@publicQuestionId").then((questionId) => {
H.visitEmbeddedPage({
resource: { question: questionId },
params: {},
});
});
- cy.findByTestId("table-root").should("be.visible");
+ cy.findByTestId("embed-frame").within(() => {
+ cy.findByTestId("table-root").should("be.visible");
+ cy.findByText("Custom viz rendered successfully").should("not.exist");
+ });
});
it("calls onClick when the viz fires a click", () => {
+ createCountQuestion();
H.visitQuestion("@questionId");
switchToDemoViz();
@@ -1001,54 +959,6 @@ describe("admin > custom visualizations", () => {
.findByText("Custom viz rendered successfully")
.should("not.exist");
});
-
- it("calls onHover and renders a tooltip", () => {
- H.visitQuestion("@questionId");
- switchToDemoViz();
-
- cy.findByTestId("demo-viz-hover-target").realHover();
-
- H.tooltip().should("contain.text", AGGREGATED_VALUE_FORMATTED);
- });
-
- it("renders a pinned custom-viz question in the collection view", () => {
- H.visitQuestion("@questionId");
- switchToDemoViz();
- H.saveSavedQuestion();
-
- cy.get("@questionId").then((id) => {
- cy.request("PUT", `/api/card/${id}`, { collection_position: 1 });
- });
-
- // Navigate to the collection via the question header's collection badge
- cy.findByRole("link", { name: /Our analytics/ }).click();
-
- H.getPinnedSection().within(() => {
- cy.findByText("Custom Viz Question Test").should("be.visible");
- cy.findByText("A question").should("be.visible");
- });
- });
-
- it("passes the user's locale to the plugin and updates when the user changes it", () => {
- H.visitQuestion("@questionId");
- switchToDemoViz();
- H.saveSavedQuestion();
-
- // Default user locale is "en"
- cy.findByTestId("demo-viz-locale").should("have.text", "Locale: en");
-
- // Change the current user's locale to German. The plugin factory runs
- // again on the next full page load with the new locale value.
- cy.request("GET", "/api/user/current").then(({ body: user }) => {
- cy.request("PUT", `/api/user/${user.id}`, { locale: "de" });
- });
-
- H.interceptPluginBundle();
- cy.reload();
- cy.wait("@pluginBundle");
-
- cy.findByTestId("demo-viz-locale").should("have.text", "Locale: de");
- });
});
describe("using a plugin — dashboard", () => {
@@ -1076,37 +986,24 @@ describe("admin > custom visualizations", () => {
});
}
- it("renders a custom viz question on a dashboard", () => {
- createCustomVizDashboard().then(({ body: dashcard }) => {
- H.visitDashboard(dashcard.dashboard_id);
- });
-
- H.getDashboardCard()
- .findByText("Custom viz rendered successfully")
- .should("be.visible");
- H.getDashboardCard()
- .findByText(`Value: ${AGGREGATED_VALUE}`)
- .should("be.visible");
- });
-
- it("falls back to the default viz on a public dashboard (metabase#GDGT-2234)", () => {
+ it("falls back to the default viz on a public and an embedded dashboard (metabase#GDGT-2234)", () => {
H.updateSetting("enable-public-sharing", true);
- createCustomVizDashboard().then(({ body: dashcard }) => {
- H.visitPublicDashboard(Number(checkNotNull(dashcard.dashboard_id)));
- });
-
- H.getDashboardCard().findByTestId("table-root").should("be.visible");
- });
-
- it("falls back to the default viz on an embedded dashboard", () => {
createCustomVizDashboard().then(({ body: dashcard }) => {
const dashboardId = Number(checkNotNull(dashcard.dashboard_id));
-
+ cy.wrap(dashboardId).as("dashboardId");
cy.request("PUT", `/api/dashboard/${dashboardId}`, {
enable_embedding: true,
});
+ H.visitPublicDashboard(dashboardId);
+ });
+
+ H.getDashboardCard().findByTestId("table-root").should("be.visible");
+ H.getDashboardCard()
+ .findByText("Custom viz rendered successfully")
+ .should("not.exist");
+ cy.get<DashboardId>("@dashboardId").then((dashboardId) => {
H.visitEmbeddedPage({
resource: { dashboard: dashboardId },
params: {},
@@ -1114,9 +1011,12 @@ describe("admin > custom visualizations", () => {
});
H.getDashboardCard().findByTestId("table-root").should("be.visible");
+ H.getDashboardCard()
+ .findByText("Custom viz rendered successfully")
+ .should("not.exist");
});
- it("exports the dashboard as a PDF", () => {
+ it("renders a custom viz question on a dashboard, shows a tooltip, exports a PDF and drills through on click", () => {
cy.deleteDownloadsFolder();
createCustomVizDashboard({ name: "custom viz pdf dash" }).then(
@@ -1124,197 +1024,181 @@ describe("admin > custom visualizations", () => {
H.visitDashboard(dashcard.dashboard_id);
},
);
+
H.getDashboardCard()
.findByText("Custom viz rendered successfully")
.should("be.visible");
+ H.getDashboardCard()
+ .findByText(`Value: ${AGGREGATED_VALUE}`)
+ .should("be.visible");
+ cy.log("Tooltip on hover");
+ H.getDashboardCard().findByTestId("demo-viz-hover-target").realHover();
+ H.tooltip().should("contain.text", AGGREGATED_VALUE_FORMATTED);
+ cy.findByTestId("dashboard-header").realHover();
+ H.tooltip().should("not.exist");
+
+ cy.log("Export as PDF");
H.openSharingMenu("Export as PDF");
cy.findByTestId("status-root-container")
.should("contain", "Downloading")
.and("contain", "Dashboard for custom viz pdf dash");
cy.verifyDownload("custom viz pdf dash.pdf", { contains: true });
- });
-
- it("shows a tooltip on hover over the custom viz in a dashcard", () => {
- createCustomVizDashboard().then(({ body: dashcard }) => {
- H.visitDashboard(dashcard.dashboard_id);
- });
-
- H.getDashboardCard().findByTestId("demo-viz-hover-target").realHover();
-
- H.tooltip().should("contain.text", AGGREGATED_VALUE_FORMATTED);
- });
-
- it("drills through on click from a dashcard", () => {
- createCustomVizDashboard().then(({ body: dashcard }) => {
- H.visitDashboard(dashcard.dashboard_id);
- });
- H.getDashboardCard()
- .findByText("Custom viz rendered successfully")
- .should("be.visible");
+ cy.log("Drill through on click");
drillThroughDemoVizClick();
H.queryBuilderHeader().findByText("Orders").should("be.visible");
// The demo plugin's query is `count(Orders)` with no breakout, so the
// underlying-records drill produces an unfiltered Orders query.
- H.queryBuilderFiltersPanel().should("not.exist");
H.tableInteractive().findByText("37.65").should("be.visible");
+ H.queryBuilderFiltersPanel().should("not.exist");
});
- describe("click behavior: custom destinations", () => {
- it("navigates to another dashboard", () => {
- H.createDashboard(
- { name: "Custom Viz Target Dashboard" },
- { wrapId: true, idAlias: "targetDashboardId" },
- );
-
- cy.get<DashboardId>("@targetDashboardId").then((targetDashboardId) => {
- createCustomVizDashboard().then(({ body: dashcard }) => {
- H.addOrUpdateDashboardCard({
- dashboard_id: dashcard.dashboard_id,
- card_id: checkNotNull(dashcard.card_id),
- card: {
- id: dashcard.id,
- visualization_settings: {
- click_behavior: {
- parameterMapping: {},
- targetId: targetDashboardId,
- linkType: "dashboard",
- type: "link",
- },
- },
- },
- });
- H.visitDashboard(dashcard.dashboard_id);
- });
-
- H.getDashboardCard().findByTestId("demo-viz-click-target").click();
+ it("follows click behavior custom destinations: URL, crossfilter, saved question and dashboard", () => {
+ const parameter: Parameter = {
+ id: "12345678",
+ name: "Count",
+ slug: "count",
+ type: "number/=",
+ };
- cy.location("pathname").should(
- "match",
- new RegExp(`^/dashboard/${targetDashboardId}(?:-|$)`),
- );
- });
- });
-
- it("navigates to a saved question", () => {
- H.createQuestion(
- {
- name: "Custom Viz Target Question",
- query: {
- "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,
- limit: 5,
- },
+ H.createDashboard(
+ { name: "Custom Viz Target Dashboard" },
+ { wrapId: true, idAlias: "targetDashboardId" },
+ );
+ H.createQuestion(
+ {
+ name: "Custom Viz Target Question",
+ query: {
+ "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,
+ limit: 5,
},
- { wrapId: true, idAlias: "targetQuestionId" },
- );
+ },
+ { wrapId: true, idAlias: "targetQuestionId" },
+ );
+ cy.get<DashboardId>("@targetDashboardId").then((targetDashboardId) => {
cy.get<CardId>("@targetQuestionId").then((targetQuestionId) => {
- createCustomVizDashboard().then(({ body: dashcard }) => {
- H.addOrUpdateDashboardCard({
+ H.createQuestionAndDashboard({
+ questionDetails: customVizQuestionDetails,
+ dashboardDetails: {
+ name: "Custom Viz Click Behavior Dashboard",
+ parameters: [parameter],
+ },
+ }).then(({ body: dashcard }) => {
+ const card_id = checkNotNull(dashcard.card_id);
+ H.updateDashboardCards({
dashboard_id: dashcard.dashboard_id,
- card_id: checkNotNull(dashcard.card_id),
- card: {
- id: dashcard.id,
- visualization_settings: {
- click_behavior: {
- parameterMapping: {},
- targetId: targetQuestionId,
- linkType: "question",
- type: "link",
+ cards: [
+ {
+ card_id,
+ row: 0,
+ col: 0,
+ visualization_settings: {
+ click_behavior: {
+ linkType: "url",
+ linkTemplate: "https://metabase.test/custom-viz",
+ type: "link",
+ },
},
},
- },
+ {
+ card_id,
+ row: 0,
+ col: 12,
+ visualization_settings: {
+ click_behavior: {
+ type: "crossfilter",
+ parameterMapping: {
+ [parameter.id]: {
+ id: parameter.id,
+ source: {
+ id: "count",
+ name: "Count",
+ type: "column",
+ },
+ target: { id: parameter.id, type: "parameter" },
+ },
+ },
+ },
+ },
+ },
+ {
+ card_id,
+ row: 8,
+ col: 0,
+ visualization_settings: {
+ click_behavior: {
+ parameterMapping: {},
+ targetId: targetQuestionId,
+ linkType: "question",
+ type: "link",
+ },
+ },
+ },
+ {
+ card_id,
+ row: 8,
+ col: 12,
+ visualization_settings: {
+ click_behavior: {
+ parameterMapping: {},
+ targetId: targetDashboardId,
+ linkType: "dashboard",
+ type: "link",
+ },
+ },
+ },
+ ],
});
H.visitDashboard(dashcard.dashboard_id);
});
- H.getDashboardCard().findByTestId("demo-viz-click-target").click();
+ cy.log("Open a URL");
+ const anchorClick = cy.stub();
+ H.onNextAnchorClick((anchor: HTMLAnchorElement) =>
+ anchorClick(anchor.href),
+ );
+ H.getDashboardCard(0).findByTestId("demo-viz-click-target").click();
+ cy.wrap(anchorClick).should(
+ "have.been.calledOnceWith",
+ "https://metabase.test/custom-viz",
+ );
+ cy.log("Update a dashboard filter");
+ H.getDashboardCard(1)
+ .findByText(/Value: \d+/)
+ .should("be.visible");
+ H.getDashboardCard(1).findByTestId("demo-viz-click-target").click();
+ // The crossfilter behavior sets the dashboard parameter to the value
+ // of the clicked column.
+ cy.location("search").should(
+ "include",
+ `${parameter.slug}=${AGGREGATED_VALUE}`,
+ );
+
+ cy.log("Navigate to a saved question");
+ H.getDashboardCard(2).findByTestId("demo-viz-click-target").click();
cy.location("pathname").should(
"match",
new RegExp(`^/question/${targetQuestionId}(?:-|$)`),
);
- });
- });
+ H.tableInteractive().should("be.visible");
- it("opens a URL", () => {
- createCustomVizDashboard().then(({ body: dashcard }) => {
- H.addOrUpdateDashboardCard({
- dashboard_id: dashcard.dashboard_id,
- card_id: checkNotNull(dashcard.card_id),
- card: {
- id: dashcard.id,
- visualization_settings: {
- click_behavior: {
- linkType: "url",
- linkTemplate: "https://metabase.test/custom-viz",
- type: "link",
- },
- },
- },
- });
- H.visitDashboard(dashcard.dashboard_id);
- });
+ cy.go("back");
+ cy.location("pathname").should("match", /^\/dashboard\//);
- H.onNextAnchorClick((anchor: HTMLAnchorElement) => {
- expect(anchor).to.have.attr(
- "href",
- "https://metabase.test/custom-viz",
+ cy.log("Navigate to another dashboard");
+ H.getDashboardCard(3)
+ .findByText("Custom viz rendered successfully")
+ .should("be.visible");
+ H.getDashboardCard(3).findByTestId("demo-viz-click-target").click();
+ cy.location("pathname").should(
+ "match",
+ new RegExp(`^/dashboard/${targetDashboardId}(?:-|$)`),
);
});
- H.getDashboardCard().findByTestId("demo-viz-click-target").click();
- });
-
- it("updates a dashboard filter", () => {
- const parameter: Parameter = {
- id: "12345678",
- name: "Count",
- slug: "count",
- type: "number/=",
- };
-
- H.createQuestionAndDashboard({
- questionDetails: customVizQuestionDetails,
- dashboardDetails: {
- name: "Custom Viz Crossfilter Dashboard",
- parameters: [parameter],
- },
- }).then(({ body: dashcard }) => {
- H.addOrUpdateDashboardCard({
- dashboard_id: dashcard.dashboard_id,
- card_id: checkNotNull(dashcard.card_id),
- card: {
- id: dashcard.id,
- visualization_settings: {
- click_behavior: {
- type: "crossfilter",
- parameterMapping: {
- [parameter.id]: {
- id: parameter.id,
- source: { id: "count", name: "Count", type: "column" },
- target: { id: parameter.id, type: "parameter" },
- },
- },
- },
- },
- },
- });
- H.visitDashboard(dashcard.dashboard_id);
- });
-
- H.getDashboardCard()
- .findByText(/Value: \d+/)
- .should("be.visible");
- H.getDashboardCard().findByTestId("demo-viz-click-target").click();
-
- // The crossfilter behavior sets the dashboard parameter to the value of
- // the clicked column.
- cy.location("search").should(
- "include",
- `${parameter.slug}=${AGGREGATED_VALUE}`,
- );
});
});
});
@@ -1339,11 +1223,6 @@ describe("admin > custom visualizations", () => {
},
{ wrapId: true, idAlias: "questionId" },
);
-
- // Query the card once so it appears in the /chart command's recent list.
- cy.get<CardId>("@questionId").then((cardId) => {
- cy.request("POST", `/api/card/${cardId}/query`);
- });
});
describe("regular documents", () => {
@@ -1358,21 +1237,13 @@ describe("admin > custom visualizations", () => {
});
});
- it("renders the custom viz when the document is opened", () => {
- H.interceptPluginBundle();
- H.visitDocument("@documentId");
- cy.wait("@pluginBundle");
-
- H.getDocumentCard(DOC_QUESTION_NAME).within(() => {
- cy.findByText("Custom viz rendered successfully").should(
- "be.visible",
- );
- cy.findByText(/Value: \d+/).should("be.visible");
- });
- });
+ it("falls back to the default visualization when the plugin bundle fails to load, then renders the custom viz when the document is opened again", () => {
+ const bundleMatcher = {
+ method: "GET",
+ pathname: "/api/ee/custom-viz-plugin/*/bundle",
+ };
- it("falls back to the default visualization when the plugin bundle fails to load", () => {
- cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", {
+ cy.intercept(bundleMatcher, {
statusCode: 500,
body: "boom",
}).as("failedBundle");
@@ -1381,14 +1252,32 @@ describe("admin > custom visualizations", () => {
cy.wait("@failedBundle");
H.getDocumentCard(DOC_QUESTION_NAME).within(() => {
- cy.findByText("Custom viz rendered successfully").should("not.exist");
cy.findByTestId("table-root").should("be.visible");
+ cy.findByText("Custom viz rendered successfully").should("not.exist");
+ });
+
+ cy.intercept(bundleMatcher, (req) => req.continue()).as(
+ "bundleRestored",
+ );
+ cy.reload();
+ cy.wait("@bundleRestored");
+
+ H.getDocumentCard(DOC_QUESTION_NAME).within(() => {
+ cy.findByText("Custom viz rendered successfully").should(
+ "be.visible",
+ );
+ cy.findByText(/Value: \d+/).should("be.visible");
});
});
});
describe("inserting via / command", () => {
beforeEach(() => {
+ // Query the card once so it appears in the /chart command's recent list.
+ cy.get<CardId>("@questionId").then((cardId) => {
+ cy.request("POST", `/api/card/${cardId}/query`);
+ });
+
H.createDocument({
name: "Empty Doc",
document: {
@@ -1514,18 +1403,6 @@ describe("admin > custom visualizations", () => {
});
});
- it("renders the custom-viz icon in the entity picker data-source modal", () => {
- H.startNewQuestion();
- H.miniPickerBrowseAll().click();
-
- H.entityPickerModal().within(() => {
- H.entityPickerModalItem(0, "Our analytics").click();
- H.entityPickerModalItem(1, ICON_QUESTION_NAME)
- .find(PLUGIN_ICON_SELECTOR)
- .should("exist");
- });
- });
-
it("renders the custom-viz icon across app surfaces when navigating through the UI", () => {
H.interceptPluginBundle();
@@ -1586,6 +1463,18 @@ describe("admin > custom visualizations", () => {
.find(PLUGIN_ICON_SELECTOR)
.should("exist");
+ cy.log("Entity picker data-source modal, reached via New → Question");
+ H.newButton("Question").click();
+ H.miniPickerBrowseAll().click();
+ H.entityPickerModal().within(() => {
+ H.entityPickerModalItem(0, "Our analytics").click();
+ H.entityPickerModalItem(1, ICON_QUESTION_NAME)
+ .find(PLUGIN_ICON_SELECTOR)
+ .should("exist");
+ });
+ cy.realPress("Escape");
+ H.entityPickerModal().should("not.exist");
+
cy.log("Navigate → dashboard via bookmark link in the nav sidebar");
H.openNavigationSidebar();
H.navigationSidebar()
@@ -1657,8 +1546,6 @@ describe("admin > custom visualizations", () => {
let devServerPid: number | null = null;
beforeEach(() => {
- H.restore("postgres-writable");
- cy.signInAsAdmin();
H.activateToken("bleeding-edge");
H.updateSetting("csp-img-enabled", true);
H.updateSetting("custom-viz-enabled", true);
@@ -1817,7 +1704,7 @@ describe("admin > custom visualizations", () => {
describe("sandbox", () => {
beforeEach(() => {
- H.restore("postgres-writable");
+ H.restore();
cy.signInAsAdmin();
H.activateToken("bleeding-edge");
H.updateSetting("csp-img-enabled", true);
@@ -1843,21 +1730,11 @@ describe("sandbox", () => {
name: string;
payload: string;
errorPattern: RegExp;
- before?: () => void;
- additionalAssertions?: () => void;
}> = [
{
name: "window.fetch",
payload: 'window.fetch("/api/canary-should-be-blocked-by-sandbox");',
errorPattern: blockedPattern(/API call: window\.fetch/),
- before: () => {
- cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
- "canary",
- );
- },
- additionalAssertions: () => {
- cy.get("@canary.all").should("have.length", 0);
- },
},
{
name: "document.open",
@@ -2006,14 +1883,6 @@ describe("sandbox", () => {
payload:
"eval('window.fetch(\"/api/canary-should-be-blocked-by-sandbox\")');",
errorPattern: blockedPattern(/API call: window\.fetch/),
- before: () => {
- cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
- "canary",
- );
- },
- additionalAssertions: () => {
- cy.get("@canary.all").should("have.length", 0);
- },
},
{
name: "XMLHttpRequest",
@@ -2029,14 +1898,6 @@ describe("sandbox", () => {
name: "window.open",
payload: 'window.open("/api/canary-should-be-blocked-by-sandbox");',
errorPattern: blockedPattern(/API call: window\.open/),
- before: () => {
- cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
- "canary",
- );
- },
- additionalAssertions: () => {
- cy.get("@canary.all").should("have.length", 0);
- },
},
{
name: "document.write",
@@ -2064,14 +1925,6 @@ describe("sandbox", () => {
payload:
'window.fetch.bind(window)("/api/canary-should-be-blocked-by-sandbox");',
errorPattern: blockedPattern(/API call: window\.fetch/),
- before: () => {
- cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
- "canary",
- );
- },
- additionalAssertions: () => {
- cy.get("@canary.all").should("have.length", 0);
- },
},
{
// Try to bypass via Function.prototype.bind.call. Confirms the check
@@ -2080,14 +1933,6 @@ describe("sandbox", () => {
payload:
'Function.prototype.bind.call(window.fetch, window)("/api/canary-should-be-blocked-by-sandbox");',
errorPattern: blockedPattern(/API call: window\.fetch/),
- before: () => {
- cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
- "canary",
- );
- },
- additionalAssertions: () => {
- cy.get("@canary.all").should("have.length", 0);
- },
},
{
name: "Worker constructor",
@@ -2177,14 +2022,6 @@ describe("sandbox", () => {
payload:
'new FontFace("x", "url(/api/canary-should-be-blocked-by-sandbox)").load();',
errorPattern: blockedPattern(/API call: FontFace\.load/),
- before: () => {
- cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
- "canary",
- );
- },
- additionalAssertions: () => {
- cy.get("@canary.all").should("have.length", 0);
- },
},
{
name: "document.adoptedStyleSheets setter",
@@ -2315,9 +2152,13 @@ describe("sandbox", () => {
it("blocks browser APIs that are not allowed in the sandbox", () => {
const bundle = SANDBOX_CASES.map((c, index) => {
const delay = 1000 + index * 100;
- return `window.setTimeout(function() { try { ${c.payload} } catch (e) { console.error(e); } }, ${delay});`;
+ return `window.setTimeout(function() { try { ${c.payload} } catch (e) { console.error(${JSON.stringify(c.name)}, e); } }, ${delay});`;
}).join("\n");
+ cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
+ "canary",
+ );
+
cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
req.continue((res) => {
res.body = `console.log("injected bundle");${bundle}\n${String(res.body)};\n`;
@@ -2333,20 +2174,15 @@ describe("sandbox", () => {
cy.wait("@injectedBundle");
cy.get("@consoleLog").should("be.calledWith", "injected bundle");
- for (const {
- name,
- errorPattern,
- before,
- additionalAssertions,
- } of SANDBOX_CASES) {
- before?.();
+ for (const { name, errorPattern } of SANDBOX_CASES) {
cy.log(`Verifying error pattern for: ${name}`);
cy.get("@consoleError").should(
- "have.been.calledWithMatch",
+ "have.been.calledWith",
+ name,
Cypress.sinon.match.has("message", Cypress.sinon.match(errorPattern)),
);
- additionalAssertions?.();
}
+ cy.get("@canary.all").should("have.length", 0);
});
// `window.location` and the Location attributes are `[LegacyUnforgeable]`,
@@ -2364,9 +2200,13 @@ describe("sandbox", () => {
'location.hash = "#attacker-pwned";',
];
// Run inline in the bundle preamble. Each is wrapped in try/catch so an
- // attempt that errors doesn't short-circuit the rest.
+ // attempt that errors doesn't short-circuit the rest, and logs whether it
+ // ran to the end or threw.
const attackBundle = payloads
- .map((p) => `try { ${p} } catch (e) {}`)
+ .map(
+ (p, index) =>
+ `try { ${p}; console.log("plugin location op", ${index}, "ran"); } catch (e) { console.log("plugin location op", ${index}, "threw"); }`,
+ )
.join("\n");
cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
@@ -2376,170 +2216,68 @@ describe("sandbox", () => {
});
}).as("injectedBundle");
- H.visitQuestion("@sandboxCardId");
- cy.wait("@injectedBundle");
-
- cy.findByRole("heading", {
- name: "Custom viz rendered successfully",
- }).should("be.visible");
-
- cy.location("pathname").should("match", /\/question/);
- cy.location("href").then((href) => {
- expect(href).not.to.include("attacker");
- });
- cy.location("search").should("not.contain", "attacker-pwned");
- cy.location("hash").should("not.contain", "attacker-pwned");
- });
-
- // innerHTML/outerHTML/insertAdjacentHTML go through DOMPurify rather than
- // being blocked outright, so this case doesn't fit the "expect a thrown
- // error and a fallback viz" shape of SANDBOX_CASES. Instead we inject an
- // <img onerror> — which the browser would execute in the host realm if it
- // survived assignment — and confirm DOMPurify stripped it by checking the
- // onerror's side effect (a fetch to the canary URL) never happens.
- it("sanitizes innerHTML through DOMPurify before it reaches the DOM", () => {
- cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
- "canary",
- );
-
- const payload = `
- var d = document.createElement('div');
- d.innerHTML = '<img src="x" onerror="fetch(\\'/api/canary-should-be-blocked-by-sandbox\\')">';
- document.body.appendChild(d);
- `;
-
- cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
- req.continue((res) => {
- res.body = `${payload}\n${String(res.body)};\n`;
- res.send();
- });
- }).as("injectedBundle");
-
H.visitQuestion("@sandboxCardId", {
onBeforeLoad(win) {
cy.spy(win.console, "log").as("consoleLog");
- cy.spy(win.console, "error").as("consoleError");
},
});
cy.wait("@injectedBundle");
- // Viz still renders — sanitization mutates the HTML but doesn't throw.
cy.findByRole("heading", {
name: "Custom viz rendered successfully",
}).should("be.visible");
- cy.get("@canary.all").should("have.length", 0);
- cy.get("@consoleError").should(
- "have.been.calledWithMatch",
- /\[plugin \d+\] DOMPurify stripped content from innerHTML/,
- );
- });
-
- it("sanitizes ShadowRoot.innerHTML through DOMPurify before it reaches the DOM", () => {
- cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
- "canary",
- );
-
- const payload = `
- var host = document.createElement('div');
- var shadow = host.attachShadow({ mode: 'open' });
- shadow.innerHTML = '<img src="x" onerror="fetch(\\'/api/canary-should-be-blocked-by-sandbox\\')">';
- document.body.appendChild(host);
- `;
-
- cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
- req.continue((res) => {
- res.body = `${payload}\n${String(res.body)};\n`;
- res.send();
- });
- }).as("injectedBundle");
-
- H.visitQuestion("@sandboxCardId", {
- onBeforeLoad(win) {
- cy.spy(win.console, "log").as("consoleLog");
- cy.spy(win.console, "error").as("consoleError");
- },
+ payloads.forEach((_payload, index) => {
+ cy.get("@consoleLog").should(
+ "have.been.calledWith",
+ "plugin location op",
+ index,
+ );
});
- cy.wait("@injectedBundle");
- cy.findByRole("heading", {
- name: "Custom viz rendered successfully",
- }).should("be.visible");
- cy.get("@canary.all").should("have.length", 0);
- cy.get("@consoleError").should(
- "have.been.calledWithMatch",
- /\[plugin \d+\] DOMPurify stripped content from ShadowRoot\.innerHTML/,
- );
+ cy.location("pathname").should("match", /\/question/);
+ cy.location("href").should("not.include", "attacker");
+ cy.location("search").should("not.contain", "attacker-pwned");
+ cy.location("hash").should("not.contain", "attacker-pwned");
});
- // `Document` is itself a Node, so it's a valid root for TreeWalker /
- // NodeIterator and a valid target for `MutationObserver.observe`. With
- // an Element-only decoy, the plugin could pass `document` as the root
- // and walk the entire host DOM, surfacing real host Text nodes that
- // weren't decoyed. Locking this down requires the Node-level decoy.
- it("decoys non-Element nodes reached via TreeWalker rooted at document", () => {
- const HOST_MARKER_TEXT = "treewalker-host-canary-do-not-leak";
-
- const payload = `
- setTimeout(function() {
- var walker = document.createTreeWalker(document, NodeFilter.SHOW_TEXT);
- var sawMarker = false;
- var node;
- let nonEmptyCount = 0;
- while ((node = walker.nextNode())) {
- if ((node.textContent || "").indexOf(${JSON.stringify(HOST_MARKER_TEXT)}) !== -1) {
- sawMarker = true;
- break;
- }
- if (node.textContent && node.textContent.trim() !== "") {
- nonEmptyCount++;
- }
+ // innerHTML/outerHTML/insertAdjacentHTML go through DOMPurify rather than
+ // being blocked outright, so these cases don't fit the "expect a thrown
+ // error" shape of SANDBOX_CASES. Instead we inject an <img onerror> — which
+ // the browser would execute in the host realm if it survived assignment —
+ // and confirm DOMPurify stripped it by checking the onerror's side effect
+ // (a fetch to the canary URL) never happens.
+ //
+ // Host-app globals: direct access is closed by near-membrane-dom's default
+ // behavior: it remaps only the own keys of a fresh sandbox iframe's window
+ // from host to plugin.
+ //
+ // Each payload runs in its own function scope, logs distinct messages and
+ // touches a fresh decoy, so they share one page load.
+ it("sanitizes HTML, hides host globals and returns decoys for out-of-scope DOM access", () => {
+ const hostSelector = "#root";
+ const preamble = `
+ (function() {
+ var d = document.createElement('div');
+ d.innerHTML = '<img src="x" onerror="fetch(\\'/api/canary-should-be-blocked-by-sandbox\\')">';
+ document.body.appendChild(d);
+ })();
+ (function() {
+ var host = document.createElement('div');
+ var shadow = host.attachShadow({ mode: 'open' });
+ shadow.innerHTML = '<img src="x" onerror="fetch(\\'/api/canary-should-be-blocked-by-sandbox\\')">';
+ document.body.appendChild(host);
+ })();
+ (function() {
+ var hostEl = document.querySelector('${hostSelector}');
+ if (hostEl) {
+ const elementId = hostEl.getAttribute("id");
+ hostEl.setAttribute('data-pwned-by-plugin', 'true');
+ console.log('plugin read element id', elementId);
+ console.log('plugin saw decoy', hostEl.getAttribute('data-plugin-sandbox-decoy'));
+ } else {
+ console.log('plugin-saw-decoy', false);
}
- console.log('plugin treewalker(document) saw host marker:', sawMarker);
- console.log('plugin treewalker(document) saw non-empty nodes:', nonEmptyCount);
- }, 1500);
- `;
-
- cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
- req.continue((res) => {
- res.body = `${payload}\n${String(res.body)};\n`;
- res.send();
- });
- }).as("injectedBundle");
-
- H.visitQuestion("@sandboxCardId", {
- onBeforeLoad(win) {
- cy.spy(win.console, "log").as("consoleLog");
- },
- });
- cy.wait("@injectedBundle");
-
- cy.window().then((win) => {
- const marker = win.document.createElement("span");
- marker.id = "treewalker-host-marker";
- marker.textContent = HOST_MARKER_TEXT;
- win.document.body.appendChild(marker);
- });
-
- cy.findByRole("heading", {
- name: "Custom viz rendered successfully",
- }).should("be.visible");
-
- cy.get("@consoleLog").should(
- "have.been.calledWith",
- "plugin treewalker(document) saw host marker:",
- false,
- );
- cy.get("@consoleLog").should(
- "have.been.calledWith",
- "plugin treewalker(document) saw non-empty nodes:",
- 27,
- );
- });
-
- // Direct access is closed by near-membrane-dom's default behavior: it
- // remaps only the own keys of a fresh sandbox iframe's window from host to plugin.
- it("does not expose host-app globals to the plugin", () => {
- const payload = `
+ })();
setTimeout(function() {
console.log("plugin sees MetabaseBootstrap:", typeof window.MetabaseBootstrap);
try {
@@ -2564,10 +2302,30 @@ describe("sandbox", () => {
console.log("plugin sees SECRET:", typeof window.SECRET);
}, 500);
`;
+ // Runs after the bundle so the plugin container exists.
+ const epilogue = `
+ setTimeout(function() {
+ var container = document.querySelector('[data-plugin-sandbox]');
+ if (!container) {
+ console.log('plugin parent test:', 'no container');
+ return;
+ }
+ const { parentElement, parentNode} = container;
+ console.log('plugin parentElement decoy:', parentElement && parentElement.getAttribute('data-plugin-sandbox-decoy'));
+ console.log('plugin parentElement id:', parentElement && parentElement.getAttribute('id'));
+ console.log('plugin parentNode decoy:', parentNode && parentNode.getAttribute && parentNode.getAttribute('data-plugin-sandbox-decoy'));
+ if (parentElement) {
+ parentElement.setAttribute('data-pwned-by-plugin', 'true');
+ }
+ }, 1000);
+ `;
+ cy.intercept("GET", "/api/canary-should-be-blocked-by-sandbox").as(
+ "canary",
+ );
cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
req.continue((res) => {
- res.body = `${payload}\n${String(res.body)};\n`;
+ res.body = `${preamble}\n${String(res.body)};\n${epilogue}`;
res.send();
});
}).as("injectedBundle");
@@ -2575,18 +2333,37 @@ describe("sandbox", () => {
H.visitQuestion("@sandboxCardId", {
onBeforeLoad(win) {
cy.spy(win.console, "log").as("consoleLog");
+ cy.spy(win.console, "error").as("consoleError");
+ // @ts-expect-error - test window property
+ win.SECRET = "abracadabra";
},
});
- cy.window().then((win) => {
- // @ts-expect-error - test window property
- win.SECRET = "abracadabra";
- });
cy.wait("@injectedBundle");
+ // Viz still renders — sanitization mutates the HTML but doesn't throw.
cy.findByRole("heading", {
name: "Custom viz rendered successfully",
}).should("be.visible");
+ cy.log("DOMPurify strips the onerror handler");
+ cy.get("@consoleError").should(
+ "have.been.calledWithMatch",
+ /\[plugin \d+\] DOMPurify stripped content from innerHTML/,
+ );
+ cy.get("@consoleError").should(
+ "have.been.calledWithMatch",
+ /\[plugin \d+\] DOMPurify stripped content from ShadowRoot\.innerHTML/,
+ );
+ cy.get("@canary.all").should("have.length", 0);
+
+ cy.log("The host realm has these globals, the plugin does not");
+ cy.window().its("SECRET").should("eq", "abracadabra");
+ cy.window().its("MetabaseBootstrap").should("exist");
+ cy.get("@consoleLog").should(
+ "have.been.calledWith",
+ "plugin sees SECRET:",
+ "undefined",
+ );
cy.get("@consoleLog").should(
"have.been.calledWith",
"plugin sees MetabaseBootstrap:",
@@ -2612,42 +2389,10 @@ describe("sandbox", () => {
"plugin sees MetabaseSiteLocalization:",
"undefined",
);
- });
- it("isolates DOM access to the plugin subtree (out-of-scope reads and writes hit a decoy)", () => {
- const hostSelector = "#root";
- const payload = `
- var hostEl = document.querySelector('${hostSelector}');
- if (hostEl) {
- const elementId = hostEl.getAttribute("id");
- hostEl.setAttribute('data-pwned-by-plugin', 'true');
- console.log('plugin read element id', elementId);
- console.log('plugin saw decoy', hostEl.getAttribute('data-plugin-sandbox-decoy'));
- } else {
- console.log('plugin-saw-decoy', false);
- }
- `;
-
- cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
- req.continue((res) => {
- res.body = `${payload}\n${String(res.body)};\n`;
- res.send();
- });
- }).as("injectedBundle");
-
- H.visitQuestion("@sandboxCardId", {
- onBeforeLoad(win) {
- cy.spy(win.console, "log").as("consoleLog");
- },
- });
- cy.wait("@injectedBundle");
-
- cy.findByRole("heading", {
- name: "Custom viz rendered successfully",
- }).should("be.visible");
-
- // The plugin reached for visualization-root but received a decoy with
- // data-plugin-sandbox-decoy="true" instead of the real element.
+ cy.log(
+ "The plugin reached for #root but received a decoy with data-plugin-sandbox-decoy=true",
+ );
cy.get("@consoleLog").should(
"have.been.calledWith",
"plugin saw decoy",
@@ -2658,47 +2403,11 @@ describe("sandbox", () => {
"plugin read element id",
"sandbox-decoy",
);
-
- // The real host element was untouched.
cy.get(hostSelector).should("not.have.attr", "data-pwned-by-plugin");
- });
-
- it("returns a decoy when the plugin walks up to its container's parentElement/parentNode", () => {
- const payload = `
- setTimeout(function() {
- var container = document.querySelector('[data-plugin-sandbox]');
- if (!container) {
- console.log('plugin parent test:', 'no container');
- return;
- }
- const { parentElement, parentNode} = container;
- console.log('plugin parentElement decoy:', parentElement && parentElement.getAttribute('data-plugin-sandbox-decoy'));
- console.log('plugin parentElement id:', parentElement && parentElement.getAttribute('id'));
- console.log('plugin parentNode decoy:', parentNode && parentNode.getAttribute && parentNode.getAttribute('data-plugin-sandbox-decoy'));
- if (parentElement) {
- parentElement.setAttribute('data-pwned-by-plugin', 'true');
- }
- }, 1000);
- `;
-
- cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
- req.continue((res) => {
- res.body = `${String(res.body)};\n${payload}`;
- res.send();
- });
- }).as("injectedBundle");
-
- H.visitQuestion("@sandboxCardId", {
- onBeforeLoad(win) {
- cy.spy(win.console, "log").as("consoleLog");
- },
- });
- cy.wait("@injectedBundle");
-
- cy.findByRole("heading", {
- name: "Custom viz rendered successfully",
- }).should("be.visible");
+ cy.log(
+ "The plugin walked up to its container's parentElement/parentNode and received a decoy",
+ );
cy.get("@consoleLog").should(
"have.been.calledWith",
"plugin parentElement decoy:",
@@ -2714,26 +2423,58 @@ describe("sandbox", () => {
"plugin parentNode decoy:",
"true",
);
-
cy.get("[data-plugin-sandbox]")
.parent()
.should("not.have.attr", "data-pwned-by-plugin");
});
- it("MutationObserver on out-of-scope nodes observes a decoy and never fires for host mutations", () => {
+ // `Document` is itself a Node, so it's a valid root for TreeWalker /
+ // NodeIterator and a valid target for `MutationObserver.observe`. With
+ // an Element-only decoy, the plugin could pass `document` as the root
+ // and walk the entire host DOM, surfacing real host Text nodes that
+ // weren't decoyed. Locking this down requires the Node-level decoy.
+ it("decoys non-Element nodes reached via TreeWalker rooted at document, and observes a decoy with MutationObserver on out-of-scope nodes", () => {
+ const HOST_MARKER_TEXT = "treewalker-host-canary-do-not-leak";
+
const payload = `
- var seenMutations = 0;
- var observer = new MutationObserver(function(records) {
- seenMutations += records.length;
- });
- observer.observe(document.body, {
- childList: true,
- subtree: true,
- attributes: true,
- });
setTimeout(function() {
- console.log('plugin observed mutations:', seenMutations);
+ var walker = document.createTreeWalker(document, NodeFilter.SHOW_TEXT);
+ var sawMarker = false;
+ var node;
+ let nonEmptyCount = 0;
+ while ((node = walker.nextNode())) {
+ if ((node.textContent || "").indexOf(${JSON.stringify(HOST_MARKER_TEXT)}) !== -1) {
+ sawMarker = true;
+ break;
+ }
+ if (node.textContent && node.textContent.trim() !== "") {
+ nonEmptyCount++;
+ }
+ }
+ console.log('plugin treewalker(document) saw host marker:', sawMarker);
+ console.log('plugin treewalker(document) saw non-empty nodes:', nonEmptyCount);
}, 1500);
+ (function() {
+ var seenMutations = 0;
+ var observer = new MutationObserver(function(records) {
+ seenMutations += records.length;
+ });
+ observer.observe(document.body, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ });
+ var ownMutations = 0;
+ var ownNode = document.createElement('div');
+ new MutationObserver(function(records) {
+ ownMutations += records.length;
+ }).observe(ownNode, { attributes: true });
+ ownNode.setAttribute('data-own-mutation', 'true');
+ setTimeout(function() {
+ console.log('plugin observed own mutations:', ownMutations);
+ console.log('plugin observed mutations:', seenMutations);
+ }, 1500);
+ })();
`;
cy.intercept("GET", "/api/ee/custom-viz-plugin/*/bundle*", (req) => {
@@ -2746,27 +2487,51 @@ describe("sandbox", () => {
H.visitQuestion("@sandboxCardId", {
onBeforeLoad(win) {
cy.spy(win.console, "log").as("consoleLog");
+ // DOMContentLoaded fires before the plugin bundle loads, so the marker
+ // is in the host DOM before the walker runs. The host keeps mutating
+ // the real DOM while the plugin observer is active. If the plugin held
+ // a real reference to document.body, these mutations would fire its
+ // observer.
+ win.document.addEventListener("DOMContentLoaded", () => {
+ const marker = win.document.createElement("span");
+ marker.id = "treewalker-host-marker";
+ marker.textContent = HOST_MARKER_TEXT;
+ win.document.body.appendChild(marker);
+
+ const probe = win.document.createElement("div");
+ win.document.body.appendChild(probe);
+ win.setInterval(() => {
+ probe.toggleAttribute("data-mutation-probe");
+ win.document.body.toggleAttribute("data-mutation-probe-attr");
+ }, 100);
+ });
},
});
cy.wait("@injectedBundle");
+ cy.get("#treewalker-host-marker").should("have.text", HOST_MARKER_TEXT);
cy.findByRole("heading", {
name: "Custom viz rendered successfully",
}).should("be.visible");
- // Mutate the real host DOM. If the plugin held a real reference to
- // document.body, these would fire its observer. The membrane swapped
- // body for a detached decoy, so observation is wired to a node that
- // never sees host changes.
- cy.document().then((doc) => {
- const probe = doc.createElement("div");
- probe.setAttribute("data-mutation-probe", "true");
- doc.body.appendChild(probe);
- doc.body.setAttribute("data-mutation-probe-attr", "true");
- probe.remove();
- doc.body.removeAttribute("data-mutation-probe-attr");
- });
+ cy.get("@consoleLog").should(
+ "have.been.calledWith",
+ "plugin treewalker(document) saw host marker:",
+ false,
+ );
+ cy.get("@consoleLog").should(
+ "have.been.calledWith",
+ "plugin treewalker(document) saw non-empty nodes:",
+ 27,
+ );
+ // The membrane swapped body for a detached decoy, so observation is
+ // wired to a node that never sees host changes.
+ cy.get("@consoleLog").should(
+ "have.been.calledWith",
+ "plugin observed own mutations:",
+ 1,
+ );
cy.get("@consoleLog").should(
"have.been.calledWith",
"plugin observed mutations:",
@@ -2774,8 +2539,9 @@ describe("sandbox", () => {
);
});
- it("blocks forbidden apis in widget settings", () => {
+ it("blocks forbidden apis in widget settings and sandboxes React component setting widgets", () => {
H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ_3_SECURITY);
+ H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ_4_SECURITY_COMPONENT);
H.createQuestion(
{
@@ -2810,31 +2576,11 @@ describe("sandbox", () => {
Cypress.sinon.match(/blocked API call: window\.fetch/),
),
);
- });
-
- it("sandboxes React component setting widgets", () => {
- H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ_4_SECURITY_COMPONENT);
- H.createQuestion(
- {
- name: "Custom Viz Component Widget Security Test",
- query: {
- "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,
- aggregation: [["count"]],
- },
- display: "table",
- },
- { wrapId: true, idAlias: "questionId" },
+ cy.log(
+ "Switch to the component widget plugin; the custom viz group is already expanded",
);
-
- H.visitQuestion("@questionId", {
- onBeforeLoad(win) {
- cy.spy(win.console, "error").as("consoleError");
- },
- });
-
cy.findByTestId("viz-type-button").click();
- cy.findByTestId("custom-viz-plugins-toggle").click();
cy.findByTestId(
`${H.CUSTOM_VIZ_IDENTIFIER_4_SECURITY_COMPONENT}-button`,
).click();