Skip to content

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

add support for custom viz in EAJS (#78133)

Nicolò Pretto987f30803a37
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 7ce8fc34192..68165642828 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -3073,6 +3073,7 @@
enterprise/custom-viz-plugin
{:team "Gadget"
:api #{metabase-enterprise.custom-viz-plugin.api
+ metabase-enterprise.custom-viz-plugin.api.sandbox-host
metabase-enterprise.custom-viz-plugin.init
metabase-enterprise.custom-viz-plugin.settings}
:uses #{api
diff --git a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
index 0769d3d6605..62ac04da4cb 100644
--- a/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
+++ b/e2e/support/helpers/e2e-embedding-iframe-sdk-helpers.ts
@@ -3,7 +3,10 @@ import { match } from "ts-pattern";
import { openSharingMenu } from "e2e/support/helpers/e2e-sharing-helpers";
import { JWT_SHARED_SECRET } from "e2e/support/helpers/embedding-sdk-helpers/constants";
import type { MetabaseTheme } from "metabase/embedding-sdk/theme/MetabaseTheme";
-import type { CreateApiKeyResponse } from "metabase-types/api";
+import type {
+ CreateApiKeyResponse,
+ CustomVizDisplayType,
+} from "metabase-types/api";
import { createApiKey, updateSetting } from "./api";
import { getIframeBody } from "./e2e-embedding-helpers";
@@ -34,6 +37,7 @@ export interface BaseEmbedTestPageOptions {
theme?: MetabaseTheme;
preferredAuthMethod?: "jwt" | "saml";
locale?: string;
+ allowedCustomVisualizations?: CustomVizDisplayType[];
};
elements: MetabaseElement[];
@@ -325,6 +329,7 @@ export const getNewEmbedConfigurationScript = ({
useExistingUserSession,
preferredAuthMethod,
locale,
+ allowedCustomVisualizations,
}: BaseEmbedTestPageOptions["metabaseConfig"] = {}) => {
const config = {
instanceUrl,
@@ -335,6 +340,7 @@ export const getNewEmbedConfigurationScript = ({
theme,
preferredAuthMethod,
locale,
+ allowedCustomVisualizations,
};
return `
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
new file mode 100644
index 00000000000..24db2099fb6
--- /dev/null
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/custom-viz.cy.spec.ts
@@ -0,0 +1,98 @@
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { CardId } from "metabase-types/api";
+
+const { H } = cy;
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+describe(
+ "scenarios > embedding > sdk iframe embedding > custom visualizations",
+ { tags: "@EE" },
+ () => {
+ beforeEach(() => {
+ H.prepareSdkIframeEmbedTest({ withToken: "bleeding-edge" });
+
+ cy.log("Turn on the prereqs for custom visualizations");
+ cy.request("PUT", "/api/setting", {
+ "csp-img-enabled": true, // csp-img is required to enable custom-viz
+ "custom-viz-enabled": true,
+ });
+
+ cy.log("Upload the demo-viz custom visualization plugin");
+ H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);
+
+ cy.log("Create a question that targets the demo-viz custom display");
+ // demo-viz expects exactly one row with one numeric column.
+ H.createQuestion({
+ name: "Custom Viz EAJS Question",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ },
+ display: H.CUSTOM_VIZ_DISPLAY,
+ }).then(({ body: question }) => {
+ cy.wrap(question.id).as("questionId");
+ });
+
+ cy.log(
+ "Sign out so the donor request is anonymous and must pass the Sec-Fetch gate instead of the session-auth bypass",
+ );
+ cy.signOut();
+ });
+
+ it("renders the custom visualization when allowedCustomVisualizations includes the display", () => {
+ cy.log(
+ "EAJS has no eval-permissive page CSP, so the plugin sandbox loads the hosted donor document",
+ );
+ cy.intercept("GET", "**/api/ee/custom-viz-plugin/sandbox-host*").as(
+ "getSandboxHost",
+ );
+
+ cy.get<CardId>("@questionId").then((questionId) => {
+ const frame = H.loadSdkIframeEmbedTestPage({
+ elements: [
+ {
+ component: "metabase-question",
+ attributes: { questionId },
+ },
+ ],
+ metabaseConfig: {
+ allowedCustomVisualizations: [H.CUSTOM_VIZ_DISPLAY],
+ },
+ });
+
+ cy.wait("@getCardQuery");
+
+ cy.log("The sandbox loads the donor document as its iframe src");
+ cy.wait("@getSandboxHost").its("response.statusCode").should("eq", 200);
+
+ frame.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({
+ elements: [
+ {
+ component: "metabase-question",
+ attributes: { questionId },
+ },
+ ],
+ });
+
+ cy.wait("@getCardQuery");
+
+ frame.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");
+ cy.findByText("Custom viz rendered successfully").should("not.exist");
+ });
+ });
+ });
+ },
+);
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index b41fd85b8b6..504a7fc7d66 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -17,6 +17,7 @@
[metabase-enterprise.content-translation.routes]
[metabase-enterprise.content-verification.api.routes]
[metabase-enterprise.custom-viz-plugin.api]
+ [metabase-enterprise.custom-viz-plugin.api.sandbox-host]
[metabase-enterprise.data-apps.api]
[metabase-enterprise.data-complexity-score.api]
[metabase-enterprise.data-studio.api]
@@ -113,7 +114,14 @@
"/audit-app" (premium-handler metabase-enterprise.audit-app.api.routes/routes :audit-app)
"/billing" metabase-enterprise.billing.api.routes/routes
"/content-translation" (premium-handler metabase-enterprise.content-translation.routes/routes :content-translation)
- "/custom-viz-plugin" (premium-handler metabase-enterprise.custom-viz-plugin.api/routes :custom-viz)
+ ;; The sandbox donor GET can be accessed without auth (an iframe src cannot carry session auth), so it lives in
+ ;; its own namespace, tested before the rest of the session-authed custom-viz routes. Both stay behind
+ ;; the :custom-viz premium gate.
+ "/custom-viz-plugin" (premium-handler
+ (handlers/routes
+ metabase-enterprise.custom-viz-plugin.api.sandbox-host/routes
+ metabase-enterprise.custom-viz-plugin.api/routes)
+ :custom-viz)
"/cloud-add-ons" metabase-enterprise.cloud-add-ons.api/routes
"/cloud-proxy" metabase-enterprise.cloud-proxy.api/routes
;; No premium-handler gate yet — we haven't settled on the feature flag name or final API shape.
diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj
index 3c3d0416d85..a2bedb4e8af 100644
--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj
@@ -261,35 +261,6 @@
(finally
(try (.delete tempfile) (catch Exception _))))))
-(def ^:private sandbox-host-html
- "Minimal HTML doc that the patched `@locker/near-membrane-dom` loads as the iframe document
- so plugin code can be `eval`'d under a relaxed, per-iframe CSP."
- "<!doctype html><html><head><meta charset=\"utf-8\"></head><body></body></html>")
-
-(def ^:private sandbox-host-csp
- "CSP applied ONLY to the sandbox iframe document.
- - `'unsafe-eval'` required by near-membrane to evaluate plugin code inside the realm.
- - `frame-ancestors 'self'` - so Metabase can embed this document."
- (str "default-src 'none'; "
- "script-src 'unsafe-eval'; "
- "frame-ancestors 'self';"))
-
-(api.macros/defendpoint :get "/sandbox-host" :- :any
- "Serve a minimal HTML document used as the iframe `src` for the near-membrane custom-viz
- sandbox. The response carries a per-document `Content-Security-Policy` that permits
- `'unsafe-eval'` only inside this iframe, so the main Metabase document keeps its strict
- nonce-based CSP."
- []
- {:status 200
- :headers {"Content-Type" "text/html; charset=utf-8"
- "Content-Security-Policy" sandbox-host-csp
- "X-Frame-Options" "SAMEORIGIN"
- "X-Content-Type-Options" "nosniff"
- "Cross-Origin-Resource-Policy" "same-origin"
- "Referrer-Policy" "no-referrer"
- "Cache-Control" "public, max-age=60"}
- :body sandbox-host-html})
-
(api.macros/defendpoint :get "/:id/bundle" :- :any
"Serve the JS bundle for a plugin from the on-disk cache.
Returns application/javascript with ETag and Cache-Control headers.
diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api/sandbox_host.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api/sandbox_host.clj
new file mode 100644
index 00000000000..f2095a62404
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api/sandbox_host.clj
@@ -0,0 +1,83 @@
+(ns metabase-enterprise.custom-viz-plugin.api.sandbox-host
+ "Donor endpoint for the near-membrane custom-viz sandbox: a blank iframe document whose only
+ capability is `'unsafe-eval'` in its own realm. It cannot require auth, because EAJS loads it as an
+ iframe `src`, which carries no headers and no first-party cookies.
+
+ Served only when the browser sends `Sec-Fetch-Site: same-origin` and `Sec-Fetch-Dest: iframe`
+ (page JS cannot forge those), or, for session-authed callers, as long as there is a valid session.
+ Everything else 404s. Keep it inert: never add content, data, or parameters here."
+ (:require
+ [metabase-enterprise.custom-viz-plugin.settings :as custom-viz.settings]
+ [metabase.api.macros :as api.macros]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private sandbox-host-html
+ "Minimal HTML doc that the patched `@locker/near-membrane-dom` loads as the iframe document
+ so plugin code can be `eval`'d under a relaxed, per-iframe CSP."
+ "<!doctype html><html><head><meta charset=\"utf-8\"></head><body></body></html>")
+
+(def ^:private sandbox-host-csp
+ "CSP applied ONLY to the sandbox iframe document.
+ - `'unsafe-eval'` required by near-membrane to evaluate plugin code inside the realm.
+ - `frame-ancestors *` instead of `X-Frame-Options`, so EAJS customer pages can frame it too."
+ "default-src 'none'; script-src 'unsafe-eval'; frame-ancestors *;")
+
+(defn- sec-fetch-same-origin-iframe?
+ "True when the browser attests this is a same-origin iframe navigation, the one way EAJS loads
+ the donor. `Sec-Fetch-*` headers cannot be forged by page JS."
+ [{:keys [headers]}]
+ (and (= (get headers "sec-fetch-site") "same-origin")
+ (= (get headers "sec-fetch-dest") "iframe")))
+
+(defn- sec-fetch-absent?
+ "True when the request carries no fetch-metadata headers at all, e.g. an older browser that
+ predates Fetch Metadata."
+ [{:keys [headers]}]
+ (and (nil? (get headers "sec-fetch-site"))
+ (nil? (get headers "sec-fetch-dest"))))
+
+(defn- donor-load-allowed?
+ "Whether to serve the donor. Core-app (session-authed) callers may load it when the browser
+ sends no fetch metadata (older browsers) or attests a same-origin iframe; a present cross-site
+ attestation is rejected even when authed, so an authenticated user cannot be made to frame the
+ donor from an attacker's page. EAJS (unauthed) callers must always send an attested same-origin
+ iframe navigation."
+ [request]
+ (if (:metabase-user-id request)
+ (or (sec-fetch-absent? request)
+ (sec-fetch-same-origin-iframe? request))
+ (sec-fetch-same-origin-iframe? request)))
+
+(api.macros/defendpoint :get "/sandbox-host" :- :any
+ "Serve a minimal HTML document used as the iframe `src` for the near-membrane custom-viz
+ sandbox. The response carries a per-document `Content-Security-Policy` that permits
+ `'unsafe-eval'` only inside this iframe, so the main Metabase document keeps its strict
+ nonce-based CSP. 404s unless the custom-viz kill switch is on and the request passes the
+ fetch-metadata gate (see [[donor-load-allowed?]])."
+ [_route-params _query-params _body request]
+ (if-not (and (custom-viz.settings/enable-custom-viz?)
+ (donor-load-allowed? request))
+ {:status 404
+ :headers {"Content-Type" "text/plain; charset=utf-8"
+ "Cache-Control" "no-store"}
+ :body "Not found"}
+ {:status 200
+ :headers {"Content-Type" "text/html; charset=utf-8"
+ "Content-Security-Policy" sandbox-host-csp
+ ;; nil drops the header: the global security middleware would otherwise inject
+ ;; X-Frame-Options: DENY, which blocks the cross-origin framing EAJS needs.
+ "X-Frame-Options" nil
+ "X-Content-Type-Options" "nosniff"
+ "Cross-Origin-Resource-Policy" "same-origin"
+ "Referrer-Policy" "no-referrer"
+ ;; no-store, not a shared/public cache: the 200-vs-404 split depends on the
+ ;; Sec-Fetch metadata and the session, which a URL-keyed cache can't see, so a
+ ;; cached 200 would otherwise be replayed to requests the gate meant to 404.
+ "Cache-Control" "no-store"}
+ :body sandbox-host-html}))
+
+(def ^{:arglists '([request respond raise])} routes
+ "Unauthed `/api/ee/custom-viz-plugin/sandbox-host` donor route, mounted alongside the
+ session-authed custom-viz-plugin routes."
+ (api.macros/ns-handler *ns*))
diff --git a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
index abbacea3136..b9358a2b7bc 100644
--- a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
@@ -445,41 +445,113 @@
;;; ------------------------------------------------ Sandbox-host Endpoint ------------------------------------------------
+;; Pinned independently of the source constant on purpose: the donor is unauthed, so a change to
+;; the served body must break a test rather than silently ride along with the source.
+(def ^:private inert-donor-doc
+ "<!doctype html><html><head><meta charset=\"utf-8\"></head><body></body></html>")
+
(deftest sandbox-host-endpoint-test
(testing "GET /sandbox-host returns minimal HTML with a per-document CSP"
(mt/with-premium-features #{:custom-viz}
(let [resp (mt/user-http-request-full-response
:rasta :get 200 "ee/custom-viz-plugin/sandbox-host")
headers (:headers resp)]
- (testing "returns a tiny HTML body"
- (is (string? (:body resp)))
- (is (str/includes? (:body resp) "<!doctype html>"))
- (is (str/includes? (:body resp) "<body></body>")))
+ (testing "the body is exactly the inert donor document (pinned: this endpoint is unauthed, nothing may be added to it)"
+ (is (= inert-donor-doc (:body resp))))
(testing "response is served as HTML"
(is (str/starts-with? (get headers "Content-Type") "text/html")))
- (testing "Content-Security-Policy allows unsafe-eval only inside the sandbox doc"
- (let [csp (get headers "Content-Security-Policy")]
- (is (some? csp))
- (is (str/includes? csp "default-src 'none'"))
- (is (str/includes? csp "script-src 'unsafe-eval'"))
- (is (not (str/includes? csp "sandbox")))
- (is (str/includes? csp "frame-ancestors 'self'"))))
- (testing "framing is allowed for same-origin (overrides the global X-Frame-Options: DENY)"
- (is (= "SAMEORIGIN" (get headers "X-Frame-Options"))))
+ (testing "the CSP is exactly the per-document sandbox policy (pinned)"
+ (is (= "default-src 'none'; script-src 'unsafe-eval'; frame-ancestors *;"
+ (get headers "Content-Security-Policy"))))
+ (testing "no X-Frame-Options is served (frame-ancestors is the framing policy, so EAJS customer pages can frame it)"
+ (is (nil? (get headers "X-Frame-Options"))))
(testing "hardening headers are present"
(is (= "nosniff" (get headers "X-Content-Type-Options")))
(is (= "no-referrer" (get headers "Referrer-Policy")))
(is (= "same-origin" (get headers "Cross-Origin-Resource-Policy")))
- (is (= "public, max-age=60" (get headers "Cache-Control")))))))
+ ;; no-store, not public: the gate's 200-vs-404 depends on headers/session a
+ ;; URL-keyed shared cache can't see, so a cached 200 must never be replayable.
+ (is (= "no-store" (get headers "Cache-Control")))))))
(testing "GET /sandbox-host requires the :custom-viz premium feature"
(mt/with-premium-features #{}
(mt/assert-has-premium-feature-error
"Custom Visualizations"
(mt/user-http-request :rasta :get 402 "ee/custom-viz-plugin/sandbox-host"))))
- (testing "GET /sandbox-host requires authentication"
+ (testing "GET /sandbox-host is a 404 when the custom-viz kill switch is off"
+ (mt/with-premium-features #{:custom-viz}
+ (mt/with-temporary-setting-values [custom-viz-enabled false]
+ (let [resp (client/client-full-response :get 404 "ee/custom-viz-plugin/sandbox-host")]
+ (testing "and the 404 never carries the eval-permitting CSP"
+ (is (not (str/includes? (str (get-in resp [:headers "Content-Security-Policy"])) "unsafe-eval")))))))))
+
+(defn- get-sandbox-host
+ "GET the donor endpoint, as `:rasta` when `authed?`, asserting `expected-status`.
+ A nil `sec-fetch-site`/`sec-fetch-dest` means the header is not sent at all."
+ [{:keys [authed? sec-fetch-site sec-fetch-dest expected-status]}]
+ (let [headers (cond-> {}
+ sec-fetch-site (assoc "sec-fetch-site" sec-fetch-site)
+ sec-fetch-dest (assoc "sec-fetch-dest" sec-fetch-dest))
+ args (cond-> []
+ (seq headers) (conj {:request-options {:headers headers}}))]
+ (if authed?
+ (apply mt/user-http-request-full-response :rasta :get expected-status "ee/custom-viz-plugin/sandbox-host" args)
+ (apply client/client-full-response :get expected-status "ee/custom-viz-plugin/sandbox-host" args))))
+
+(deftest sandbox-host-fetch-metadata-gate-test
+ ;; The whole gate in one table. Every 200 also pins the body: the donor is reachable without
+ ;; authentication and its response carries an eval-permitting CSP, so it must ALWAYS be this
+ ;; exact empty document. Never add content, data, or anything request-dependent to it.
+ (mt/with-premium-features #{:custom-viz}
+ (doseq [{:keys [description expected-status] :as scenario}
+ [{:description "an unauthed browser-attested same-origin iframe navigation is served (the EAJS path)"
+ :sec-fetch-site "same-origin"
+ :sec-fetch-dest "iframe"
+ :expected-status 200}
+ {:description "cross-site framing of the donor URL is a 404"
+ :sec-fetch-site "cross-site"
+ :sec-fetch-dest "iframe"
+ :expected-status 404}
+ {:description "a top-level navigation (URL pasted in a tab) is a 404"
+ :sec-fetch-site "none"
+ :sec-fetch-dest "document"
+ :expected-status 404}
+ {:description "a non-iframe use (script/img/fetch) is a 404"
+ :sec-fetch-site "same-origin"
+ :sec-fetch-dest "empty"
+ :expected-status 404}
+ {:description "absent fetch metadata is rejected (the unauthed donor requires an attested same-origin iframe load)"
+ :expected-status 404}
+ {:description "a partial fetch-metadata set (only one of the two headers) is rejected"
+ :sec-fetch-site "same-origin"
+ :expected-status 404}
+ {:description "an unauthed cross-site top-level load is a 404"
+ :sec-fetch-site "cross-site"
+ :sec-fetch-dest "document"
+ :expected-status 404}
+ {:description "a session-authed request with no fetch metadata is served (older browsers)"
+ :authed? true
+ :expected-status 200}
+ {:description "a session-authed same-origin iframe navigation is served"
+ :authed? true
+ :sec-fetch-site "same-origin"
+ :sec-fetch-dest "iframe"
+ :expected-status 200}
+ {:description "a session-authed request with a present cross-site attestation is a 404 (an authed user must not be framable cross-site)"
+ :authed? true
+ :sec-fetch-site "cross-site"
+ :sec-fetch-dest "document"
+ :expected-status 404}]]
+ (testing description
+ (let [resp (get-sandbox-host scenario)]
+ (if (= 200 expected-status)
+ (is (= inert-donor-doc (:body resp)))
+ (is (= "Not found" (:body resp)))))))))
+
+(deftest custom-viz-list-still-requires-auth-test
+ (testing "splitting out the unauthed donor route must not expose the other custom-viz routes"
(mt/with-premium-features #{:custom-viz}
- (is (= "Unauthenticated"
- (client/client :get 401 "ee/custom-viz-plugin/sandbox-host"))))))
+ (is (= "Unauthenticated" (client/client :get 401 "ee/custom-viz-plugin/list")))
+ (is (= "Unauthenticated" (client/client :get 401 "ee/custom-viz-plugin/"))))))
;;; ------------------------------------------------ Bundle Endpoint ------------------------------------------------
diff --git a/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts
index 1c030d1524b..e84d76df3a3 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts
+++ b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts
@@ -4,6 +4,7 @@ import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-me
import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
import { api } from "metabase/api/client";
import type { IconData } from "metabase/common/utils/icon";
+import { isEmbeddingEajs } from "metabase/embedding-sdk/config";
import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";
import type { DispatchFn } from "metabase/redux/hooks";
import {
@@ -28,8 +29,19 @@ import {
unregisterCustomVizDisplay,
useCustomVizPlugins,
} from "../../metabase-enterprise/custom_viz/custom-viz-plugins";
+import type { SandboxMode } from "../../metabase-enterprise/custom_viz/sandbox";
import { isWidgetMount } from "../../metabase-enterprise/custom_viz/widget-mount";
+/**
+ * EAJS has no eval-permissive page CSP in production, so its plugin sandbox
+ * uses the hosted donor document (served with a per-document eval CSP). The
+ * react-sdk npm package runs on the customer's own page and inherits its
+ * CSP, so "blank" (about:blank) works there.
+ */
+export function getSdkSandboxMode(): SandboxMode {
+ return isEmbeddingEajs() ? "hosted" : "blank";
+}
+
/**
* Allowlist of plugin identifiers from the `allowedCustomVisualizations`
* MetabaseProvider prop. Empty / undefined = no custom viz allowed.
@@ -137,8 +149,7 @@ export function initializeSdkCustomVizPlugin() {
}
return eeLoadCustomVizPlugin(plugin, {
...options,
- // Note: in the future we might want to check the domain to check if we need "blank" or "sandbox" mode, to support data apps
- sandboxMode: "blank",
+ sandboxMode: getSdkSandboxMode(),
});
},
@@ -161,7 +172,7 @@ export function initializeSdkCustomVizPlugin() {
return null;
}
return await eeLoadCustomVizPlugin(plugin, {
- sandboxMode: "blank",
+ sandboxMode: getSdkSandboxMode(),
});
} catch {
return null;
@@ -183,7 +194,7 @@ export function initializeSdkCustomVizPlugin() {
}, [display, allowed]);
return eeUseAutoLoadCustomVizPlugin(allowed ? display : undefined, {
- sandboxMode: "blank",
+ sandboxMode: getSdkSandboxMode(),
});
},
diff --git a/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.unit.spec.ts
index 5211184e5b7..2c4d4e049b9 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.unit.spec.ts
+++ b/enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.unit.spec.ts
@@ -1,7 +1,24 @@
import { api } from "metabase/api/client";
+import { EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG } from "metabase/embedding-sdk/config";
import { getPluginAssetUrl } from "metabase/visualizations/custom-visualizations/custom-viz-utils";
-import { sdkCustomVizAssetManager } from "./initialize";
+import { getSdkSandboxMode, sdkCustomVizAssetManager } from "./initialize";
+
+describe("getSdkSandboxMode", () => {
+ afterEach(() => {
+ EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG.isSimpleEmbedding = false;
+ });
+
+ it('returns "hosted" when running as EAJS (simple embedding)', () => {
+ EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG.isSimpleEmbedding = true;
+ expect(getSdkSandboxMode()).toBe("hosted");
+ });
+
+ it('returns "blank" for the react-sdk npm package (not EAJS)', () => {
+ EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG.isSimpleEmbedding = false;
+ expect(getSdkSandboxMode()).toBe("blank");
+ });
+});
const okResponse = () =>
// Unjustified type cast. FIXME
diff --git a/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts b/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts
index 34fe0fe5741..6a4b7299d1c 100644
--- a/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts
+++ b/frontend/src/embedding-sdk-bundle/types/metabase-provider.ts
@@ -78,8 +78,6 @@ export interface MetabaseProviderProps {
/**
* Opt-in support for EE custom visualization plugins inside the SDK.
- * When set, the SDK loads custom-viz bundles into an `about:blank`
- * sandbox (no hosted-sandbox endpoint required).
*
* Pass an allowlist of `custom:`-prefixed plugin identifiers (manifest
* `name`), e.g. `["custom:Thumbs", "custom:Calendar"]`. Only
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
index 6036dbc9e75..836acebf84c 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
@@ -18,6 +18,7 @@ import { getLoginStatus } from "embedding-sdk-bundle/store/selectors";
import type { SdkDashboardEntityPublicProps } from "embedding-sdk-bundle/types/dashboard";
import type { SdkQuestionEntityPublicProps } from "embedding-sdk-bundle/types/question";
import { applyThemePreset } from "embedding-sdk-shared/lib/apply-theme-preset";
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
import type { MetabaseAuthConfig } from "embedding-sdk-shared/types/auth-config";
import { createSnowplowTracker } from "metabase/analytics";
import { type OnBeforeRequestHandler, PLUGIN_API } from "metabase/api/client";
@@ -33,6 +34,7 @@ import { useParamRerenderKey } from "../hooks/use-param-rerender-key";
import { useSdkIframeEmbedEventBus } from "../hooks/use-sdk-iframe-embed-event-bus";
import type { SdkIframeEmbedSettings } from "../types/embed";
import { stripInternalIframeQueryParameters } from "../utils/strip-internal-iframe-query-parameters";
+import { resolveAllowedCustomVisualizations } from "../utils/validate-allowed-custom-visualizations";
import { DashboardParametersBridge } from "./DashboardParametersBridge";
import { MetabaseBrowser } from "./MetabaseBrowser";
@@ -69,6 +71,11 @@ const onSettingsChanged = (settings: SdkIframeEmbedSettings) => {
// Forward the host page URL so it's sent as X-Metabase-Embed-Referrer on API requests.
_embedReferrer = settings?._embedReferrer;
+
+ // Custom viz allowlist, read by the plugin loaders via the props store.
+ ensureMetabaseProviderPropsStore().setProps({
+ allowedCustomVisualizations: resolveAllowedCustomVisualizations(settings),
+ });
};
const store = getSdkStore();
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
index 1cd3906f2bd..18a406e22d1 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/constants.ts
@@ -29,6 +29,7 @@ export const ALLOWED_EMBED_SETTING_KEYS_MAP = {
"jwtProviderUri",
"pluginsConfig",
"guestEmbedProviderUri",
+ "allowedCustomVisualizations",
] satisfies (keyof SdkIframeEmbedBaseSettings)[],
dashboard: [
"dashboardId",
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
index 887aa077cb1..03a723ad5e5 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/types/embed.ts
@@ -269,6 +269,19 @@ export type SdkIframeEmbedBaseSettings = {
// Callback to handle link clicks. Return { handled: true } to prevent default navigation.
handleLink?: (url: string) => { handled: boolean };
};
+
+ // Type inlined (not CustomVizDisplayType) so hovering the public setting shows the format.
+ /**
+ * Opt-in support for EE custom visualization plugins inside the embed.
+ *
+ * Pass an allowlist of `custom:`-prefixed plugin identifiers (manifest
+ * `name`), e.g. `["custom:Thumbs", "custom:Calendar"]`. Only
+ * listed plugins are loaded. Omit or pass `[]` to disable.
+ *
+ * Ignored in guest embeds: custom visualizations need an authenticated
+ * user.
+ */
+ allowedCustomVisualizations?: `custom:${string}`[];
};
export type SdkIframeEmbedAuthTypeSettings = {
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/post-message.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/post-message.ts
index 6d4674007ee..0031780a417 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/post-message.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/post-message.ts
@@ -26,7 +26,11 @@ export function listenForEajsMessages<Source extends EajsMessageSource>(
const messageHandler = (event: MessageEvent<EajsMessageBySource[Source]>) => {
switch (options.messageSource) {
case "embed.js":
- if (!isWithinIframe() || event.source !== window.parent) {
+ if (
+ !isWithinIframe() ||
+ !event.isTrusted ||
+ event.source !== window.parent
+ ) {
return;
}
break;
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/validate-allowed-custom-visualizations.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/validate-allowed-custom-visualizations.ts
new file mode 100644
index 00000000000..97a12c41a1b
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/validate-allowed-custom-visualizations.ts
@@ -0,0 +1,72 @@
+import type { CustomVizDisplayType } from "metabase-types/api";
+import { isCustomVizDisplay } from "metabase-types/guards/visualization";
+
+const warnedMessages = new Set<string>();
+
+function warnOnce(message: string) {
+ if (!warnedMessages.has(message)) {
+ warnedMessages.add(message);
+ console.warn(message);
+ }
+}
+
+// Test-only: the warn-once dedupe is module-level state that leaks across tests.
+export function resetWarnOnceForTesting() {
+ warnedMessages.clear();
+}
+
+/**
+ * Runtime-validates a host-provided `allowedCustomVisualizations` value.
+ * Drops (and warns about) anything that isn't a `custom:`-prefixed string.
+ */
+export function validateAllowedCustomVisualizations(
+ value: unknown,
+): CustomVizDisplayType[] {
+ if (value == null) {
+ return [];
+ }
+
+ if (!Array.isArray(value)) {
+ warnOnce(
+ `Ignored allowedCustomVisualizations: ${JSON.stringify(value) ?? String(value)}. ` +
+ 'Expected an array of "custom:"-prefixed plugin identifiers, e.g. ["custom:my-viz"].',
+ );
+ return [];
+ }
+
+ return value.filter((entry): entry is CustomVizDisplayType => {
+ if (isCustomVizDisplay(entry)) {
+ return true;
+ }
+ warnOnce(
+ `Ignored invalid allowedCustomVisualizations entry: ${JSON.stringify(entry) ?? String(entry)}. ` +
+ 'Entries must be "custom:"-prefixed plugin identifiers, e.g. "custom:my-viz". ' +
+ "Built-in visualizations are always enabled and don't need to be listed.",
+ );
+ return false;
+ });
+}
+
+/**
+ * The `allowedCustomVisualizations` provider prop for an embed's settings.
+ * Guest embeds fail closed: custom viz needs an authenticated user.
+ */
+export function resolveAllowedCustomVisualizations(settings?: {
+ isGuest?: boolean;
+ allowedCustomVisualizations?: unknown;
+}): CustomVizDisplayType[] {
+ if (settings?.isGuest) {
+ if (
+ Array.isArray(settings.allowedCustomVisualizations) &&
+ settings.allowedCustomVisualizations.length > 0
+ ) {
+ warnOnce(
+ "allowedCustomVisualizations is ignored in guest embeds: custom visualizations are not supported there.",
+ );
+ }
+ return [];
+ }
+ return validateAllowedCustomVisualizations(
+ settings?.allowedCustomVisualizations,
+ );
+}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/validate-allowed-custom-visualizations.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/validate-allowed-custom-visualizations.unit.spec.ts
new file mode 100644
index 00000000000..ac61e64c0b8
--- /dev/null
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/utils/validate-allowed-custom-visualizations.unit.spec.ts
@@ -0,0 +1,119 @@
+import {
+ resetWarnOnceForTesting,
+ resolveAllowedCustomVisualizations,
+ validateAllowedCustomVisualizations,
+} from "./validate-allowed-custom-visualizations";
+
+let warnSpy: jest.SpyInstance;
+
+beforeEach(() => {
+ resetWarnOnceForTesting();
+ warnSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ warnSpy.mockRestore();
+});
+
+describe("validateAllowedCustomVisualizations", () => {
+ it("keeps custom:-prefixed strings", () => {
+ expect(
+ validateAllowedCustomVisualizations(["custom:demo-viz", "custom:Thumbs"]),
+ ).toEqual(["custom:demo-viz", "custom:Thumbs"]);
+ expect(warnSpy).not.toHaveBeenCalled();
+ });
+
+ it("drops strings without the custom: prefix", () => {
+ expect(
+ validateAllowedCustomVisualizations(["custom:demo-viz", "table", "bar"]),
+ ).toEqual(["custom:demo-viz"]);
+ });
+
+ it("drops non-string entries", () => {
+ expect(
+ validateAllowedCustomVisualizations([
+ "custom:demo-viz",
+ 123,
+ null,
+ undefined,
+ { name: "custom:fake" },
+ ["custom:fake"],
+ ]),
+ ).toEqual(["custom:demo-viz"]);
+ });
+
+ it("returns an empty array for non-array input", () => {
+ expect(validateAllowedCustomVisualizations(undefined)).toEqual([]);
+ expect(validateAllowedCustomVisualizations(null)).toEqual([]);
+ expect(validateAllowedCustomVisualizations("custom:demo-viz")).toEqual([]);
+ expect(validateAllowedCustomVisualizations({})).toEqual([]);
+ });
+
+ it("warns once per dropped entry, mentioning built-ins", () => {
+ validateAllowedCustomVisualizations(["ThumbsWithoutPrefix"]);
+ validateAllowedCustomVisualizations(["ThumbsWithoutPrefix"]);
+
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('"ThumbsWithoutPrefix"'),
+ );
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Built-in visualizations are always enabled"),
+ );
+ });
+
+ it("warns when the value is not an array (but not when omitted)", () => {
+ validateAllowedCustomVisualizations(undefined);
+ validateAllowedCustomVisualizations(null);
+ expect(warnSpy).not.toHaveBeenCalled();
+
+ validateAllowedCustomVisualizations("custom:not-an-array");
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Expected an array"),
+ );
+ });
+});
+
+describe("resolveAllowedCustomVisualizations", () => {
+ it("forces an empty allowlist for guest embeds, even when one is passed", () => {
+ expect(
+ resolveAllowedCustomVisualizations({
+ isGuest: true,
+ allowedCustomVisualizations: ["custom:demo-viz"],
+ }),
+ ).toEqual([]);
+ });
+
+ it("warns when a guest embed passes a non-empty allowlist", () => {
+ resolveAllowedCustomVisualizations({
+ isGuest: true,
+ allowedCustomVisualizations: ["custom:demo-viz"],
+ });
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("ignored in guest embeds"),
+ );
+ });
+
+ it("does not warn when a guest embed passes no allowlist", () => {
+ resolveAllowedCustomVisualizations({ isGuest: true });
+ resolveAllowedCustomVisualizations({
+ isGuest: true,
+ allowedCustomVisualizations: [],
+ });
+ expect(warnSpy).not.toHaveBeenCalled();
+ });
+
+ it("returns the validated allowlist for non-guest embeds", () => {
+ expect(
+ resolveAllowedCustomVisualizations({
+ isGuest: false,
+ allowedCustomVisualizations: ["custom:demo-viz", "not-custom"],
+ }),
+ ).toEqual(["custom:demo-viz"]);
+ });
+
+ it("returns an empty allowlist when settings are missing", () => {
+ expect(resolveAllowedCustomVisualizations(undefined)).toEqual([]);
+ expect(resolveAllowedCustomVisualizations({})).toEqual([]);
+ });
+});
diff --git a/src/metabase/request/core.clj b/src/metabase/request/core.clj
index 909d0a7edf1..ec25010bf09 100644
--- a/src/metabase/request/core.clj
+++ b/src/metabase/request/core.clj
@@ -59,6 +59,7 @@
data-app-url-segment
data-app?
device-info
+ embed-sdk-eajs-entrypoint?
embed?
embedded?
geocode-ip-addresses
diff --git a/src/metabase/request/util.clj b/src/metabase/request/util.clj
index 10a646e1cf7..f77ea2ac24f 100644
--- a/src/metabase/request/util.clj
+++ b/src/metabase/request/util.clj
@@ -60,6 +60,14 @@
[{:keys [uri]}]
(re-matches data-app-uri-regex uri))
+(defn embed-sdk-eajs-entrypoint?
+ "Is this ring request the modular embedding (EAJS) entrypoint page, served by `index/embed-sdk`?
+ Matches exactly `/embed/sdk/v1` and, on purpose, any future `/embed/sdk/vN` version. Any other
+ `/embed/sdk/*` URI falls through to the static embed page and does not match. The react embedding
+ SDK renders on the host page and never requests this route."
+ [{:keys [uri]}]
+ (re-matches #"^/embed/sdk/v\d+$" uri))
+
(defn cacheable?
"Can the ring request be permanently cached?"
[{:keys [request-method uri], :as _request}]
diff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.clj
index f75473c6d8e..7ce6ae2ac74 100644
--- a/src/metabase/server/middleware/security.clj
+++ b/src/metabase/server/middleware/security.clj
@@ -237,7 +237,7 @@
(defn- content-security-policy-header
"`Content-Security-Policy` header. See https://content-security-policy.com for more details."
- [nonce data-app-iframe? data-app-connect-hosts]
+ [nonce data-app-iframe? data-app-connect-hosts allow-blob-img?]
{"Content-Security-Policy"
(str/join
(for [[k vs] {:default-src ["'none'"]
@@ -305,18 +305,22 @@
:img-src (let [restricted (cond-> (into (parse-allowed-resource-hosts (server.settings/csp-img-allowed-hosts))
(map-tile-server->hosts))
config/is-dev? (conj frontend-address))]
- (cond
- ;; A sandboxed data-app document NEVER gets `*`: an ungated
- ;; `new Image()`/`<img>` under `img-src *` would beacon the viewing
- ;; user's data off-origin (the `img` tag can't be blocked — the SDK
- ;; uses it). Always use the restricted allowlist: `'self'` (the
- ;; instance) + the admin's "Allowed domains for images"
- ;; (`csp-img-allowed-hosts`, so custom viz still renders) + blob:, plus
- ;; the app's own `allowed_hosts` (mirroring connect-src/frame-src —
- ;; the app can already fetch those, so this adds no exfil channel).
- data-app-iframe? (-> restricted (conj "blob:") (into data-app-connect-hosts))
- (server.settings/csp-img-enabled) restricted
- :else (into ["*"] always-allowed-resource-hosts)))
+ (cond-> (cond
+ ;; A sandboxed data-app document NEVER gets `*`: an ungated
+ ;; `new Image()`/`<img>` under `img-src *` would beacon the viewing
+ ;; user's data off-origin (the `img` tag can't be blocked — the SDK
+ ;; uses it). Always use the restricted allowlist: `'self'` (the
+ ;; instance) + the admin's "Allowed domains for images"
+ ;; (`csp-img-allowed-hosts`, so custom viz still renders) + blob:, plus
+ ;; the app's own `allowed_hosts` (mirroring connect-src/frame-src —
+ ;; the app can already fetch those, so this adds no exfil channel).
+ data-app-iframe? (into restricted data-app-connect-hosts)
+ (server.settings/csp-img-enabled) restricted
+ :else (into ["*"] always-allowed-resource-hosts))
+ ;; Data apps and the EAJS embed page both load custom viz icons
+ ;; as blob: <img> URLs (see the callers of `:allow-blob-img?`).
+ ;; `*` does not cover the blob: scheme, so it is listed either way.
+ allow-blob-img? (conj "blob:")))
:connect-src (into
["'self'"
;; Google Identity Services
@@ -360,8 +364,8 @@
(or (interactive-embedding-origins) "'none'")))
(defn- content-security-policy-header-with-frame-ancestors
- [frame-ancestors-mode nonce data-app-iframe? data-app-connect-hosts]
- (cond-> (update (content-security-policy-header nonce data-app-iframe? data-app-connect-hosts)
+ [frame-ancestors-mode nonce data-app-iframe? data-app-connect-hosts allow-blob-img?]
+ (cond-> (update (content-security-policy-header nonce data-app-iframe? data-app-connect-hosts allow-blob-img?)
"Content-Security-Policy"
#(format "%s frame-ancestors %s;" % (frame-ancestors-value frame-ancestors-mode)))
;; MANDATORY for data apps — do not remove/weaken. Sole barrier (no JS backstop)
@@ -480,12 +484,12 @@
`:frame-ancestors` controls clickjacking protection: `:any` (open embedding),
`:self` (same-origin only), or `:none` (default — no framing unless interactive
embedding is configured)."
- [& {:keys [origin nonce frame-ancestors allow-cache? data-app-iframe? data-app-connect-hosts]
- :or {frame-ancestors :none, allow-cache? false, data-app-iframe? false}}]
+ [& {:keys [origin nonce frame-ancestors allow-cache? data-app-iframe? data-app-connect-hosts allow-blob-img?]
+ :or {frame-ancestors :none, allow-cache? false, data-app-iframe? false, allow-blob-img? false}}]
(merge
(if allow-cache? cache-far-future-headers (cache-prevention-headers))
strict-transport-security-header
- (content-security-policy-header-with-frame-ancestors frame-ancestors nonce data-app-iframe? data-app-connect-hosts)
+ (content-security-policy-header-with-frame-ancestors frame-ancestors nonce data-app-iframe? data-app-connect-hosts allow-blob-img?)
(access-control-headers origin (embedding.settings/embedding-app-origins-sdk))
;; Tell browsers not to render our site as an iframe (prevent clickjacking)
(x-frame-options-header frame-ancestors)
@@ -573,7 +577,10 @@
;; doc) and `frame-src` (both the iframe doc and the top page,
;; whose `frame-src` gates the iframe's own navigations).
:data-app-connect-hosts (when-let [slug (data-app-slug request)]
- (drop-instance-origin (data-app-connect-src-hosts slug))))
+ (drop-instance-origin (data-app-connect-src-hosts slug)))
+ ;; Data apps and the EAJS embed page both render custom viz icons as blob: <img> URLs
+ :allow-blob-img? (or (data-app-iframe-request? request)
+ (request/embed-sdk-eajs-entrypoint? request)))
cors-headers (when (always-allow-cors? request response)
{"Access-Control-Allow-Origin" "*"
"Access-Control-Allow-Headers" "*"
diff --git a/test/metabase/api/common_test.clj b/test/metabase/api/common_test.clj
index 3c82d852c4b..54e450ee146 100644
--- a/test/metabase/api/common_test.clj
+++ b/test/metabase/api/common_test.clj
@@ -21,7 +21,7 @@
{:status 404
:body "Not found."
:headers {"Cache-Control" "max-age=0, no-cache, must-revalidate, proxy-revalidate"
- "Content-Security-Policy" (str (-> (@#'mw.security/content-security-policy-header nil false nil) vals first)
+ "Content-Security-Policy" (str (-> (@#'mw.security/content-security-policy-header nil false nil false) vals first)
" frame-ancestors 'none';")
"Content-Type" "text/plain"
"Expires" "Tue, 03 Jul 2001 06:00:00 GMT"
diff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.clj
index c59b2344e39..62f22e87b92 100644
--- a/test/metabase/server/middleware/security_test.clj
+++ b/test/metabase/server/middleware/security_test.clj
@@ -12,13 +12,18 @@
[metabase.util.json :as json]
[stencil.core :as stencil]))
+(defn- header->directive
+ [csp-header directive]
+ (-> csp-header
+ (str/split #"; *")
+ (as-> xs (filter #(str/starts-with? % (str directive " ")) xs))
+ first))
+
(defn- csp-directive
[directive]
(-> (mw.security/security-headers)
(get "Content-Security-Policy")
- (str/split #"; *")
- (as-> xs (filter #(str/starts-with? % (str directive " ")) xs))
- first))
+ (header->directive directive)))
(defn- csp-directive-from-response
[response directive]
@@ -839,6 +844,27 @@
(mt/with-temporary-setting-values [map-tile-server-url "/local/{z}/{x}/{y}.png"]
(is (= "img-src 'self' data:" (csp-directive "img-src"))))))))
+(defn- csp-directive-for-uri
+ "Runs the full security middleware for a request to `uri` and returns its CSP `directive`."
+ [uri directive]
+ (let [wrapped-handler (mw.security/add-security-headers
+ (fn [_request respond _raise]
+ (respond {:status 200 :headers {} :body "ok"})))
+ response (wrapped-handler {:headers {} :uri uri} identity identity)]
+ (header->directive (get-in response [:headers "Content-Security-Policy"]) directive)))
+
+(deftest csp-header-img-src-blob-eajs-embed-tests
+ (testing "the EAJS embed page (/embed/sdk/v1) allows blob: in img-src for custom viz icons"
+ (is (str/includes? (csp-directive-for-uri "/embed/sdk/v1" "img-src") "blob:")))
+ (testing "a future versioned entrypoint is covered on purpose"
+ (is (str/includes? (csp-directive-for-uri "/embed/sdk/v2" "img-src") "blob:")))
+ (testing "a normal app request does not allow blob: in img-src"
+ (is (not (str/includes? (csp-directive-for-uri "/" "img-src") "blob:"))))
+ (testing "other /embed/sdk/* URIs are served the static embed page and do not allow blob:"
+ (is (not (str/includes? (csp-directive-for-uri "/embed/sdk/foo" "img-src") "blob:"))))
+ (testing "a static/public embed request does not allow blob: in img-src"
+ (is (not (str/includes? (csp-directive-for-uri "/embed/question/abc" "img-src") "blob:")))))
+
(deftest csp-header-font-src-tests
(testing "font-src is restricted to 'self' and data: when no custom fonts are configured"
(mt/with-premium-features #{:whitelabel}