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
Improve errors when data app iframe is loaded without a parent or when iframe can't be loaded (#79169)
Timofey Kachalov45bf40939089
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsxindex bf06de3fdb4..7223955f782 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx@@ -14,6 +14,7 @@ import { useGetDataAppQuery } from "metabase-enterprise/api";import {DATA_APP_ERROR_MESSAGE_TYPE,+ DATA_APP_LOAD_TIMEOUT_MS,DATA_APP_READY_MESSAGE_TYPE,type DataAppBundleErrorMessage,} from "../../constants";@@ -54,6 +55,9 @@ export function DataAppView() {const [appReady, setAppReady] = useState(false);const [bundleError, setBundleError] =useState<DataAppBundleErrorMessage | null>(null);+ // Diagnostic string for the "Show error details" toggle; non-null once the+ // iframe fails to load (blocked / unreachable / hung), which drives the error UI.+ const [loadError, setLoadError] = useState<string | null>(null);// Reset whenever we navigate to a different app so a stale error/ready state// doesn't stick (the next app must re-earn the overlay being dropped).@@ -61,6 +65,7 @@ export function DataAppView() {useEffect(() => {setBundleError(null);setAppReady(false);+ setLoadError(null);}, [name]);// Read parent path → iframe src ONCE; never re-derive on later renders.@@ -155,6 +160,44 @@ export function DataAppView() {return () => window.removeEventListener("message", onMessage);}, []);+ // The iframe can fail to load without ever posting back — blocked by a CSP+ // `frame-src` violation, unreachable, or hung — which would otherwise leave the+ // loading overlay spinning forever. Surface an error via a CSP-violation signal+ // (instant, the cross-origin misconfiguration case) and a timeout backstop.+ useEffect(() => {+ // Stop once anything resolves the wait — including a `loadError` already set+ // by the CSP signal — so the timeout can't clobber a more specific message.+ if (!validName || appReady || bundleError || loadError) {+ return undefined;+ }++ const onViolation = (event: SecurityPolicyViolationEvent) => {+ if (+ event.effectiveDirective.startsWith("frame-src") &&+ event.blockedURI.startsWith(window.location.origin)+ ) {+ setLoadError(+ t`Frame ${event.blockedURI} was blocked by the browser’s content security policy.`,+ );+ }+ };++ document.addEventListener("securitypolicyviolation", onViolation);++ const timer = window.setTimeout(+ () =>+ setLoadError(+ t`The data app didn’t load within ${DATA_APP_LOAD_TIMEOUT_MS / 1000} seconds. The frame may be unreachable.`,+ ),+ DATA_APP_LOAD_TIMEOUT_MS,+ );++ return () => {+ document.removeEventListener("securitypolicyviolation", onViolation);+ window.clearTimeout(timer);+ };+ }, [validName, appReady, bundleError, loadError]);+if (!validName) {return (<NotFound@@ -237,6 +280,16 @@ export function DataAppView() {);}+ if (loadError) {+ return (+ <GenericError+ title={t`Couldn’t load this data app`}+ message={t`This data app didn’t load. It may have been blocked or is unreachable. Try refreshing the page, or go back.`}+ details={loadError}+ />+ );+ }+return (<Box pos="relative" h="100%">{!appReady && (diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsxindex 3273a807bd5..7f650a19f7f 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx@@ -7,6 +7,7 @@ import { createMockDataApp } from "metabase-types/api/mocks";import {DATA_APP_ERROR_MESSAGE_TYPE,+ DATA_APP_LOAD_TIMEOUT_MS,DATA_APP_READY_MESSAGE_TYPE,} from "../../constants";@@ -183,4 +184,93 @@ describe("DataAppView", () => {expect(screen.getByTestId("data-app-loading")).toBeInTheDocument();});});++ describe("load failure", () => {+ /** Dispatch a `securitypolicyviolation` as if the browser blocked framing. */+ function dispatchFrameSrcViolation(blockedURI: string) {+ // jsdom has no `SecurityPolicyViolationEvent` constructor, so build a plain+ // Event and attach the two fields the handler reads.+ const event = new Event(+ "securitypolicyviolation",+ ) as SecurityPolicyViolationEvent;+ Object.assign(event, { effectiveDirective: "frame-src", blockedURI });+ act(() => {+ document.dispatchEvent(event);+ });+ }++ it("shows an error instead of spinning when framing is blocked by CSP", () => {+ setupIframe();+ expect(screen.getByTestId("data-app-loading")).toBeInTheDocument();++ dispatchFrameSrcViolation(window.location.origin);++ expect(+ screen.getByText("Couldn’t load this data app"),+ ).toBeInTheDocument();+ });++ it("shows an error when the iframe never signals it loaded", () => {+ jest.useFakeTimers();+ try {+ setupIframe();+ expect(screen.getByTestId("data-app-loading")).toBeInTheDocument();++ act(() => {+ jest.advanceTimersByTime(DATA_APP_LOAD_TIMEOUT_MS);+ });++ expect(+ screen.getByText("Couldn’t load this data app"),+ ).toBeInTheDocument();+ } finally {+ jest.useRealTimers();+ }+ });++ it("does not error once the app reports ready before the timeout", () => {+ jest.useFakeTimers();+ try {+ const iframe = setupIframe();++ postMessage(iframe.contentWindow, {+ type: DATA_APP_READY_MESSAGE_TYPE,+ });++ act(() => {+ jest.advanceTimersByTime(DATA_APP_LOAD_TIMEOUT_MS);+ });++ expect(+ screen.queryByText("Couldn’t load this data app"),+ ).not.toBeInTheDocument();+ expect(screen.getByTitle("Sales")).toBeInTheDocument();+ } finally {+ jest.useRealTimers();+ }+ });++ it("keeps the first error's reason — the timeout can't overwrite the CSP one", () => {+ jest.useFakeTimers();+ try {+ setupIframe();++ dispatchFrameSrcViolation(window.location.origin);++ act(() => {+ jest.advanceTimersByTime(DATA_APP_LOAD_TIMEOUT_MS);+ });++ // The specific CSP detail survives; the generic timeout copy never appears.+ expect(+ screen.getByText(/content security policy/i),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(/frame may be unreachable/i),+ ).not.toBeInTheDocument();+ } finally {+ jest.useRealTimers();+ }+ });+ });});diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/constants.tsindex 49df2b1f754..c9cd7f495b4 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts@@ -11,3 +11,10 @@ export type DataAppBundleErrorMessage = {};export const DATA_APP_READY_MESSAGE_TYPE = "metabase.data-app.ready" as const;++/**+ * How long to wait for the iframe to signal ready before assuming it failed to+ * load — blocked, unreachable, or hung — and showing an error instead of a+ * spinner that would otherwise never resolve.+ */+export const DATA_APP_LOAD_TIMEOUT_MS = 20_000;diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsxindex 752eea53f84..d4b26da87ac 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx@@ -105,6 +105,24 @@ function BundleHost({ name }: { name: string }) {);}+function DataAppStandaloneMessage({ message }: { message: string }) {+ return (+ <div+ style={{+ display: "flex",+ height: "100vh",+ alignItems: "center",+ justifyContent: "center",+ padding: 24,+ textAlign: "center",+ color: color("text-secondary"),+ }}+ >+ {message}+ </div>+ );+}+/*** Iframe-top React app. Reads the data-app name from the URL, mounts the* bundle, and gets out of the way. Any sub-routes the bundle navigates to@@ -114,11 +132,17 @@ function BundleHost({ name }: { name: string }) {export const DataAppIframeApp = () => {const name = useMemo(() => readNameFromUrl(), []);+ if (window.parent === window) {+ return (+ <DataAppStandaloneMessage+ message={t`This data app can’t be opened directly.`}+ />+ );+ }+if (!name) {return (- <div style={{ padding: 16, color: color("error") }}>- {t`Missing data-app name in URL`}- </div>+ <DataAppStandaloneMessage message={t`Missing data-app name in URL`} />);}diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsxindex c55295a2d2c..683e72f5be7 100644--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsx@@ -27,6 +27,17 @@ const mockedReadName = jest.mocked(readNameFromUrl);const mockedUseBundle = jest.mocked(useDataAppBundle);const mockedReport = jest.mocked(reportErrorToParent);+// A stand-in parent window, identity-distinct from `window` so the app reads as+// framed; a bare object covers the only member the code touches (`postMessage`).+const framedParent = { postMessage: jest.fn() } as unknown as Window;++function setFramed(framed: boolean) {+ Object.defineProperty(window, "parent", {+ configurable: true,+ value: framed ? framedParent : window,+ });+}+type SetupOpts = {name?: string | null;bundle?: ReturnType<typeof useDataAppBundle>;@@ -44,7 +55,20 @@ const setup = ({};describe("DataAppIframeApp", () => {- afterEach(() => jest.clearAllMocks());+ beforeEach(() => setFramed(true));+ afterEach(() => {+ setFramed(false);+ jest.clearAllMocks();+ });++ it("shows an error when opened directly as a top-level page (no parent frame)", () => {+ setFramed(false);+ setup();++ expect(+ screen.getByText("This data app can’t be opened directly."),+ ).toBeInTheDocument();+ });it("shows an error when the URL has no data-app name", () => {setup({ name: null });