The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Allow data app analytics through the instance's proxy (#84200)
Phoomparin Manof401779a3282
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.cljindex a719d850ca6..c01924a6a7d 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj@@ -21,14 +21,11 @@[metabase.api.routes.common :refer [+auth]][metabase.events.core :as events][metabase.remote-sync.core :as remote-sync]- [metabase.settings.core :as setting]- [metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.json :as json][metabase.util.malli.schema :as ms])(:import- (java.io ByteArrayInputStream)- (java.net URI)))+ (java.io ByteArrayInputStream)))(set! *warn-on-reflection* true)@@ -48,27 +45,6 @@;;; ------------------------------------------------ Helpers -------------------------------------------------(defn- metaplow-origin- "Origin of the configured Metaplow collector, without its `/api/send` path.- The data-app sandbox accepts origins, not URLs with paths."- []- (when-let [url (setting/get-value-of-type :string :metaplow-url)]- (try- (let [uri (URI. url)- scheme (some-> (.getScheme uri) u/lower-case-en)- host (.getHost uri)- port (.getPort uri)]- (when (and (#{"http" "https"} scheme) host)- (str scheme "://" host (when-not (= -1 port) (str ":" port)))))- (catch Exception _))))--(defn- bundle-allowed-hosts- "Origins the bundle may fetch, including the configured analytics collector."- [allowed-hosts]- (let [origin (metaplow-origin)]- (cond-> allowed-hosts- origin (conj origin))))-(defn- repo-status [](let [url (data-apps.apps/repo-url)]{:configured (some? url)@@ -411,12 +387,8 @@(if (and bundle (pos? (alength bundle)))(respond {:status 200:headers (-> bundle-response-headers- ;; JSON array of origins the sandboxed bundle may fetch/XHR. Include- ;; the configured product analytics collector so SDK analytics work- ;; without granting access to the collector for another environment.- ;; The iframe reads this to configure its Near-Membrane fetch allowlist.(assoc "X-Metabase-Data-App-Allowed-Hosts"- (json/encode (bundle-allowed-hosts (:allowed_hosts row))))+ (json/encode (:allowed_hosts row)))(cond-> etag (assoc "ETag" etag))):body (ByteArrayInputStream. bundle)})(respond {:status 404diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.cljindex bc0ba0123aa..d7617ec275b 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj@@ -221,24 +221,10 @@:allowed_hosts ["https://api.example.com"]);; publish the app so its bundle is served (crowberto, as a superuser, can read the collection)(data-app.resources/ensure-resources! (t2/select-one :model/DataApp :name "demo"))- (testing "the bundle response normalizes the configured product analytics origin"- (mt/with-temporary-setting-values- [metaplow-url "HTTPS://product-analytics-ingestion.metabase.com/api/send"]- (let [resp (mt/user-http-request-full-response :crowberto :get 200 "apps/demo/bundle")]- (is (= (json/encode ["https://api.example.com"- "https://product-analytics-ingestion.metabase.com"])- (get-in resp [:headers "X-Metabase-Data-App-Allowed-Hosts"]))))))- (testing "the configured staging origin replaces the production origin"- (mt/with-temporary-setting-values [metaplow-url "https://product-analytics-ingestion.staging.metabase.com/api/send"]- (let [resp (mt/user-http-request-full-response :crowberto :get 200 "apps/demo/bundle")]- (is (= (json/encode ["https://api.example.com"- "https://product-analytics-ingestion.staging.metabase.com"])- (get-in resp [:headers "X-Metabase-Data-App-Allowed-Hosts"]))))))- (testing "an unset product analytics URL leaves the app's allowlist unchanged"- (mt/with-temporary-setting-values [metaplow-url nil]- (let [resp (mt/user-http-request-full-response :crowberto :get 200 "apps/demo/bundle")]- (is (= (json/encode ["https://api.example.com"])- (get-in resp [:headers "X-Metabase-Data-App-Allowed-Hosts"])))))))))+ (testing "the bundle response includes only the app's configured allowed hosts"+ (let [resp (mt/user-http-request-full-response :crowberto :get 200 "apps/demo/bundle")]+ (is (= (json/encode ["https://api.example.com"])+ (get-in resp [:headers "X-Metabase-Data-App-Allowed-Hosts"]))))))))(deftest list-includes-allowed-hosts-test(mt/with-premium-features #{:data-apps}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.tsindex a35e97c58de..223e3a20884 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.ts@@ -3,11 +3,9 @@** By default the sandbox hard-blocks all network egress (see* `metabase/utils/scripts-sandbox/distortions-blocked-apis`). When an app- * declares `allowed_hosts` in its `data_app.yaml`, those origins — and ONLY- * those, never the Metabase origin, which stays reachable only via sanctioned- * SDK calls — become reachable through `fetch`/`XMLHttpRequest`. Host matching- * mirrors the CSP `connect-src` the backend emits for the same hosts, so the JS- * layer and the browser CSP layer agree.+ * declares `allowed_hosts` in its `data_app.yaml`, those origins become reachable+ * through `fetch`. The instance origin allows only `/api/analytics-proxy` for SDK+ * analytics. Other instance requests must use SDK calls. XHR stays blocked.** The wildcard semantics (`*.example.com` matches subdomains, not the apex)* intentionally match the backend's `approved-domain?`@@ -16,6 +14,8 @@* sandboxed browser realm — so keep the two in sync if either changes.*/+import { ANALYTICS_PROXY_PATH } from "embedding-sdk-shared/constants/analytics";+import type { SandboxBlockedNetworkListener, SandboxRealm } from "./types";interface AllowedOrigin {@@ -115,6 +115,7 @@ const getBlockedReason = (base: string,allowedHosts: string[],metabaseOrigin: string,+ analyticsProxyPath: string,): string | null => {const url = toUrl(input, base);@@ -123,6 +124,11 @@ const getBlockedReason = (}if (url.origin === metabaseOrigin) {+ // whitelist analytics proxy endpoint explicitly+ if (url.pathname === analyticsProxyPath) {+ return null;+ }+return `${url.origin} (the instance origin is reachable only via the SDK)`;}@@ -153,17 +159,21 @@ export const makeSandboxFetch = (allowedHosts: string[],label: string,onBlocked?: SandboxBlockedNetworkListener,-): typeof fetch | null => {- if (allowedHosts.length === 0) {- return null;- }-+): typeof fetch => {const realFetch = targetWindow.fetch.bind(targetWindow);const base = targetWindow.location.href;const metabaseOrigin = targetWindow.location.origin;+ const metabaseRoot = (targetWindow.MetabaseRoot ?? "/").replace(/\/+$/, "");+ const analyticsProxyPath = `${metabaseRoot}${ANALYTICS_PROXY_PATH}`;return function dataAppFetch(input: RequestInfo | URL, init?: RequestInit) {- const reason = getBlockedReason(input, base, allowedHosts, metabaseOrigin);+ const reason = getBlockedReason(+ input,+ base,+ allowedHosts,+ metabaseOrigin,+ analyticsProxyPath,+ );if (reason) {reportBlockedEvent(onBlocked, {diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.tsindex f1564c2ece2..5f37b097c94 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.ts@@ -94,10 +94,6 @@ describe("makeSandboxFetch", () => {location: { href: base, origin },});- it("returns null for an empty allowlist (keeps the sandbox hard block)", () => {- expect(makeSandboxFetch(window, [], "sales")).toBeNull();- });-it("allows listed hosts and blocks others", async () => {const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));const sandboxFetch = makeSandboxFetch(@@ -116,7 +112,7 @@ describe("makeSandboxFetch", () => {expect(realFetch).toHaveBeenCalledTimes(1);});- it("always blocks the Metabase origin, even if it's in allowed_hosts", async () => {+ it("blocks other Metabase paths, even if the origin is in allowed_hosts", async () => {const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));// The Metabase origin is mistakenly allowlisted — it must still be denied.const sandboxFetch = makeSandboxFetch(@@ -134,6 +130,41 @@ describe("makeSandboxFetch", () => {);expect(realFetch).not.toHaveBeenCalled();});++ it.each([+ { allowedHosts: [] },+ { allowedHosts: ["https://api.example.com"] },+ ])(+ "allows the analytics proxy with allowed_hosts $allowedHosts",+ async ({ allowedHosts }) => {+ const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));++ const sandboxFetch = makeSandboxFetch(+ fakeWindow(realFetch),+ allowedHosts,+ "sales",+ )!;++ const payload = {+ method: "POST",+ body: JSON.stringify({ schema: "test", data: [] }),+ credentials: "omit" as const,+ };++ await sandboxFetch("/api/analytics-proxy", payload);+ await sandboxFetch(new URL(`${origin}/api/analytics-proxy`), payload);+ await sandboxFetch(new Request(`${origin}/api/analytics-proxy`, payload));++ expect(realFetch.mock.calls).toEqual([+ ["/api/analytics-proxy", { ...payload, redirect: "manual" }],+ [+ new URL(`${origin}/api/analytics-proxy`),+ { ...payload, redirect: "manual" },+ ],+ [expect.any(Request), { redirect: "manual" }],+ ]);+ },+ );});describe("onBlocked reporting", () => {diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.tsindex f0b92e19ec2..1402057be35 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts@@ -18,8 +18,7 @@ const REALM_CREATING_CTOR_NAMES = [/*** Data-app Near-Membrane distortion callback. Reuses the shared* `utils/scripts-sandbox` callback (same fetch/XHR/DOM blocking as custom-viz), but- * gives `fetch` an allowlist when the app declares `allowed_hosts` — otherwise it- * falls through to the shared hard block (default: no network). `XMLHttpRequest` is+ * allows `fetch` to the analytics proxy and the app's `allowed_hosts`. `XMLHttpRequest` is* never allowlisted (it can't opt out of following a redirect to the instance), so* `blockHostRealmXhr` hard-blocks it. No per-plugin DOM scoping like custom-viz: a* data app is a full-page route owned by one bundle, with no sibling DOM.@@ -158,7 +157,7 @@ export function makeDistortionCallback(return createElementDistortion;}- if (sandboxFetch && value === targetWindow.fetch) {+ if (value === targetWindow.fetch) {return sandboxFetch;}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.tsindex a4b92491aaa..f8c85fd0520 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.ts@@ -76,12 +76,28 @@ describe("makeDistortionCallback", () => {expect(callback(win.XMLHttpRequest)).toBe(win.XMLHttpRequest);});- it("does not wrap fetch/XHR when allowed_hosts is empty (shared hard block stands)", () => {+ it("allows only the analytics proxy when allowed_hosts is empty", async () => {const win = fakeWindow();+ const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));+ win.fetch = realFetch;+const callback = makeDistortionCallback("sales", win, []);- // No wrapper is installed; the value passes through to the shared callback,- // whose default-deny block of fetch/XHR is covered by the shared module.- expect(callback(win.fetch)).toBe(win.fetch);++ // Restore the fetch's type signature from the distortion callback+ const distorted = callback(win.fetch) as typeof fetch;+ await distorted("/api/analytics-proxy", { method: "POST" });++ // Analytics proxy endpoint must not be blocked+ expect(realFetch).toHaveBeenCalledWith("/api/analytics-proxy", {+ method: "POST",+ redirect: "manual",+ });++ await expect(distorted("/api/user/current")).rejects.toThrow(+ /blocked fetch/,+ );++ expect(realFetch).toHaveBeenCalledTimes(1);expect(callback(win.XMLHttpRequest)).toBe(win.XMLHttpRequest);});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.tsindex a1e7c3a15f5..2a88f6c92e4 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts@@ -39,6 +39,7 @@ export interface SandboxRealm {fetch: typeof fetch;XMLHttpRequest: typeof XMLHttpRequest;location: { href: string; origin: string };+ MetabaseRoot?: string;}export interface SandboxBlockedNetworkInfo {diff --git a/frontend/src/embedding-sdk-bundle/analytics/snowplow.ts b/frontend/src/embedding-sdk-bundle/analytics/snowplow.tsindex 9e04977ec2d..428dfb38ea6 100644--- a/frontend/src/embedding-sdk-bundle/analytics/snowplow.ts+++ b/frontend/src/embedding-sdk-bundle/analytics/snowplow.ts@@ -6,6 +6,7 @@ import {import { version as reactVersion } from "react";import type { SdkStoreState } from "embedding-sdk-bundle/store/types";+import { ANALYTICS_PROXY_PATH } from "embedding-sdk-shared/constants/analytics";import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";import { isEmbedPreviewRequest } from "metabase/embedding/lib/auth/set-embed-preview-header";import { getSettings } from "metabase/settings";@@ -85,7 +86,7 @@ export function initSdkTracker({// the SDK tracker is new, so there's no legacy format to preserve.encodeBase64: false,// Deliver through the instance proxy, not the collector's tp2 path.- postPath: "/api/analytics-proxy",+ postPath: ANALYTICS_PROXY_PATH,// No cookies / localStorage: the SDK must not touch the host page's storage.stateStorageStrategy: "none",// v4 defaults this to true, and the test-cookie probe ignores stateStorageStrategy.diff --git a/frontend/src/embedding-sdk-shared/constants/analytics.ts b/frontend/src/embedding-sdk-shared/constants/analytics.tsnew file mode 100644index 00000000000..0acd09675b4--- /dev/null+++ b/frontend/src/embedding-sdk-shared/constants/analytics.ts@@ -0,0 +1 @@+export const ANALYTICS_PROXY_PATH = "/api/analytics-proxy";