Skip to content

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

Improve Data Apps sandboxing (#78938)

Timofey Kachalovb75261aba268
diff --git a/e2e/support/assets/data-apps/isolation/data_app.yaml b/e2e/support/assets/data-apps/isolation/data_app.yaml
new file mode 100644
index 00000000000..ae8da92b536
--- /dev/null
+++ b/e2e/support/assets/data-apps/isolation/data_app.yaml
@@ -0,0 +1,2 @@
+name: Isolation
+path: ./dist/index.js
diff --git a/e2e/support/assets/data-apps/isolation/src/App.tsx b/e2e/support/assets/data-apps/isolation/src/App.tsx
new file mode 100644
index 00000000000..9512ac66eea
--- /dev/null
+++ b/e2e/support/assets/data-apps/isolation/src/App.tsx
@@ -0,0 +1,82 @@
+import { useRef, useState } from "react";
+
+import { createProbes } from "./probes";
+import {
+ REACT_PROBES,
+ ReactProbeHost,
+ useProbeCustomElement,
+} from "./ReactProbes";
+import type { ReactMode } from "./types";
+import { describeError, getEnv } from "./utils";
+
+// A data app that, from inside the sandbox, probes each way a bundle might reach
+// across the isolation boundary and reports the first sign of the outcome:
+// `isolated:` (held) or `reached:` (crossed). The spec asserts every probe
+// reports `isolated:`.
+export default function App() {
+ const env = getEnv();
+ const [result, setResult] = useState("pending");
+ const [reactMode, setReactMode] = useState<ReactMode | null>(null);
+ const firedRef = useRef(false);
+
+ useProbeCustomElement(setResult);
+
+ // If a probe never reports, `no-probe-observed` fails the spec (the probe
+ // never fired) rather than hanging.
+ const arm = () =>
+ window.setTimeout(
+ () => setResult((r) => (r === "pending" ? "no-probe-observed" : r)),
+ 20000,
+ );
+
+ const fire = (run: () => void) => {
+ arm();
+
+ try {
+ run();
+ } catch (err) {
+ setResult(`isolated:${describeError(err)}`);
+ }
+ };
+
+ const probes = createProbes(env, setResult);
+
+ return (
+ <div data-testid="data-app-isolation" style={{ padding: 24 }}>
+ <h1>Isolation probe</h1>
+ <div data-testid="isolation-result">{result}</div>
+
+ <div style={{ display: "flex", gap: 8, marginTop: 16, flexWrap: "wrap" }}>
+ {probes.map((probe) => (
+ <button
+ key={probe.id}
+ data-testid={`isolation-${probe.id}`}
+ onClick={() => fire(probe.run)}
+ >
+ {probe.label}
+ </button>
+ ))}
+ {REACT_PROBES.map((probe) => (
+ <button
+ key={probe.id}
+ data-testid={`isolation-${probe.id}`}
+ onClick={() => {
+ arm();
+ firedRef.current = false;
+ setReactMode(probe.mode);
+ }}
+ >
+ {probe.label}
+ </button>
+ ))}
+ </div>
+
+ <ReactProbeHost
+ mode={reactMode}
+ env={env}
+ report={setResult}
+ firedRef={firedRef}
+ />
+ </div>
+ );
+}
diff --git a/e2e/support/assets/data-apps/isolation/src/BoundaryReporter.tsx b/e2e/support/assets/data-apps/isolation/src/BoundaryReporter.tsx
new file mode 100644
index 00000000000..8dec1906a38
--- /dev/null
+++ b/e2e/support/assets/data-apps/isolation/src/BoundaryReporter.tsx
@@ -0,0 +1,32 @@
+import { Component } from "react";
+import type { ReactNode } from "react";
+
+import { describeError } from "./utils";
+
+// Catches a gated-tag throw from the guest reconciler so it reports `isolated:`
+// rather than tearing the tree down. (`.message` may itself throw across the
+// membrane — read it defensively.)
+export class BoundaryReporter extends Component<
+ { onResult: (msg: string) => void; children: ReactNode },
+ { failed: boolean }
+> {
+ state = { failed: false };
+
+ static getDerivedStateFromError() {
+ return { failed: true };
+ }
+
+ componentDidCatch(error: unknown) {
+ let reason = "opaque";
+ try {
+ reason = describeError(error);
+ } catch {
+ // keep "opaque"
+ }
+ this.props.onResult(`isolated:${reason}`);
+ }
+
+ render() {
+ return this.state.failed ? null : this.props.children;
+ }
+}
diff --git a/e2e/support/assets/data-apps/isolation/src/ReactProbes.tsx b/e2e/support/assets/data-apps/isolation/src/ReactProbes.tsx
new file mode 100644
index 00000000000..4912d1e98a4
--- /dev/null
+++ b/e2e/support/assets/data-apps/isolation/src/ReactProbes.tsx
@@ -0,0 +1,128 @@
+import { createElement, useState } from "react";
+import type { MutableRefObject } from "react";
+
+import { BoundaryReporter } from "./BoundaryReporter";
+import type { IsolationTestEnv, ReactMode, ReactProbe, Report } from "./types";
+import { reportRealm } from "./utils";
+
+export const REACT_PROBES: ReactProbe[] = [
+ {
+ id: "react-about-blank",
+ label: "React iframe about:blank",
+ mode: "react-iframe-about-blank",
+ },
+ { id: "react-src", label: "React iframe src", mode: "react-iframe-src" },
+ {
+ id: "react-srcdoc",
+ label: "React iframe srcdoc",
+ mode: "react-iframe-srcdoc",
+ },
+ {
+ id: "inner-html",
+ label: "iframe via dangerouslySetInnerHTML",
+ mode: "react-inner-html",
+ },
+ {
+ id: "custom-element",
+ label: "custom element upgrade callback",
+ mode: "react-custom-element",
+ },
+];
+
+// Registered once; its upgrade callback fires from host React but runs as a
+// guest closure, so `window` here is the gated guest realm.
+export const useProbeCustomElement = (report: Report) => {
+ useState(() => {
+ const tag = "x-isolation-probe";
+
+ if (!customElements.get(tag)) {
+ customElements.define(
+ tag,
+ class extends HTMLElement {
+ connectedCallback() {
+ reportRealm(report, window, "custom-element");
+ }
+ },
+ );
+ }
+
+ return null;
+ });
+};
+
+type ReactProbeHostProps = {
+ mode: ReactMode | null;
+ env: IsolationTestEnv;
+ report: Report;
+ firedRef: MutableRefObject<boolean>;
+};
+
+export function ReactProbeHost({
+ mode,
+ env,
+ report,
+ firedRef,
+}: ReactProbeHostProps) {
+ return (
+ // Keyed on the mode so each probe gets a fresh boundary.
+ <BoundaryReporter key={mode ?? "none"} onResult={report}>
+ {mode === "react-iframe-about-blank" && (
+ <iframe
+ title="isolation-target"
+ ref={(element) => {
+ if (element && !firedRef.current) {
+ firedRef.current = true;
+ reportRealm(report, element.contentWindow, "react-about-blank");
+ }
+ }}
+ style={{ display: "none" }}
+ />
+ )}
+
+ {mode === "react-iframe-src" && (
+ <iframe
+ title="isolation-target"
+ src={`${env.instanceUrl}/`}
+ onLoad={(e) =>
+ reportRealm(report, e.currentTarget.contentWindow, "react-src")
+ }
+ style={{ display: "none" }}
+ />
+ )}
+
+ {mode === "react-iframe-srcdoc" && (
+ <iframe
+ title="isolation-target"
+ srcDoc={'<!doctype html><meta charset="utf-8">'}
+ onLoad={(e) =>
+ reportRealm(report, e.currentTarget.contentWindow, "react-srcdoc")
+ }
+ style={{ display: "none" }}
+ />
+ )}
+
+ {/* Markup, not a tag: the parser inserts the iframe, bypassing
+ `createElement`; the host markup guard must sanitize it. */}
+ {mode === "react-inner-html" && (
+ <div
+ ref={(host) => {
+ if (!host || firedRef.current) {
+ return;
+ }
+ firedRef.current = true;
+ const iframe = host.querySelector("iframe");
+ reportRealm(
+ report,
+ iframe ? iframe.contentWindow : null,
+ "inner-html",
+ );
+ }}
+ dangerouslySetInnerHTML={{
+ __html: `<iframe style="display:none"></iframe>`,
+ }}
+ />
+ )}
+ {mode === "react-custom-element" && createElement("x-isolation-probe")}
+ </BoundaryReporter>
+ );
+}
diff --git a/e2e/support/assets/data-apps/isolation/src/index.tsx b/e2e/support/assets/data-apps/isolation/src/index.tsx
new file mode 100644
index 00000000000..97a94779d6c
--- /dev/null
+++ b/e2e/support/assets/data-apps/isolation/src/index.tsx
@@ -0,0 +1,7 @@
+import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";
+
+import App from "./App";
+
+const factory: DataAppFactory = () => ({ component: App });
+
+export default factory;
diff --git a/e2e/support/assets/data-apps/isolation/src/probes.ts b/e2e/support/assets/data-apps/isolation/src/probes.ts
new file mode 100644
index 00000000000..748f2de8a1e
--- /dev/null
+++ b/e2e/support/assets/data-apps/isolation/src/probes.ts
@@ -0,0 +1,357 @@
+import type { IsolationTestEnv, Probe, Report } from "./types";
+import { blobUrl, describeError, reportRealm } from "./utils";
+
+// BFS the endowed object graph for a raw `Api` exposing a provisioning
+// endpoint; stop at the reference, never dispatch.
+const endowmentApi = (report: Report) => {
+ const bundle = (
+ window as unknown as {
+ METABASE_EMBEDDING_SDK_BUNDLE?: Record<string, unknown>;
+ }
+ ).METABASE_EMBEDDING_SDK_BUNDLE;
+
+ if (!bundle) {
+ report("isolated:no-sdk-bundle");
+ return;
+ }
+
+ const store =
+ typeof bundle.getSdkStore === "function"
+ ? (bundle.getSdkStore as () => unknown)()
+ : null;
+
+ const seen = new Set<unknown>();
+ const queue: unknown[] = [bundle, store];
+
+ for (let i = 0; i < queue.length && i < 5000; i++) {
+ const node = queue[i];
+
+ if (
+ !node ||
+ seen.has(node) ||
+ (typeof node !== "object" && typeof node !== "function")
+ ) {
+ continue;
+ }
+
+ seen.add(node);
+
+ const createUser = (
+ node as { endpoints?: Record<string, { initiate?: unknown }> }
+ ).endpoints?.createUser;
+
+ if (createUser && typeof createUser.initiate === "function") {
+ report("reached:endowment-provisioning-endpoint");
+ return;
+ }
+
+ let keys: string[] = [];
+
+ try {
+ keys = Object.keys(node as object).slice(0, 60);
+ } catch {
+ keys = [];
+ }
+
+ for (const key of keys) {
+ try {
+ queue.push((node as Record<string, unknown>)[key]);
+ } catch {
+ // getter threw — skip
+ }
+ }
+ }
+
+ report("isolated:no-provisioning-endpoint-in-endowments");
+};
+
+export const createProbes = (
+ env: IsolationTestEnv,
+ report: Report,
+): Probe[] => {
+ const realm = (win: Window | null | undefined, label: string) =>
+ reportRealm(report, win, label);
+
+ const parsedIframeRealm = (root: ParentNode, label: string) => {
+ const iframe = root.querySelector("iframe");
+
+ if (!iframe) {
+ report("isolated:no-parsed-iframe");
+ return;
+ }
+
+ document.body.appendChild(document.adoptNode(iframe));
+
+ realm((iframe as HTMLIFrameElement).contentWindow, label);
+ };
+
+ const parentStorageRead = (kind: "localStorage" | "sessionStorage") => {
+ const ancestor = window.parent as unknown as Record<string, Storage>;
+
+ if (!ancestor || (ancestor as unknown) === window) {
+ report("isolated:parent-is-self");
+ return;
+ }
+
+ const store = ancestor[kind];
+
+ report(
+ store && typeof store.length === "number"
+ ? `reached:parent-${kind}-${store.length}-keys`
+ : `isolated:no-${kind}`,
+ );
+ };
+
+ const parentFactoryUse = (kind: "indexedDB" | "caches") => {
+ const ancestor = window.parent as unknown as {
+ indexedDB: IDBFactory;
+ caches: CacheStorage;
+ };
+
+ if (!ancestor || (ancestor as unknown) === window) {
+ report("isolated:parent-is-self");
+ return;
+ }
+
+ if (kind === "indexedDB") {
+ ancestor.indexedDB.open("isolation-probe");
+ } else {
+ ancestor.caches.match("/");
+ }
+
+ report(`reached:parent-${kind}`);
+ };
+
+ return [
+ {
+ id: "create-element",
+ label: "document.createElement about:blank",
+ run: () => {
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+
+ realm(iframe.contentWindow, "create-element");
+ },
+ },
+ {
+ id: "function-constructor",
+ label: "fetch via Function constructor",
+ run: () => {
+ const makeFn = function () {}.constructor as (
+ ...args: string[]
+ ) => () => unknown;
+ const fetchFn = makeFn("return fetch")() as typeof fetch;
+
+ report(
+ fetchFn && fetchFn !== window.fetch
+ ? "reached:function-constructor-fetch"
+ : "isolated:function-constructor-gated",
+ );
+ },
+ },
+ {
+ id: "dom-parser",
+ label: "iframe via DOMParser",
+ run: () =>
+ parsedIframeRealm(
+ new DOMParser().parseFromString("<iframe></iframe>", "text/html")
+ .body,
+ "dom-parser",
+ ),
+ },
+ {
+ id: "range-fragment-iframe",
+ label: "iframe via Range.createContextualFragment",
+ run: () =>
+ parsedIframeRealm(
+ document.createRange().createContextualFragment("<iframe></iframe>"),
+ "range-fragment",
+ ),
+ },
+ {
+ id: "window-open",
+ label: "window.open realm",
+ run: () => {
+ const opened = window.open(env.instanceUrl, "_blank");
+
+ if (!opened) {
+ report("isolated:window-open-returned-null");
+ return;
+ }
+
+ window.setTimeout(() => {
+ realm(opened, "window-open");
+
+ try {
+ opened.close();
+ } catch {
+ // already gone
+ }
+ }, 1000);
+ },
+ },
+ {
+ id: "parent-cookie",
+ label: "host cookie via window.parent",
+ run: () => {
+ const ancestor = window.parent;
+
+ if (!ancestor || ancestor === window) {
+ report("isolated:parent-is-self");
+ return;
+ }
+
+ const cookie = ancestor.document.cookie;
+
+ report(
+ cookie && cookie.length > 0
+ ? `reached:parent-cookie-${cookie.length}-chars`
+ : "isolated:empty-cookie",
+ );
+ },
+ },
+ {
+ id: "parent-local-storage",
+ label: "host localStorage via window.parent",
+ run: () => parentStorageRead("localStorage"),
+ },
+ {
+ id: "parent-session-storage",
+ label: "host sessionStorage via window.parent",
+ run: () => parentStorageRead("sessionStorage"),
+ },
+ {
+ id: "parent-indexeddb",
+ label: "host indexedDB via window.parent",
+ run: () => parentFactoryUse("indexedDB"),
+ },
+ {
+ id: "parent-caches",
+ label: "host caches via window.parent",
+ run: () => parentFactoryUse("caches"),
+ },
+ {
+ id: "worker",
+ label: "Worker",
+ run: () => {
+ new Worker(blobUrl()).terminate();
+
+ report("reached:worker-constructed");
+ },
+ },
+ {
+ id: "shared-worker",
+ label: "SharedWorker",
+ run: () => {
+ new SharedWorker(blobUrl());
+
+ report("reached:shared-worker-constructed");
+ },
+ },
+ {
+ id: "service-worker",
+ label: "Service worker registration API",
+ run: () => {
+ const container = navigator.serviceWorker;
+
+ report(
+ container && typeof container.register === "function"
+ ? "reached:service-worker-reachable"
+ : "isolated:no-service-worker",
+ );
+ },
+ },
+ {
+ id: "dynamic-import",
+ label: "Dynamic import",
+ run: () => {
+ const dynamicImport = new Function("u", "return import(u)") as (
+ u: string,
+ ) => Promise<unknown>;
+
+ dynamicImport(`${env.instanceUrl}/api/apps/isolation/bundle`)
+ .then(() => report("reached:dynamic-import-evaluated"))
+ .catch((err) => report(`isolated:${describeError(err)}`));
+ },
+ },
+ {
+ id: "allowed-host-redirect",
+ label: "allowed_host redirect",
+ run: () => {
+ fetch("http://localhost:4444/redirect", {
+ method: "GET",
+ credentials: "include",
+ })
+ // An opaque / status-0 response means the sandbox fetch refused to
+ // follow the redirect across origins; a real response means it did.
+ .then((r) =>
+ report(
+ r.type === "opaqueredirect" || r.status === 0
+ ? `isolated:redirect-not-followed-${r.type}`
+ : `reached:redirect-followed-${r.type}-${r.status}`,
+ ),
+ )
+ .catch((err) => report(`isolated:${describeError(err)}`));
+ },
+ },
+ {
+ id: "font-face",
+ label: "credentialed GET via FontFace",
+ run: () => {
+ const font = new FontFace(
+ "isolation",
+ `url('${env.instanceUrl}/api/session/properties?font=1')`,
+ );
+
+ Promise.resolve(font.load()).catch(() => {});
+
+ report("reached:font-face-load");
+ },
+ },
+ {
+ id: "cookie-store",
+ label: "cookies via cookieStore",
+ run: () => {
+ const cookieStore = (
+ window as unknown as {
+ cookieStore?: { getAll?: () => Promise<unknown[]> };
+ }
+ ).cookieStore;
+
+ if (!cookieStore?.getAll) {
+ report("isolated:no-cookie-store");
+ return;
+ }
+
+ cookieStore
+ .getAll()
+ .then((all) =>
+ report(
+ all && all.length > 0
+ ? `reached:cookie-store-${all.length}-cookies`
+ : "isolated:cookie-store-empty",
+ ),
+ )
+ .catch((err) => report(`isolated:${describeError(err)}`));
+ },
+ },
+ {
+ id: "perf-resource-timing",
+ label: "host URLs via resource timing",
+ run: () => {
+ const count = performance.getEntriesByType("resource").length;
+
+ report(
+ count > 0
+ ? `reached:resource-timing-${count}-urls`
+ : "isolated:no-entries",
+ );
+ },
+ },
+ {
+ id: "endowment-api",
+ label: "Raw API via endowed SDK bundle",
+ run: () => endowmentApi(report),
+ },
+ ];
+};
diff --git a/e2e/support/assets/data-apps/isolation/src/types.ts b/e2e/support/assets/data-apps/isolation/src/types.ts
new file mode 100644
index 00000000000..bc99b24cc4d
--- /dev/null
+++ b/e2e/support/assets/data-apps/isolation/src/types.ts
@@ -0,0 +1,14 @@
+export type IsolationTestEnv = { instanceUrl: string };
+
+export type Report = (result: string) => void;
+
+export type Probe = { id: string; label: string; run: () => void };
+
+export type ReactMode =
+ | "react-iframe-about-blank"
+ | "react-iframe-src"
+ | "react-iframe-srcdoc"
+ | "react-inner-html"
+ | "react-custom-element";
+
+export type ReactProbe = { id: string; label: string; mode: ReactMode };
diff --git a/e2e/support/assets/data-apps/isolation/src/utils.ts b/e2e/support/assets/data-apps/isolation/src/utils.ts
new file mode 100644
index 00000000000..772af03cd99
--- /dev/null
+++ b/e2e/support/assets/data-apps/isolation/src/utils.ts
@@ -0,0 +1,78 @@
+import type { IsolationTestEnv, Report } from "./types";
+
+export const getEnv = (): IsolationTestEnv => {
+ const env = (
+ globalThis as { __METABASE_DATA_APP_TEST_ENV__?: IsolationTestEnv }
+ ).__METABASE_DATA_APP_TEST_ENV__;
+
+ if (!env) {
+ throw new Error("isolation fixture: missing test env");
+ }
+
+ return env;
+};
+
+export const describeError = (err: unknown): string =>
+ (err as { message?: string })?.message ?? String(err);
+
+export const blobUrl = () =>
+ URL.createObjectURL(new Blob([""], { type: "text/javascript" }));
+
+export const htmlDocIframe = () => {
+ const doc = document.implementation.createHTMLDocument("x");
+ const iframe = doc.createElement("iframe");
+
+ doc.body.appendChild(iframe);
+
+ return iframe;
+};
+
+export const xmlDocIframe = () => {
+ const doc = document.implementation.createDocument(
+ "http://www.w3.org/1999/xhtml",
+ "html",
+ );
+ const iframe = doc.createElement("iframe") as HTMLIFrameElement;
+
+ doc.documentElement.appendChild(iframe);
+
+ return iframe;
+};
+
+export const templateIframe = () => {
+ const template = document.createElement("template");
+ const iframe = template.content.ownerDocument.createElement(
+ "iframe",
+ ) as HTMLIFrameElement;
+
+ template.content.appendChild(iframe);
+
+ return iframe;
+};
+
+export const realmVerdict = (
+ realm: Window | null | undefined,
+ label: string,
+) => {
+ if (!realm || realm === window) {
+ return `isolated:${label}-is-self`;
+ }
+
+ const realmFetch = realm.fetch;
+
+ return realmFetch && realmFetch !== window.fetch
+ ? `reached:${label}-realm`
+ : `isolated:${label}-gated`;
+};
+
+export const reportRealm = (
+ report: Report,
+ realm: Window | null | undefined,
+ label: string,
+) => {
+ try {
+ report(realmVerdict(realm, label));
+ } catch (err) {
+ report(`isolated:${describeError(err)}`);
+ }
+};
diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx
index c7747d9569a..9358e967e71 100644
--- a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx
+++ b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx
@@ -113,6 +113,43 @@ function QueryStates() {
);
}
+function DownloadQuestionPage() {
+ const { downloadQuestionId } = getTestEnv();
+
+ return (
+ <div data-testid="data-app-download-question" style={{ padding: 24 }}>
+ <h1>Download question</h1>
+ <div style={{ height: 360 }}>
+ {downloadQuestionId != null ? (
+ <StaticQuestion questionId={downloadQuestionId} withDownloads />
+ ) : (
+ <div data-testid="download-question-loading">…</div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// An InteractiveQuestion on a single-column (count) query, so a spec can switch it
+// to a custom viz — the example `demo-viz` requires exactly one result column.
+function CustomVizPage() {
+ const { scalarQuery } = getTestEnv();
+ const q = useMetabaseQueryObject(scalarQuery);
+
+ return (
+ <div data-testid="data-app-custom-viz" style={{ padding: 24 }}>
+ <h1>Custom viz</h1>
+ <div style={{ height: 360 }}>
+ {q.query ? (
+ <InteractiveQuestion card={{ query: q.query }} />
+ ) : (
+ <div data-testid="custom-viz-loading">…</div>
+ )}
+ </div>
+ </div>
+ );
+}
+
function StaticQuestionPage() {
const { questionQuery } = getTestEnv();
const q = useMetabaseQueryObject(questionQuery);
@@ -131,6 +168,34 @@ function StaticQuestionPage() {
);
}
+// Data apps may not run native SQL: the backend rejects native queries from the
+// `data-app` client. The `card` prop takes a raw query with no native/structured
+// check, so this page hand-builds a native query to prove the backend refuses it.
+function NativeQueryPage() {
+ const { nativeQuery } = getTestEnv();
+
+ if (!nativeQuery) {
+ return <div data-testid="data-app-native-query">no-native-query-env</div>;
+ }
+
+ return (
+ <div data-testid="data-app-native-query" style={{ padding: 24 }}>
+ <h1>Native query</h1>
+ <div style={{ height: 360 }}>
+ <StaticQuestion
+ card={{
+ query: {
+ type: "native",
+ database: nativeQuery.database,
+ native: { query: nativeQuery.query },
+ },
+ }}
+ />
+ </div>
+ </div>
+ );
+}
+
function Combinators() {
const combinators = getTestEnv().combinators!;
const countAgg = aggregations.count();
@@ -383,6 +448,9 @@ const ROUTES: Record<string, ComponentType> = {
"/isolation": Isolation,
"/query-states": QueryStates,
"/static-question": StaticQuestionPage,
+ "/native-query": NativeQueryPage,
+ "/download-question": DownloadQuestionPage,
+ "/custom-viz": CustomVizPage,
"/combinators": Combinators,
"/actions": Actions,
"/clipboard": Clipboard,
diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx
index 97a94779d6c..673040288e4 100644
--- a/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx
+++ b/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx
@@ -1,7 +1,13 @@
import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";
import App from "./App";
+import { getTestEnv } from "./test-env";
-const factory: DataAppFactory = () => ({ component: App });
+const factory: DataAppFactory = () => ({
+ component: App,
+ providerProps: {
+ allowedCustomVisualizations: getTestEnv().allowedCustomVisualizations,
+ },
+});
export default factory;
diff --git a/e2e/support/helpers/build-data-app-fixture.mjs b/e2e/support/helpers/build-data-app-fixture.mjs
index abc41f12ed2..1d18213b3fe 100644
--- a/e2e/support/helpers/build-data-app-fixture.mjs
+++ b/e2e/support/helpers/build-data-app-fixture.mjs
@@ -43,9 +43,23 @@ const { dataAppConfig } = await import(pathToFileURL(dataAppDevEntry).href);
process.chdir(appDir);
+const buildInfoDefine = Object.fromEntries(
+ [
+ "VERSION",
+ "GIT_BRANCH",
+ "GIT_COMMIT_SHA",
+ "BUILD_TIME",
+ "EMBEDDING_SDK_BUNDLE_HOST",
+ ].map((key) => [`process.env.${key}`, '""']),
+);
+
await build({
root: appDir,
configFile: false,
logLevel: "warn",
+ define: {
+ ...buildInfoDefine,
+ "process.env.IS_EMBEDDING_SDK": '"true"',
+ },
plugins: dataAppConfig().plugins,
});
diff --git a/e2e/support/helpers/data-app-test-env.ts b/e2e/support/helpers/data-app-test-env.ts
index 8e177e682a8..1a866eba5a4 100644
--- a/e2e/support/helpers/data-app-test-env.ts
+++ b/e2e/support/helpers/data-app-test-env.ts
@@ -13,6 +13,17 @@ import type { LocalFieldReference } from "@metabase/embedding-sdk-react/data-app
export type DataAppTestEnv = {
scalarQuery: { source: TableSource; aggregations: CountAggregation[] };
questionQuery: { source: TableSource };
+ /**
+ * `/download-question` page: the id of a saved CHART question (so a `.png`
+ * export is offered). Passed in because the id tracks the Cypress snapshot.
+ */
+ downloadQuestionId?: number;
+ /**
+ * `custom:`-prefixed plugin identifiers the app allows the SDK to load (e.g.
+ * `["custom:demo-viz"]`). The fixture forwards this to the SDK provider's
+ * `allowedCustomVisualizations`, which hard-gates custom-viz loading.
+ */
+ allowedCustomVisualizations?: `custom:${string}`[];
/**
* `/sandboxing` page: URLs it fetches to probe the sandbox's `allowed_hosts`
* gate. `allowedUrl` is expected to be in `allowed_hosts`, `blockedUrl` is not.
@@ -48,6 +59,13 @@ export type DataAppTestEnv = {
actionId?: number;
/** `/actions` page: the parameters the page passes to `execute()`. */
actionParams?: Record<string, string | number>;
+ /**
+ * `/native-query` page: a hand-built native query the app renders through
+ * `<StaticQuestion card={{ query }}>`. Data apps aren't allowed to run native
+ * SQL (the backend rejects it for the `data-app` client), so the page exists to
+ * assert that rejection.
+ */
+ nativeQuery?: { database: number; query: string };
};
// The queries use the SDK's `source` API (`{ type: "table", id }`); the database
diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.ts
index d836595bad8..4a62f47edf5 100644
--- a/e2e/support/helpers/e2e-data-app-helpers.ts
+++ b/e2e/support/helpers/e2e-data-app-helpers.ts
@@ -117,7 +117,12 @@ export const mockDataApp = <TestEnv = DataAppTestEnv>(
{
statusCode: 200,
headers: {
- "content-type": "text/javascript",
+ // Match the REAL bundle endpoint (`data_apps/api.clj`), which serves
+ // `application/javascript` + `nosniff`. The runtime fetch-and-evals the
+ // bundle, so the type is irrelevant there — but a stricter mock (e.g.
+ // `text/plain`) would diverge from production, so keep it aligned.
+ "content-type": "application/javascript",
+ "X-Content-Type-Options": "nosniff",
"X-Metabase-Data-App-Allowed-Hosts": JSON.stringify(allowedHosts),
},
body: prelude + bundleCode,
diff --git a/e2e/test/scenarios/data-apps/custom-viz.cy.spec.ts b/e2e/test/scenarios/data-apps/custom-viz.cy.spec.ts
new file mode 100644
index 00000000000..a5ec3590cfa
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/custom-viz.cy.spec.ts
@@ -0,0 +1,53 @@
+import {
+ DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,
+ DATA_APP_NAME as APP_NAME,
+ visitDataAppRoute as visitAppRoute,
+} from "e2e/support/helpers";
+
+import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";
+
+const { H } = cy;
+
+describe("scenarios > data apps > custom visualizations", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ // Enabling custom viz requires CSP image loading on, then the feature toggle.
+ H.updateSetting("csp-img-enabled", true);
+ H.updateSetting("custom-viz-enabled", true);
+ // Install the example plugin (identifier "demo-viz") straight through the API.
+ H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);
+ });
+
+ it("renders a custom visualization inside a data app", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: {
+ ...TEST_ENV,
+ // Opt the SDK into loading the custom viz inside the data app; without this
+ // allowlist the SDK never surfaces or loads the plugin.
+ allowedCustomVisualizations: [H.CUSTOM_VIZ_DISPLAY], // "custom:demo-viz"
+ },
+ });
+
+ 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();
+
+ // The custom viz's own DOM proves it loaded + rendered inside the data app.
+ cy.findByTestId("demo-viz-click-target", { timeout: 30000 }).should(
+ "be.visible",
+ );
+ });
+ });
+});
diff --git a/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts b/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts
index c3f956e8cfa..581065ba323 100644
--- a/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts
@@ -118,11 +118,13 @@ describe("scenarios > data apps > sandbox & isolation", () => {
cy.findByTestId("probe-innerhtml").should("have.text", "stripped");
- // XHR obeys the same allowlist as fetch.
+ // XHR is hard-blocked entirely — data apps are fetch-only. It can't opt out
+ // of following a redirect back to the instance, so it's never allowlisted
+ // like fetch: both blocked and allowed hosts are refused.
cy.findByTestId("blocked-xhr-result").should("contain", "blocked");
cy.findByTestId("allowed-xhr-result", { timeout: 30000 }).should(
- "have.text",
- "ok: 200",
+ "contain",
+ "blocked",
);
});
});
@@ -188,7 +190,9 @@ describe("scenarios > data apps > sandbox & isolation", () => {
expect(csp).to.contain("frame-ancestors 'self'");
expect(csp).to.contain("default-src 'none'");
expect(csp).to.contain("form-action 'none'");
- expect(csp).to.contain("'unsafe-eval'");
+ // The data-app document deliberately does NOT grant 'unsafe-eval' — it's
+ // confined to the sandbox-host realm doc (see the BE sandbox-host-endpoint-test).
+ expect(csp).to.not.contain("'unsafe-eval'");
expect(String(res.headers["x-frame-options"] ?? "")).to.match(
/sameorigin/i,
);
diff --git a/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts b/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts
new file mode 100644
index 00000000000..dbad5a01357
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/sandboxing_isolation.cy.spec.ts
@@ -0,0 +1,214 @@
+const { H } = cy;
+
+const APP_NAME = "isolation";
+const APP_DISPLAY_NAME = "Isolation";
+
+type IsolationTestEnv = { instanceUrl: string };
+
+describe("scenarios > data apps > sandbox isolation", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ });
+
+ const setUp = () => {
+ const instanceUrl = Cypress.config("baseUrl") ?? "";
+ const testEnv: IsolationTestEnv = { instanceUrl };
+
+ H.mockDataApp(APP_NAME, { displayName: APP_DISPLAY_NAME, testEnv });
+ H.openDataApp(APP_NAME);
+ };
+
+ /**
+ * Click a probe and assert it reported that the boundary held. Every probe
+ * stops at the first sign it reached across the boundary: `isolated:` means it
+ * did not, `reached:` means it did. `pending` / `no-probe-observed` mean the
+ * probe never fired, which is also a failure — none of those contain
+ * `isolated:`, so a single assertion covers all three.
+ */
+ const runProbe = (buttonTestId: string) => {
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId(buttonTestId).scrollIntoView().click();
+
+ cy.findByTestId("isolation-result", { timeout: 30000 })
+ .should("not.have.text", "pending")
+ .invoke("text")
+ .then((text) => {
+ cy.log(`isolation-result: ${text}`);
+ expect(text, "the boundary held").to.contain("isolated:");
+ });
+ });
+ };
+
+ /**
+ * For the probes whose element is refused during React's own render pass.
+ *
+ * The guard throws from `createElement` inside the reconciler, and the app's
+ * `BoundaryReporter` never catches it: that boundary is declared in the GUEST
+ * realm while HOST React renders the tree, and React's error-boundary detection
+ * does not survive the membrane. The throw therefore reaches the host boundary
+ * and takes the data app down — which is the correct outcome, but it also
+ * destroys the probe, so there is no `isolation-result` left to read. Assert on
+ * the guard's own message instead.
+ */
+ const runProbeExpectingGuard = (buttonTestId: string) => {
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId(buttonTestId).scrollIntoView().click();
+ });
+
+ cy.contains("blocked host createElement", { timeout: 30000 }).should(
+ "exist",
+ );
+ };
+
+ it("keeps a document.createElement about:blank iframe within the gated realm", () => {
+ setUp();
+ runProbe("isolation-create-element");
+ });
+
+ it("gates a host-React about:blank iframe", () => {
+ setUp();
+ runProbeExpectingGuard("isolation-react-about-blank");
+ });
+
+ it("gates an iframe pointing at Metabase itself", () => {
+ setUp();
+ runProbeExpectingGuard("isolation-react-src");
+ });
+
+ it("gates a srcdoc iframe", () => {
+ setUp();
+ runProbeExpectingGuard("isolation-react-srcdoc");
+ });
+
+ it("keeps a window.open realm within the gated realm", () => {
+ setUp();
+ runProbe("isolation-window-open");
+ });
+
+ it("gates the Worker constructor", () => {
+ setUp();
+ runProbe("isolation-worker");
+ });
+
+ it("gates the SharedWorker constructor", () => {
+ setUp();
+ runProbe("isolation-shared-worker");
+ });
+
+ it("gates the service worker registration API", () => {
+ setUp();
+ runProbe("isolation-service-worker");
+ });
+
+ it("gates dynamic import", () => {
+ setUp();
+ runProbe("isolation-dynamic-import");
+ });
+
+ it("keeps a dangerouslySetInnerHTML iframe within the gated realm", () => {
+ setUp();
+ runProbe("isolation-inner-html");
+ });
+
+ it("keeps a Function-constructor fetch gated", () => {
+ setUp();
+ runProbe("isolation-function-constructor");
+ });
+
+ it("keeps a DOMParser iframe within the gated realm", () => {
+ setUp();
+ runProbe("isolation-dom-parser");
+ });
+
+ it("keeps a raw API out of the SDK endowments", () => {
+ setUp();
+ runProbe("isolation-endowment-api");
+ });
+
+ it("gates document.cookie on the parent realm", () => {
+ setUp();
+ runProbe("isolation-parent-cookie");
+ });
+
+ it("gates localStorage on the parent realm", () => {
+ setUp();
+ runProbe("isolation-parent-local-storage");
+ });
+
+ it("gates sessionStorage on the parent realm", () => {
+ setUp();
+ runProbe("isolation-parent-session-storage");
+ });
+
+ it("gates indexedDB on the parent realm", () => {
+ setUp();
+ runProbe("isolation-parent-indexeddb");
+ });
+
+ it("gates caches on the parent realm", () => {
+ setUp();
+ runProbe("isolation-parent-caches");
+ });
+
+ it("gates FontFace.load", () => {
+ setUp();
+ runProbe("isolation-font-face");
+ });
+
+ it("gates cookieStore", () => {
+ setUp();
+ runProbe("isolation-cookie-store");
+ });
+
+ it("gates performance resource timing", () => {
+ setUp();
+ runProbe("isolation-perf-resource-timing");
+ });
+
+ it("keeps a Range.createContextualFragment iframe within the gated realm", () => {
+ setUp();
+ runProbe("isolation-range-fragment-iframe");
+ });
+
+ it("keeps a custom element's upgrade callback in the gated realm", () => {
+ setUp();
+ runProbe("isolation-custom-element");
+ });
+
+ it("gates an allowed_host redirect to the instance", () => {
+ const instanceUrl = Cypress.config("baseUrl") ?? "";
+ const cors = {
+ "Access-Control-Allow-Origin": instanceUrl,
+ "Access-Control-Allow-Credentials": "true",
+ };
+
+ // An allowed host that answers the CORS preflight for a credentialed GET,
+ // then 307-redirects it to the instance origin. The sandbox fetch checks only
+ // the initial (allowed) URL; it must not follow the redirect across origins.
+ cy.intercept("OPTIONS", "http://localhost:4444/**", {
+ statusCode: 204,
+ headers: {
+ ...cors,
+ "Access-Control-Allow-Methods": "GET",
+ "Access-Control-Allow-Headers": "content-type",
+ },
+ });
+ cy.intercept("GET", "http://localhost:4444/**", (req) => {
+ req.reply({
+ statusCode: 307,
+ headers: { ...cors, Location: `${instanceUrl}/api/session/properties` },
+ });
+ });
+
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: { instanceUrl },
+ allowedHosts: ["http://localhost:4444"],
+ });
+ H.openDataApp(APP_NAME);
+
+ runProbe("isolation-allowed-host-redirect");
+ });
+});
diff --git a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts b/e2e/test/scenarios/data-apps/sdk.cy.spec.ts
index 522eabdffe9..18d526a8894 100644
--- a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts
+++ b/e2e/test/scenarios/data-apps/sdk.cy.spec.ts
@@ -1,4 +1,5 @@
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { ORDERS_BY_YEAR_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
import {
DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,
DATA_APP_NAME as APP_NAME,
@@ -200,4 +201,37 @@ describe("scenarios > data apps > SDK runtime", () => {
});
});
});
+
+ describe("question downloads", () => {
+ beforeEach(() => {
+ cy.deleteDownloadsFolder();
+ });
+
+ it("downloads a chart question as PNG", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: {
+ ...TEST_ENV,
+ downloadQuestionId: ORDERS_BY_YEAR_QUESTION_ID,
+ },
+ });
+
+ visitAppRoute("download-question");
+
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ // The chart must render before its toolbar (and the download button) exist.
+ cy.findByTestId("data-app-download-question", {
+ timeout: 30000,
+ }).should("exist");
+ cy.findByTestId("question-download-widget-button", { timeout: 30000 })
+ .should("be.visible")
+ .click();
+
+ cy.findByText(".png").click();
+ cy.findByTestId("download-results-button").click();
+ });
+
+ cy.verifyDownload(".png", { contains: true });
+ });
+ });
});
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
index 0ddf54020a5..3b2f9d6b45d 100644
--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
@@ -23,8 +23,8 @@
;;; ------------------------------------------------ Constants ------------------------------------------------
-;; Slug must not collide with the literal `repo-status` sub-route.
-(def ^:private slug-regex #"(?!repo-status$)[^/]+")
+;; Slug must not collide with the literal `repo-status`/`sandbox-host` sub-routes.
+(def ^:private slug-regex #"(?!repo-status$|sandbox-host$)[^/]+")
(def ^:private bundle-response-headers
;; `no-cache` so the browser may cache but must revalidate via
@@ -87,6 +87,41 @@
(api/check-superuser)
(repo-status))
+;;; --------------------------------------------- Sandbox host ---------------------------------------------
+
+(def ^:private sandbox-host-html
+ "Empty document loaded as the Near-Membrane realm iframe. It only needs to exist and carry the
+ CSP below; the membrane populates the realm itself."
+ "<!doctype html><html><head><meta charset=\"utf-8\"></head><body></body></html>")
+
+(def ^:private sandbox-host-csp
+ "CSP for the sandbox realm document ONLY.
+
+ `'unsafe-eval'` is what Near-Membrane needs to evaluate the app bundle inside the realm.
+ Serving the realm from its own document is what lets the data-app document drop that grant:
+ an `about:blank` realm would instead inherit the data-app document's CSP, forcing
+ `'unsafe-eval'` there and handing an attacker `eval`/`Function` in the host realm.
+
+ `default-src 'none'` gives the realm no network of its own — unlike the inherited case, where
+ it would pick up the data-app document's `connect-src` (which includes the instance origin)."
+ (str "default-src 'none'; "
+ "script-src 'unsafe-eval'; "
+ "frame-ancestors 'self';"))
+
+(api.macros/defendpoint :get "/sandbox-host" :- :any
+ "Serve the document used as the `src` of the Near-Membrane realm iframe, carrying a
+ per-document CSP that confines `'unsafe-eval'` to that realm. See [[sandbox-host-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})
+
;;; ------------------------------------------------ Apps ------------------------------------------------
(defn- data-app-response
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj
index e819ef51735..ca77e97b87c 100644
--- a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj
@@ -302,3 +302,37 @@
(is (=? {:enabled true}
(mt/user-http-request :crowberto :put 200 "apps/demo" {:enabled true})))
(is (=? {:name "demo"} (mt/user-http-request :crowberto :get 200 "apps/demo"))))))))
+
+(deftest sandbox-host-endpoint-test
+ (mt/with-premium-features #{:data-apps-preview}
+ (let [resp (mt/user-http-request-full-response :crowberto :get 200 "apps/sandbox-host")
+ headers (:headers resp)]
+ (testing "serves a minimal HTML document"
+ (is (str/includes? (:body resp) "<!doctype html>"))
+ (is (str/starts-with? (get headers "Content-Type") "text/html")))
+ (testing "carries the per-document CSP that confines 'unsafe-eval' to the realm"
+ ;; This grant is why the data-app document itself can drop 'unsafe-eval'
+ ;; (see `data-app-unsafe-eval-test`), and `default-src 'none'` means the
+ ;; realm has no network of its own rather than inheriting the data-app
+ ;; document's `connect-src` (which includes the instance origin).
+ (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 (str/includes? csp "frame-ancestors 'self'"))
+ (testing "and the endpoint's CSP wins over the global middleware one"
+ (is (not (str/includes? csp "'nonce-"))))))
+ (testing "is framable same-origin, overriding the global X-Frame-Options"
+ (is (= "SAMEORIGIN" (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"))))))
+ ;; `slug-regex` must exclude this literal, or `/apps/sandbox-host` would be
+ ;; routed as a data app named "sandbox-host" and 404.
+ (testing "the route is not shadowed by the /:slug route"
+ (mt/with-premium-features #{:data-apps-preview}
+ (mt/with-model-cleanup [:model/DataApp]
+ (create-app!)
+ (is (= 200 (:status (mt/user-http-request-full-response
+ :crowberto :get 200 "apps/sandbox-host"))))))))
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx
index 034bff4231a..a9f324bc841 100644
--- a/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx
@@ -25,6 +25,8 @@ import {
} from "virtual:metabase-data-app-dev-config";
import { createRoot } from "react-dom/client";
+import { DATA_APP_PROVIDER_PROP_KEYS } from "metabase-enterprise/data_apps/sandbox/types";
+
// The same baseline reset the production iframe loads (`iframe-vendors.ts`), so the
// dev preview matches production. style-loader injects it at runtime.
import "metabase-enterprise/data_apps/sandbox/iframe-baseline.css";
@@ -68,7 +70,7 @@ if (!root) {
const appRoot = createRoot(root);
-const sandbox = createDataAppSandbox({
+const sandboxPromise = createDataAppSandbox({
label: "dev",
targetWindow: window,
allowedHosts,
@@ -86,6 +88,7 @@ const sandbox = createDataAppSandbox({
});
async function loadAndRender() {
+ const sandbox = await sandboxPromise;
const res = await fetch(bundleUrl, { cache: "no-store" });
if (!res.ok) {
@@ -97,11 +100,18 @@ async function loadAndRender() {
const code = await res.text();
const { component: Component, providerProps } = sandbox.evaluate(code)();
+ const rawProviderProps = providerProps ?? {};
+ const safeProviderProps = Object.fromEntries(
+ DATA_APP_PROVIDER_PROP_KEYS.filter((key) => key in rawProviderProps).map(
+ (key) => [key, rawProviderProps[key]],
+ ),
+ );
+
appRoot.render(
<DataAppDevProvider
appSlug={appSlug}
authConfig={authConfig}
- {...providerProps}
+ {...safeProviderProps}
>
<Component />
</DataAppDevProvider>,
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts
index 32925360779..7cea5e4df37 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts
@@ -45,13 +45,17 @@ export const useDataAppBundle = (
return;
}
- const { component, providerProps } = instantiateDataAppBundle(
+ const { component, providerProps } = await instantiateDataAppBundle(
code,
name,
window,
allowedHosts,
);
+ if (cancelled) {
+ return;
+ }
+
setData({ component, providerProps });
};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.ts
index d60136027fc..c0ffe44179b 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.ts
@@ -43,7 +43,9 @@ function setup({
mockedFetch.mockResolvedValue({ code, allowedHosts });
}
if (app) {
- mockedInstantiate.mockReturnValue(app);
+ // Instantiating is async: Near-Membrane defers setup to the realm iframe's
+ // `load` event once the sandbox is given a realm-host document.
+ mockedInstantiate.mockResolvedValue(app);
}
return renderHook(() => useDataAppBundle("sales"));
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts
index cfcc0cac019..e46111f3251 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts
@@ -7,7 +7,7 @@ import { pick } from "underscore";
import * as sdkExports from "embedding-sdk-package";
import * as dataAppExports from "embedding-sdk-package/data-app";
-import { getSubpathSafeUrl } from "metabase/urls";
+import { DATA_APP_REALM_HOST_URL, getSubpathSafeUrl } from "metabase/urls";
import { createDataAppSandbox } from "metabase-enterprise/data_apps/sandbox/sandbox";
import {
DATA_APP_PROVIDER_PROP_KEYS,
@@ -107,16 +107,17 @@ export const fetchDataAppBundleCode = async (
* the iframe's own `window` — same realm as the React tree rendering the
* factory's component, so no cross-document mounting.
*/
-export const instantiateDataAppBundle = (
+export const instantiateDataAppBundle = async (
code: string,
label: string,
targetWindow: Window & typeof globalThis,
allowedHosts: string[] = [],
-): LoadedDataApp => {
- const sandbox = createDataAppSandbox({
+): Promise<LoadedDataApp> => {
+ const sandbox = await createDataAppSandbox({
label,
targetWindow,
allowedHosts,
+ realmHostUrl: getSubpathSafeUrl(DATA_APP_REALM_HOST_URL),
endowments: {
React,
reactDom: ReactDOM,
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts
index b6f9bbb82ce..825de2786ad 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts
@@ -101,7 +101,9 @@ describe("fetchDataAppBundleCode", () => {
describe("instantiateDataAppBundle", () => {
const setup = (factoryResult: unknown) => {
- mockedCreateSandbox.mockReturnValue({
+ // Sandbox creation is async — Near-Membrane defers setup to the realm
+ // iframe's `load` event once `iframeSrc` is set.
+ mockedCreateSandbox.mockResolvedValue({
// @ts-expect-error - the factory result is deliberately untyped: these tests
// feed the loader malformed values (`null`, a non-function `component`).
evaluate: () => () => factoryResult,
@@ -114,7 +116,17 @@ describe("instantiateDataAppBundle", () => {
afterEach(() => jest.clearAllMocks());
- it("returns the component and narrows providerProps to the allowed keys", () => {
+ it("points the sandbox at the realm-host document", async () => {
+ const { instantiate } = setup({ component: () => null });
+
+ await instantiate();
+
+ expect(mockedCreateSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({ realmHostUrl: "/api/apps/sandbox-host" }),
+ );
+ });
+
+ it("returns the component and narrows providerProps to the allowed keys", async () => {
const component = () => null;
const { instantiate } = setup({
component,
@@ -126,7 +138,7 @@ describe("instantiateDataAppBundle", () => {
},
});
- const loaded = instantiate();
+ const loaded = await instantiate();
expect(loaded.component).toBe(component);
expect(loaded.providerProps).toEqual({
@@ -137,10 +149,12 @@ describe("instantiateDataAppBundle", () => {
it.each<unknown>([{ component: "not a function" }, null])(
"throws when the factory returns %p",
- (factoryResult) => {
+ async (factoryResult) => {
const { instantiate } = setup(factoryResult);
- expect(instantiate).toThrow(/missing a `component` function/);
+ await expect(instantiate()).rejects.toThrow(
+ /missing a `component` function/,
+ );
},
);
});
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.ts
index 9a2fa4b30ad..a35e97c58de 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
@@ -177,49 +177,75 @@ export const makeSandboxFetch = (
);
}
- return realFetch(input, init);
+ // An allowlisted host could 30x to `<instance>/api/user`, which the browser
+ // would follow same-origin with the session cookie.
+ return realFetch(input, { ...init, redirect: "manual" });
};
};
-export const makeSandboxXhr = (
- targetWindow: SandboxRealm,
- allowedHosts: string[],
- label: string,
- onBlocked?: SandboxBlockedNetworkListener,
-): typeof XMLHttpRequest | null => {
- if (allowedHosts.length === 0) {
- return null;
+/**
+ * `XMLHttpRequest` is deliberately NOT allowlisted — it stays on the sandbox's
+ * hard block even for apps that declare `allowed_hosts`.
+ *
+ * A URL check can only run at `open()`, against the *initial* URL, and XHR has
+ * no way to opt out of following redirects (`fetch`'s `redirect: "manual"` has
+ * no XHR equivalent). So an allowlisted host could answer with a `307` to
+ * `<instance>/api/user` and the browser would follow it same-origin, carrying
+ * the session cookie — the privileged, cookie-authed request the allowlist
+ * exists to prevent. There is no way to make an allowlisted XHR safe, so the
+ * guest simply doesn't get one.
+ */
+
+const XHR_BLOCKED = new WeakSet<Window & typeof globalThis>();
+
+/**
+ * Makes `XMLHttpRequest` unusable in the data-app document's HOST realm, so the
+ * "data apps are fetch-only" rule holds for host-side code too — not just for
+ * the guest behind the membrane.
+ *
+ * Constructing one deliberately SUCCEEDS. Libraries feature-detect XHR by
+ * building an instance and probing it — Snowplow decides its transport with
+ * `'withCredentials' in new XMLHttpRequest()` — so throwing from the
+ * constructor takes the whole app down instead of letting callers route around
+ * XHR. The instance is inert instead: every method throws, and `withCredentials`
+ * is absent, so a CORS probe reports "unusable" and the caller falls back to a
+ * non-XHR transport of its own accord.
+ */
+export function blockHostRealmXhr(
+ targetWindow: Window & typeof globalThis,
+): void {
+ if (XHR_BLOCKED.has(targetWindow)) {
+ return;
}
+ XHR_BLOCKED.add(targetWindow);
- const NativeXhr = targetWindow.XMLHttpRequest;
- const base = targetWindow.location.href;
- const metabaseOrigin = targetWindow.location.origin;
- const SandboxXhr = class extends NativeXhr {
- open(
- method: string,
- url: string | URL,
- async: boolean = true,
- username?: string | null,
- password?: string | null,
- ): void {
- const reason = getBlockedReason(url, base, allowedHosts, metabaseOrigin);
-
- if (reason) {
- reportBlockedEvent(onBlocked, {
- api: "xhr",
- url: buildRequestUrl(url, base),
- reason,
- });
-
- throw new Error(
- `[data-app ${label}] blocked XMLHttpRequest to ${reason}`,
- );
- }
- super.open(method, url, async, username, password);
- }
+ const blocked = () => {
+ throw new Error(
+ "[data-app] blocked XMLHttpRequest: data apps are fetch-only",
+ );
};
- // The subclass inherits the static UNSENT/OPENED/… constants at runtime;
- // cast so the type matches the native constructor the membrane expects.
- return SandboxXhr as typeof XMLHttpRequest;
-};
+ class BlockedXMLHttpRequest {
+ readonly readyState = 0;
+ readonly status = 0;
+ open = blocked;
+ send = blocked;
+ abort = blocked;
+ setRequestHeader = blocked;
+ getResponseHeader = blocked;
+ getAllResponseHeaders = blocked;
+ overrideMimeType = blocked;
+ // Listener registration commonly happens before `open()`, and a probe that
+ // registers one shouldn't be the thing that fails — `send()` still throws.
+ addEventListener = () => {};
+ removeEventListener = () => {};
+ dispatchEvent = () => false;
+ }
+
+ Object.defineProperty(targetWindow, "XMLHttpRequest", {
+ configurable: false,
+ enumerable: true,
+ writable: false,
+ value: BlockedXMLHttpRequest,
+ });
+}
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.ts
index cea333cd2d4..f1564c2ece2 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
@@ -1,8 +1,4 @@
-import {
- isHostAllowed,
- makeSandboxFetch,
- makeSandboxXhr,
-} from "./allowed-hosts";
+import { isHostAllowed, makeSandboxFetch } from "./allowed-hosts";
import type { SandboxRealm } from "./types";
const u = (href: string) => new URL(href);
@@ -140,46 +136,6 @@ describe("makeSandboxFetch", () => {
});
});
-describe("makeSandboxXhr", () => {
- // jsdom's window origin is http://localhost — treat that as the Metabase origin.
- const mbOrigin = window.location.origin;
-
- it("returns null for an empty allowlist", () => {
- expect(makeSandboxXhr(window, [], "sales")).toBeNull();
- });
-
- it("gates open() against the allowlist", () => {
- const SandboxXhr = makeSandboxXhr(
- window,
- ["https://api.example.com"],
- "sales",
- );
- expect(SandboxXhr).not.toBeNull();
-
- const xhr = new SandboxXhr!();
- expect(() => xhr.open("GET", "https://evil.example.org/")).toThrow(
- /blocked XMLHttpRequest/,
- );
- // Allowed host: open() should not throw.
- expect(() => xhr.open("GET", "https://api.example.com/data")).not.toThrow();
- });
-
- it("always blocks the Metabase origin, even if it's in allowed_hosts", () => {
- const SandboxXhr = makeSandboxXhr(
- window,
- [mbOrigin, "https://api.example.com"],
- "sales",
- )!;
- const xhr = new SandboxXhr();
- expect(() => xhr.open("GET", `${mbOrigin}/api/user/current`)).toThrow(
- /reachable only via the SDK/,
- );
- expect(() => xhr.open("GET", "/api/user/current")).toThrow(
- /reachable only via the SDK/,
- );
- });
-});
-
describe("onBlocked reporting", () => {
const base = "https://mb.example.com/embed/apps/sales";
const origin = "https://mb.example.com";
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.ts
index 057ab52e82f..d9e5b862a3c 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.ts
@@ -1,16 +1,13 @@
import {
CREATE_ELEMENT,
CREATE_ELEMENT_NS,
+ getXmlElementLocalName,
} from "metabase/utils/scripts-sandbox/distortions-dom-mutate";
const isStyleTag = (tag: string) => tag.toLowerCase() === "style";
function isStyleQualifiedName(qualifiedName: string) {
- const localName = qualifiedName.includes(":")
- ? qualifiedName.slice(qualifiedName.indexOf(":") + 1)
- : qualifiedName;
-
- return isStyleTag(localName);
+ return isStyleTag(getXmlElementLocalName(qualifiedName));
}
/** The shared sandbox distortion callback, as the membrane types it. */
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts
index 0ed5f0ddaf0..ee0eaf50b7c 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts
@@ -1,6 +1,6 @@
import { makeSandboxDistortionCallback } from "metabase/utils/scripts-sandbox";
-import { makeSandboxFetch, makeSandboxXhr } from "./allowed-hosts";
+import { makeSandboxFetch } from "./allowed-hosts";
import { makeCreateElementDistortion } from "./create-element";
import type {
SandboxBlockedListener,
@@ -9,20 +9,13 @@ import type {
} from "./types";
/**
- * Data-app Near Membrane distortion callback.
- *
- * Reuses the shared callback from `utils/scripts-sandbox` — same blocking of
- * fetch/XHR/etc., same DOM-mutation sanitization, same dangerous-tag /
- * inline-handler / `javascript:`-URL filters as custom-viz — but, unlike
- * custom-viz, replaces the hard `fetch`/`XMLHttpRequest` block with an
- * allowlist when the app declares `allowed_hosts`. With no `allowed_hosts`
- * the wrappers are null and we fall through to the shared hard block, so the
- * default posture stays "no network".
- *
- * Data-app intentionally omits the per-plugin DOM scoping (decoy nodes
- * outside a `data-plugin-sandbox` subtree) that custom-viz uses: a data app
- * is a full-page route owned by a single admin-uploaded bundle, so there's
- * no sibling DOM to protect from.
+ * 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
+ * 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.
*/
export function makeDistortionCallback(
label: string,
@@ -54,12 +47,90 @@ export function makeDistortionCallback(
label,
onBlockedNetwork,
);
- const sandboxXhr = makeSandboxXhr(
- targetWindow,
- allowedHosts,
- label,
- onBlockedNetwork,
+
+ // Ancestor realms reachable from the sandboxed iframe.
+ // Near-Membrane remaps the guest's `window.parent` to the real parent (the
+ // same-origin main app) — a realm it never wrapped, so its `fetch` isn't gated.
+ // Redirect every ancestor window, plus the frame element reachable via
+ // `ownerDocument.defaultView`, to the gated target: a valid Window->Window
+ // distortion, so `window.parent`/`frameElement` resolve to THIS realm (where
+ // `fetch`/`XMLHttpRequest` are gated). Captured before the membrane is built,
+ // while the ancestors are still reachable.
+ const realm = targetWindow as unknown as Window;
+
+ // A same-origin child frame's realm is reachable ONLY through
+ // `iframe.contentWindow` / `contentDocument.defaultView` (Near-Membrane isolates
+ // `window.frames`). Gate exactly those getters on the realm-creating element
+ // prototypes, so such a frame — e.g. the transient clone iframe html2canvas
+ // creates during a chart export — collapses to THIS gated realm. Deliberately
+ // narrow: matching the whole `Window` type instead fires on every window the SDK
+ // resolves at load and blows the stack.
+ const getterOf = (proto: object, key: string) =>
+ Object.getOwnPropertyDescriptor(proto, key)?.get;
+ const realmCreatingProtos = [
+ HTMLIFrameElement,
+ HTMLFrameElement,
+ HTMLObjectElement,
+ HTMLEmbedElement,
+ ].map((ctor) => ctor.prototype);
+ const contentWindowGetters = new Set<unknown>(
+ realmCreatingProtos
+ .map((p) => getterOf(p, "contentWindow"))
+ .filter(Boolean),
+ );
+ const contentDocumentGetters = new Set<unknown>(
+ realmCreatingProtos
+ .map((p) => getterOf(p, "contentDocument"))
+ .filter(Boolean),
);
+ const getGatedRealm = () => realm;
+ const getNull = () => null;
+
+ const ancestors = new Set<unknown>();
+
+ // Walk up until a window is its own parent (the top) or a cross-origin
+ // ancestor makes `.parent` throw — every real chain terminates one of those ways.
+ let ancestor: Window | null = realm;
+ while (ancestor) {
+ let up: Window | null;
+
+ try {
+ up = ancestor.parent;
+ } catch {
+ break;
+ }
+
+ if (!up || up === ancestor) {
+ break;
+ }
+
+ ancestors.add(up);
+ ancestor = up;
+ }
+
+ try {
+ if (realm.top) {
+ ancestors.add(realm.top);
+ }
+ } catch {
+ // top unreachable — nothing to redirect
+ }
+
+ try {
+ if (realm.frameElement) {
+ ancestors.add(realm.frameElement);
+ }
+ } catch {
+ // frameElement unreachable — nothing to redirect
+ }
+
+ try {
+ if (realm.opener) {
+ ancestors.add(realm.opener);
+ }
+ } catch {
+ // opener unreachable — nothing to redirect
+ }
return function distortionCallback(value: object): object {
const createElementDistortion = makeCreateElementDistortion(value, shared);
@@ -71,9 +142,21 @@ export function makeDistortionCallback(
if (sandboxFetch && value === targetWindow.fetch) {
return sandboxFetch;
}
- if (sandboxXhr && value === targetWindow.XMLHttpRequest) {
- return sandboxXhr;
+
+ if (ancestors.has(value)) {
+ return realm;
+ }
+
+ // A child frame's `contentWindow` resolves to the gated realm; its
+ // `contentDocument` to null — so neither reaches a live child realm.
+ if (contentWindowGetters.has(value)) {
+ return getGatedRealm;
}
+
+ if (contentDocumentGetters.has(value)) {
+ return getNull;
+ }
+
return shared(value);
};
}
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.ts
index e18d842575c..6902165ecc6 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
@@ -64,20 +64,16 @@ describe("makeDistortionCallback", () => {
expect(realFetch).toHaveBeenCalledTimes(1);
});
- it("routes window.XMLHttpRequest to the allowlisted subclass when allowed_hosts is set", () => {
+ it("never allowlists window.XMLHttpRequest, even when allowed_hosts is set", () => {
const win = fakeWindow();
const callback = makeDistortionCallback("sales", win, [
"https://api.example.com",
]);
- // Same signature erasure as above: the membrane hands the constructor back
- // as a bare `object`.
- const Distorted = callback(win.XMLHttpRequest) as typeof XMLHttpRequest;
-
- expect(Distorted).not.toBe(win.XMLHttpRequest);
- const xhr = new Distorted();
- expect(() => xhr.open("GET", "https://evil.example.org/")).toThrow(
- /blocked XMLHttpRequest/,
- );
+ // XHR can't opt out of following a redirect back to the instance, so it is
+ // never allowlisted: it passes through to the shared hard block (in production
+ // `blockHostRealmXhr` has already replaced it with a throwing stub before the
+ // membrane is built).
+ expect(callback(win.XMLHttpRequest)).toBe(win.XMLHttpRequest);
});
it("does not wrap fetch/XHR when allowed_hosts is empty (shared hard block stands)", () => {
@@ -89,6 +85,43 @@ describe("makeDistortionCallback", () => {
expect(callback(win.XMLHttpRequest)).toBe(win.XMLHttpRequest);
});
+ // The sandboxed iframe is same-origin with the main app, and Near-Membrane
+ // remaps the guest's `window.parent` to the target's real parent — an ungated
+ // realm whose fetch carries the session. The callback must redirect every
+ // ancestor (and the frame element) back to the gated target window.
+ it("redirects ancestor windows and the frame element to the gated target", () => {
+ const grandparent = { name: "top" };
+ const parent = { name: "main-app", parent: grandparent };
+ const frameElement = { tagName: "IFRAME" };
+ // The real realm is a `Window`; the distortion only reads `parent`/`top`/
+ // `frameElement` off it, which this stand-in supplies. Cast through the
+ // narrow `SandboxRealm` the callback is typed against.
+ const win = {
+ ...fakeWindow(),
+ parent,
+ top: grandparent,
+ frameElement,
+ } as unknown as SandboxRealm;
+
+ const callback = makeDistortionCallback("sales", win, []);
+
+ // Every ancestor reachable from the realm resolves back to the gated realm.
+ expect(callback(parent)).toBe(win);
+ expect(callback(grandparent)).toBe(win);
+ expect(callback(frameElement)).toBe(win);
+ });
+
+ it("leaves the target window itself untouched (parent chain stops at self)", () => {
+ // A top-level realm: parent === self, so the walk finds no foreign ancestor.
+ // Assigning `parent` needs the extra field the narrow type doesn't declare.
+ const win = fakeWindow() as SandboxRealm & { parent: unknown };
+ win.parent = win;
+ const callback = makeDistortionCallback("sales", win, []);
+
+ const plain = {};
+ expect(callback(plain)).toBe(plain);
+ });
+
it("delegates non-network values to the shared callback", () => {
const win = fakeWindow();
const callback = makeDistortionCallback("sales", win, [
@@ -146,29 +179,5 @@ describe("makeDistortionCallback", () => {
reason: "evil.example.org (not in allowed_hosts)",
});
});
-
- it("reports a blocked XMLHttpRequest", () => {
- const onBlocked = jest.fn();
- const win = fakeWindow();
- const callback = makeDistortionCallback(
- "sales",
- win,
- ["https://api.example.com"],
- onBlocked,
- );
- // Same signature erasure as above.
- const Distorted = callback(win.XMLHttpRequest) as typeof XMLHttpRequest;
-
- expect(() =>
- new Distorted().open("GET", "https://evil.example.org/"),
- ).toThrow();
-
- expect(onBlocked).toHaveBeenCalledWith({
- type: "network",
- api: "xhr",
- url: "https://evil.example.org/",
- reason: "evil.example.org (not in allowed_hosts)",
- });
- });
});
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.ts
new file mode 100644
index 00000000000..b48b0fd8ca7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.ts
@@ -0,0 +1,172 @@
+import DOMPurify from "dompurify";
+
+import { getXmlElementLocalName } from "metabase/utils/scripts-sandbox/distortions-dom-mutate";
+
+/**
+ * Blocks realm-creating elements for every creator in the data-app document: guest
+ * code can hand host React a plain element description (`react.element` is a shared
+ * symbol) that skips the gated guest `createElement`. So both host channels are
+ * guarded — `createElement`/`createElementNS` (blocked) and `innerHTML`/`outerHTML`/
+ * `insertAdjacentHTML` (realm tags stripped). Install AFTER Near-Membrane's realm iframe exists.
+ *
+ * Used as a module singleton (one realm per data-app bundle); `install` is
+ * idempotent per document.
+ */
+class HostRealmElementGuard {
+ // Elements that open a new same-origin browsing context — a realm the guest could
+ // reach for an unwrapped `fetch`. `<script>` is excluded on purpose: the SDK and
+ // bundler create script elements host-side, and script execution is already gated
+ // by the data-app CSP `script-src`. These are the realm-creating tags that CSP
+ // `frame-src` can't cover (srcless `about:blank`).
+ private static readonly REALM_CREATING_TAGS = new Set([
+ "iframe",
+ "frame",
+ "frameset",
+ "object",
+ "embed",
+ ]);
+
+ private static readonly HOST_PURIFY_CONFIG = {
+ FORBID_TAGS: Array.from(HostRealmElementGuard.REALM_CREATING_TAGS),
+ };
+
+ // `<iframe>`s the in-flight chart export may still create. A grant allows exactly
+ // one (html2canvas's transient clone), consumed on first use in `isBlocked` — so a
+ // guest render can't slip one through while the export's promise is still pending.
+ // Not endowed, so the guest can't raise it.
+ private iframeGrantAllowance = 0;
+
+ // DOMPurify parses by assigning `innerHTML` on a detached node, re-entering the
+ // setters we patch; pass the raw value through during that internal parse.
+ private isSanitizing = false;
+
+ private readonly installed = new WeakSet<Document>();
+
+ withIframeGrant = async <T>(callback: () => Promise<T>): Promise<T> => {
+ this.iframeGrantAllowance += 1;
+ try {
+ return await callback();
+ } finally {
+ // Reclaim the allowance if the export threw before creating its iframe.
+ this.iframeGrantAllowance = Math.max(0, this.iframeGrantAllowance - 1);
+ }
+ };
+
+ install(targetWindow: Window): void {
+ const { document } = targetWindow;
+
+ if (this.installed.has(document)) {
+ return;
+ }
+
+ this.installed.add(document);
+
+ this.guardCreateElement(document);
+ // `Element`/`ShadowRoot` are this realm's own globals — the module loads in the
+ // same realm as `targetWindow` (the data-app document).
+ this.guardMarkupInsertion();
+ }
+
+ private isBlocked(tag: string): boolean {
+ const name = getXmlElementLocalName(tag).toLowerCase();
+
+ if (name === "iframe" && this.iframeGrantAllowance > 0) {
+ // Consume the one-shot grant: only html2canvas's clone gets through, not a
+ // guest render racing the still-pending export.
+ this.iframeGrantAllowance -= 1;
+ return false;
+ }
+
+ return HostRealmElementGuard.REALM_CREATING_TAGS.has(name);
+ }
+
+ private sanitizeHostHtml(html: unknown): string {
+ const htmlString = String(html);
+ const isMarkup = htmlString.includes("<");
+
+ if (this.isSanitizing || !isMarkup) {
+ return htmlString;
+ }
+
+ this.isSanitizing = true;
+ try {
+ return DOMPurify.sanitize(
+ htmlString,
+ HostRealmElementGuard.HOST_PURIFY_CONFIG,
+ );
+ } finally {
+ this.isSanitizing = false;
+ }
+ }
+
+ private guardCreateElement(document: Document): void {
+ const createElement = document.createElement.bind(document);
+ const createElementNS = document.createElementNS.bind(document);
+
+ const rejectIfBlocked = (tag: string, api: string) => {
+ if (this.isBlocked(tag)) {
+ throw new Error(`[data-app] blocked host ${api}: ${tag}`);
+ }
+ };
+
+ const guardedCreate = (tag: string, options?: ElementCreationOptions) => {
+ rejectIfBlocked(tag, "createElement");
+ return createElement(tag, options);
+ };
+
+ const guardedCreateNS = (
+ namespaceURI: string | null,
+ qualifiedName: string,
+ options?: ElementCreationOptions,
+ ) => {
+ rejectIfBlocked(qualifiedName, "createElementNS");
+ return createElementNS(namespaceURI, qualifiedName, options);
+ };
+
+ // The natives carry tag-name overloads the guards don't reproduce; assert back to
+ // the native property type so the patched document still satisfies `Document`.
+ document.createElement = guardedCreate as Document["createElement"];
+ // Same overload-preserving assertion as `createElement`.
+ document.createElementNS = guardedCreateNS as Document["createElementNS"];
+ }
+
+ private guardMarkupInsertion(): void {
+ // Bound to the instance because the patched setter's `this` is the element.
+ const sanitize = (html: unknown) => this.sanitizeHostHtml(html);
+
+ const htmlSetterOwners = [
+ { proto: Element.prototype, keys: ["innerHTML", "outerHTML"] },
+ { proto: ShadowRoot.prototype, keys: ["innerHTML"] },
+ ];
+
+ for (const { proto, keys } of htmlSetterOwners) {
+ for (const key of keys) {
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
+ const originalSet = descriptor?.set;
+
+ if (!descriptor || !originalSet) {
+ continue;
+ }
+
+ Object.defineProperty(proto, key, {
+ ...descriptor,
+ set(this: Element | ShadowRoot, value: unknown) {
+ originalSet.call(this, sanitize(value));
+ },
+ });
+ }
+ }
+
+ const { insertAdjacentHTML } = Element.prototype;
+
+ Element.prototype.insertAdjacentHTML = function (
+ this: Element,
+ position: InsertPosition,
+ html: string,
+ ) {
+ return insertAdjacentHTML.call(this, position, sanitize(html));
+ };
+ }
+}
+
+export const hostRealmElementGuard = new HostRealmElementGuard();
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.unit.spec.ts
new file mode 100644
index 00000000000..ffa390e71cc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/host-element-guard.unit.spec.ts
@@ -0,0 +1,168 @@
+import { hostRealmElementGuard } from "./host-element-guard";
+
+// The guard patches the realm's shared prototypes/document, so install it once
+// against jsdom's globals and exercise the two host-side materialization paths.
+describe("HostRealmElementGuard", () => {
+ beforeAll(() => {
+ hostRealmElementGuard.install(window);
+ });
+
+ describe("createElement", () => {
+ it.each(["iframe", "frame", "object", "embed"])(
+ "blocks a realm-creating <%s>",
+ (tag) => {
+ expect(() => document.createElement(tag)).toThrow(
+ /blocked host createElement/,
+ );
+ },
+ );
+
+ it.each(["div", "span", "canvas", "table", "input", "a", "form"])(
+ "allows the inert <%s> the SDK may need",
+ (tag) => {
+ expect(() => document.createElement(tag)).not.toThrow();
+ },
+ );
+
+ // Not a realm; script EXECUTION is gated by CSP `script-src`, and the SDK +
+ // webpack/rspack create script elements host-side for bundle/chunk loading.
+ it("allows <script>", () => {
+ expect(() => document.createElement("script")).not.toThrow();
+ });
+
+ it("is case-insensitive", () => {
+ expect(() => document.createElement("IFRAME")).toThrow(
+ /blocked host createElement/,
+ );
+ });
+
+ it("blocks a namespaced realm tag via createElementNS", () => {
+ expect(() =>
+ document.createElementNS("http://www.w3.org/1999/xhtml", "iframe"),
+ ).toThrow(/blocked host createElementNS/);
+ });
+
+ it("allows an SVG element via createElementNS", () => {
+ expect(() =>
+ document.createElementNS("http://www.w3.org/2000/svg", "svg"),
+ ).not.toThrow();
+ });
+ });
+
+ describe("innerHTML", () => {
+ it("strips an iframe smuggled through innerHTML", () => {
+ const host = document.createElement("div");
+ host.innerHTML = '<iframe src="x"></iframe><b>ok</b>';
+
+ expect(host.querySelector("iframe")).toBeNull();
+ expect(host.querySelector("b")?.textContent).toBe("ok");
+ });
+
+ // Any markup containing a tag is routed through DOMPurify rather than
+ // pattern-matched, so a <script> is stripped along with anything else DOMPurify
+ // removes. (Inert scripts don't execute via innerHTML anyway.)
+ it("sanitizes any markup containing a tag", () => {
+ const host = document.createElement("div");
+ host.innerHTML = "<script>window.__x = 1;</script><span>hi</span>";
+
+ expect(host.querySelector("script")).toBeNull();
+ expect(host.querySelector("span")?.textContent).toBe("hi");
+ });
+
+ it("keeps ordinary markup intact", () => {
+ const host = document.createElement("div");
+ host.innerHTML = '<p class="c">text <em>emphasis</em></p>';
+
+ expect(host.querySelector("p.c em")?.textContent).toBe("emphasis");
+ });
+
+ // Inline handlers execute in the host realm; without this the guard's realm-
+ // tag fast-path would let `<img onerror>` through (CSP is the only other line
+ // of defense, and it can be stripped/misconfigured).
+ it("strips an inline event handler from innerHTML", () => {
+ const host = document.createElement("div");
+ host.innerHTML =
+ '<img src="x" onerror="fetch(\'/api/user\')" /><b>ok</b>';
+
+ expect(host.querySelector("img")?.hasAttribute("onerror")).toBe(false);
+ expect(host.querySelector("b")?.textContent).toBe("ok");
+ });
+
+ // `/` is a valid attribute-name separator, so `<img/onerror>` reaches the
+ // handler with no whitespace in front of `on` — the gate must catch it too.
+ it("strips a slash-separated inline handler from innerHTML", () => {
+ const host = document.createElement("div");
+ host.innerHTML = "<img/onerror=\"fetch('/api/user')\" src=x><b>ok</b>";
+
+ expect(host.querySelector("img")?.hasAttribute("onerror")).toBe(false);
+ expect(host.querySelector("b")?.textContent).toBe("ok");
+ });
+
+ // A handler placed directly after a quoted attribute value has no separator
+ // before `on`, but the browser still parses it as a live handler.
+ it("strips a quote-adjacent inline handler from innerHTML", () => {
+ const host = document.createElement("div");
+ host.innerHTML = '<img src="x"onerror="fetch(\'/api/user\')"><b>ok</b>';
+
+ expect(host.querySelector("img")?.hasAttribute("onerror")).toBe(false);
+ expect(host.querySelector("b")?.textContent).toBe("ok");
+ });
+
+ it("strips a javascript: URL from innerHTML", () => {
+ const host = document.createElement("div");
+ host.innerHTML = '<a href="javascript:fetch(1)">x</a>';
+
+ expect(host.innerHTML).not.toContain("javascript:");
+ expect(host.querySelector("a")?.textContent).toBe("x");
+ });
+
+ // The `javascript:` scheme can be entity-encoded (`java&#115;cript:`) and still
+ // decode to a live URL once parsed — a substring match would miss it.
+ it("strips an entity-encoded javascript: URL from innerHTML", () => {
+ const host = document.createElement("div");
+ host.innerHTML = '<a href="java&#115;cript:fetch(1)">x</a>';
+
+ expect(host.querySelector("a")?.hasAttribute("href")).toBe(false);
+ expect(host.querySelector("a")?.textContent).toBe("x");
+ });
+
+ it("strips an iframe smuggled through insertAdjacentHTML", () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ host.insertAdjacentHTML("beforeend", "<iframe></iframe><i>x</i>");
+
+ expect(host.querySelector("iframe")).toBeNull();
+ expect(host.querySelector("i")?.textContent).toBe("x");
+ host.remove();
+ });
+ });
+
+ describe("withIframeGrant", () => {
+ const createIframe = () => document.createElement("iframe");
+
+ it("allows exactly one iframe per grant (html2canvas's clone), blocking a second", async () => {
+ await hostRealmElementGuard.withIframeGrant(async () => {
+ // html2canvas's clone iframe: allowed, consuming the one-shot grant.
+ expect(createIframe).not.toThrow();
+ // A guest render racing the still-pending export must NOT get one.
+ expect(createIframe).toThrow(/blocked host createElement/);
+ });
+ });
+
+ it("blocks iframes again once the grant resolves", async () => {
+ await hostRealmElementGuard.withIframeGrant(async () => {});
+ expect(createIframe).toThrow(/blocked host createElement/);
+ });
+
+ it("reclaims the allowance if the export throws before creating its iframe", async () => {
+ await expect(
+ hostRealmElementGuard.withIframeGrant(async () => {
+ throw new Error("export failed");
+ }),
+ ).rejects.toThrow("export failed");
+
+ // The unused allowance must not leak into a later render.
+ expect(createIframe).toThrow(/blocked host createElement/);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts
index cf97b031fe0..a8d59d68862 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts
@@ -1,7 +1,11 @@
import createVirtualEnvironment from "@locker/near-membrane-dom";
+import { setChartExportIframeGrant } from "metabase/visualizations/lib/chart-export-iframe-grant";
+
+import { blockHostRealmXhr } from "./allowed-hosts";
import { makeDistortionCallback } from "./distortions";
import { DATA_APP_GLOBAL_NAMES } from "./globals";
+import { hostRealmElementGuard } from "./host-element-guard";
import type { DataAppFactory, SandboxBlockedListener } from "./types";
/**
@@ -42,8 +46,12 @@ export interface CreateDataAppSandboxOptions {
label?: string;
/** Realm the membrane binds to. Defaults to the current `window`. */
targetWindow?: Window & typeof globalThis;
- /** Origins the bundle may fetch/XHR; empty keeps the default hard block. */
+ /** Origins the bundle may fetch; empty keeps the default hard block. */
allowedHosts?: string[];
+ /**
+ * Same-origin URL serving the document Near-Membrane loads as its realm iframe.
+ */
+ realmHostUrl?: string;
/** The realm's React/SDK exposed to the bundle. See [[DataAppSandboxEndowments]]. */
endowments: DataAppSandboxEndowments;
/**
@@ -61,16 +69,26 @@ function isDataAppFactory(value: unknown): value is DataAppFactory {
return typeof value === "function";
}
-export function createDataAppSandbox({
+export async function createDataAppSandbox({
label = "",
targetWindow = window,
allowedHosts = [],
+ realmHostUrl,
endowments,
onBlocked,
}: CreateDataAppSandboxOptions) {
let captured: unknown;
- const env = createVirtualEnvironment(targetWindow, {
+ // Before the membrane, so the guest is handed the blocked stub rather than
+ // the native constructor. See [[blockHostRealmXhr]] — XHR is removed from the
+ // data-app document entirely, host realm included.
+ blockHostRealmXhr(targetWindow);
+
+ const env = await createVirtualEnvironment(targetWindow, {
+ ...(realmHostUrl ? { iframeSrc: realmHostUrl } : {}),
+ // Default `true` leaves the realm iframe attached as a reachable same-origin
+ // ancestor window; detach it so the guest can't reach one.
+ keepAlive: false,
distortionCallback: makeDistortionCallback(
label,
targetWindow,
@@ -107,6 +125,41 @@ export function createDataAppSandbox({
}),
});
+ // Gate `Error.prepareStackTrace` in the guest realm before any bundle runs: a
+ // function formatter receives V8 `CallSite[]` that can hand back non-membrane
+ // host references, so keep the guest from installing one.
+ // A non-configurable accessor drops function assignments but allows `undefined`
+ // (React dev sets it so, then restores). Must be an evaluate prelude, not a
+ // distortion — it's a red-realm property the guest owns. (Host storage is handled
+ // separately, in the shared distortion.)
+ // `prepareStackTrace` is a V8-only hook, so this vector (and this gate) only
+ // exists on Chromium — Safari/Firefox never expose the CallSite formatter.
+ env.evaluate(`(() => {
+ try {
+ let stored;
+ Object.defineProperty(Error, "prepareStackTrace", {
+ configurable: false,
+ get() {
+ return stored;
+ },
+ set(value) {
+ if (typeof value !== "function") {
+ stored = value;
+ }
+ },
+ });
+ } catch (e) {}
+ })();`);
+
+ // After the membrane built its own realm iframe — from here on, nothing in this
+ // document may create another realm, whichever React renders it.
+ hostRealmElementGuard.install(targetWindow);
+
+ // Let the chart PNG export create html2canvas's transient clone <iframe> despite
+ // the guard above — safe because the distortion collapses that iframe's realm to
+ // the gated realm, so the guest can't reach it.
+ setChartExportIframeGrant(hostRealmElementGuard.withIframeGrant);
+
return {
evaluate(code: string): DataAppFactory {
try {
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.ts
index e9015f4a14e..35e581a9841 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.ts
@@ -26,23 +26,40 @@ function baseEndowments(overrides: Partial<Endowments> = {}): Endowments {
type SetupOpts = {
overrides?: Partial<Endowments>;
runBundle?: () => void;
+ realmHostUrl?: string;
};
-function setup({ overrides, runBundle = () => {} }: SetupOpts = {}) {
+async function setup({
+ overrides,
+ runBundle = () => {},
+ realmHostUrl,
+}: SetupOpts = {}) {
let endowments: EnvEndowments | undefined;
+ let options: Parameters<typeof createVirtualEnvironment>[1] | undefined;
+
+ // The sandbox evaluates a realm-hardening prelude (pins Error.prepareStackTrace)
+ // BEFORE the bundle; only the bundle should drive `runBundle`.
+ const evaluate = jest.fn((code?: string) => {
+ if (typeof code === "string" && code.includes("prepareStackTrace")) {
+ return;
+ }
+ return runBundle();
+ });
mockedCreateEnv.mockReset();
- mockedCreateEnv.mockImplementation((_targetWindow, options) => {
- endowments = options?.endowments;
+ mockedCreateEnv.mockImplementation((_targetWindow, envOptions) => {
+ options = envOptions;
+ endowments = envOptions?.endowments;
// `VirtualEnvironment` is a class with a large internal surface (link,
// remap, lazyRemapProperties, …); the sandbox only ever calls `evaluate`.
return {
- evaluate: () => runBundle(),
+ evaluate,
} as unknown as ReturnType<typeof createVirtualEnvironment>;
});
- const sandbox = createDataAppSandbox({
+ const sandbox = await createDataAppSandbox({
endowments: baseEndowments(overrides),
+ realmHostUrl,
});
if (!endowments) {
@@ -56,14 +73,39 @@ function setup({ overrides, runBundle = () => {} }: SetupOpts = {}) {
]),
);
- return { sandbox, endowed };
+ return { sandbox, endowed, options, evaluate };
}
describe("createDataAppSandbox", () => {
+ describe("realm document", () => {
+ // The realm is served from its own document so `'unsafe-eval'` lives in ITS
+ // CSP, not the data-app document's — see `realmHostUrl`.
+ it("points the membrane's realm iframe at the realm host when given one", async () => {
+ const { options } = await setup({
+ realmHostUrl: "/api/apps/sandbox-host",
+ });
+
+ // Untyped: `iframeSrc` comes from Metabase's near-membrane patch, so it is
+ // absent from the upstream option types.
+ expect((options as { iframeSrc?: string })?.iframeSrc).toBe(
+ "/api/apps/sandbox-host",
+ );
+ });
+
+ // Without one the realm falls back to `about:blank`, which inherits the host
+ // document's CSP. That is the dev-server case, where the instance-served
+ // realm document would be cross-origin and unreachable to the membrane.
+ it("omits iframeSrc entirely when no realm host is given", async () => {
+ const { options } = await setup();
+
+ expect(options).not.toHaveProperty("iframeSrc");
+ });
+ });
+
describe("endowment injection", () => {
- it("endows the React externals under their global names and the SDK/data-app as spread copies", () => {
+ it("endows the React externals under their global names and the SDK/data-app as spread copies", async () => {
const original = baseEndowments();
- const { endowed } = setup({ overrides: original });
+ const { endowed } = await setup({ overrides: original });
expect(endowed).toMatchObject({
[DATA_APP_GLOBAL_NAMES.react]: original.React,
@@ -76,15 +118,15 @@ describe("createDataAppSandbox", () => {
});
});
- it("omits the dev jsx-runtime endowment unless one is provided", () => {
- const withoutDev = setup();
+ it("omits the dev jsx-runtime endowment unless one is provided", async () => {
+ const withoutDev = await setup();
expect(
DATA_APP_GLOBAL_NAMES.reactJsxDevRuntime in withoutDev.endowed,
).toBe(false);
const reactJsxDevRuntime = { marker: "DEV" };
- const withDev = setup({ overrides: { reactJsxDevRuntime } });
+ const withDev = await setup({ overrides: { reactJsxDevRuntime } });
expect(withDev.endowed[DATA_APP_GLOBAL_NAMES.reactJsxDevRuntime]).toBe(
reactJsxDevRuntime,
@@ -92,17 +134,51 @@ describe("createDataAppSandbox", () => {
});
});
+ describe("realm hardening", () => {
+ it("gates Error.prepareStackTrace before the bundle runs: drops functions, allows undefined", async () => {
+ const { evaluate } = await setup();
+
+ // The prelude is the first thing evaluated — before any bundle code.
+ expect(evaluate).toHaveBeenCalledTimes(1);
+ const [preludeCode] = evaluate.mock.calls[0];
+ if (typeof preludeCode !== "string") {
+ throw new Error("expected a prelude string to be evaluated");
+ }
+
+ // Run the prelude against a throwaway `Error` stand-in and assert the
+ // behaviour it installs, not just its source text. The prelude references a
+ // global `Error`, so shadow it with the stand-in.
+ const fakeError: { prepareStackTrace?: unknown } = {};
+ new Function("Error", preludeCode)(fakeError);
+
+ // A function formatter (the attack) is silently dropped.
+ fakeError.prepareStackTrace = () => "host-reference";
+ expect(fakeError.prepareStackTrace).toBeUndefined();
+
+ // `undefined` still passes through (React dev sets it, then restores).
+ fakeError.prepareStackTrace = undefined;
+ expect(fakeError.prepareStackTrace).toBeUndefined();
+
+ // The accessor is non-configurable, so the guest can't redefine it away.
+ expect(() =>
+ Object.defineProperty(fakeError, "prepareStackTrace", {
+ value: () => "host-reference",
+ }),
+ ).toThrow();
+ });
+ });
+
describe("evaluate", () => {
- it("throws when the bundle never assigns a factory", () => {
- const { sandbox } = setup();
+ it("throws when the bundle never assigns a factory", async () => {
+ const { sandbox } = await setup();
expect(() => sandbox.evaluate("code")).toThrow(
/did not assign a function/,
);
});
- it("re-throws an error thrown during evaluation as a host-realm Error", () => {
- const { sandbox } = setup({
+ it("re-throws an error thrown during evaluation as a host-realm Error", async () => {
+ const { sandbox } = await setup({
runBundle: () => {
throw new Error("bundle blew up");
},
@@ -111,8 +187,8 @@ describe("createDataAppSandbox", () => {
expect(() => sandbox.evaluate("code")).toThrow("bundle blew up");
});
- it("falls back to a generic message when the thrown value is unreadable", () => {
- const { sandbox } = setup({
+ it("falls back to a generic message when the thrown value is unreadable", async () => {
+ const { sandbox } = await setup({
runBundle: () => {
// A membrane-opaque throw whose `message` can't be read from the host.
throw new Proxy(
diff --git a/frontend/src/metabase/urls/data-apps.ts b/frontend/src/metabase/urls/data-apps.ts
index 6d496089818..db9cedb5ef0 100644
--- a/frontend/src/metabase/urls/data-apps.ts
+++ b/frontend/src/metabase/urls/data-apps.ts
@@ -1,9 +1,7 @@
/**
* Canonical data-app URLs. `DATA_APP_URL_SEGMENT` is the single source of
* truth for the `apps` path segment; the page, admin, and iframe-embed URLs
- * all derive from it, so renaming the route is a one-line change here. (REST
- * API paths deliberately live as bare strings in the API layer so they stay
- * greppable — see `metabase-enterprise/api/data-app.ts`.)
+ * all derive from it, so renaming the route is a one-line change here.
*/
export const DATA_APP_URL_SEGMENT = "apps";
@@ -17,6 +15,13 @@ export const DATA_APP_ROOT_URL = `/${DATA_APP_URL_SEGMENT}`;
*/
export const DATA_APP_EMBED_PREFIX = `/embed/${DATA_APP_URL_SEGMENT}`;
+/**
+ * Same-origin document Near-Membrane loads as the sandbox realm iframe. It carries
+ * its own CSP granting `'unsafe-eval'`, which is what lets the data-app document
+ * itself drop that grant.
+ */
+export const DATA_APP_REALM_HOST_URL = "/api/apps/sandbox-host";
+
export function dataApp(name: string) {
return `${DATA_APP_ROOT_URL}/${encodeURIComponent(name)}`;
}
diff --git a/frontend/src/metabase/utils/scripts-sandbox/distortions-blocked-apis.ts b/frontend/src/metabase/utils/scripts-sandbox/distortions-blocked-apis.ts
index 091a092de82..f54f5010ec2 100644
--- a/frontend/src/metabase/utils/scripts-sandbox/distortions-blocked-apis.ts
+++ b/frontend/src/metabase/utils/scripts-sandbox/distortions-blocked-apis.ts
@@ -116,7 +116,11 @@ block(getter(Document.prototype, "URL"), "Document.get URL");
block(getter(Document.prototype, "documentURI"), "Document.get documentURI");
block(getter(Node.prototype, "baseURI"), "Node.get baseURI");
-// Storage exfiltration
+// Storage access. These getters aren't enough on their own — Near-Membrane reads
+// the global window's OWN accessors directly, bypassing the distortion, so gating
+// the getters doesn't stop a Window from yielding a live Storage. The instance is
+// swapped for a throwing decoy instead — see `HOST_STORAGE_CTORS` in
+// `distortions.ts`.
block(getter(Window.prototype, "localStorage"), "Window.get localStorage");
block(getter(Window.prototype, "sessionStorage"), "Window.get sessionStorage");
block(getter(Window.prototype, "indexedDB"), "Window.get indexedDB");
diff --git a/frontend/src/metabase/utils/scripts-sandbox/distortions-dom-mutate.ts b/frontend/src/metabase/utils/scripts-sandbox/distortions-dom-mutate.ts
index 5e87f64278c..76f715564e8 100644
--- a/frontend/src/metabase/utils/scripts-sandbox/distortions-dom-mutate.ts
+++ b/frontend/src/metabase/utils/scripts-sandbox/distortions-dom-mutate.ts
@@ -109,6 +109,14 @@ export function createElementDistortion(errorPrefix: string) {
};
}
+/**
+ * Strip an XML namespace prefix from a qualified name (`svg:rect` -> `rect`).
+ * `indexOf` is -1 when there's no prefix, so `slice` returns the whole name.
+ */
+export function getXmlElementLocalName(qualifiedName: string): string {
+ return qualifiedName.slice(qualifiedName.indexOf(":") + 1);
+}
+
export function createElementNSDistortion(errorPrefix: string) {
return function createElementNS(
this: Document,
@@ -116,10 +124,7 @@ export function createElementNSDistortion(errorPrefix: string) {
qualifiedName: string,
options?: ElementCreationOptions,
) {
- const localName = qualifiedName.includes(":")
- ? qualifiedName.slice(qualifiedName.indexOf(":") + 1)
- : qualifiedName;
- if (BLOCKED_TAGS.has(localName.toLowerCase())) {
+ if (BLOCKED_TAGS.has(getXmlElementLocalName(qualifiedName).toLowerCase())) {
throw new Error(
`[${errorPrefix}] blocked createElementNS: ${qualifiedName}`,
);
diff --git a/frontend/src/metabase/utils/scripts-sandbox/distortions.ts b/frontend/src/metabase/utils/scripts-sandbox/distortions.ts
index 32c2f9217bc..f5ca4457688 100644
--- a/frontend/src/metabase/utils/scripts-sandbox/distortions.ts
+++ b/frontend/src/metabase/utils/scripts-sandbox/distortions.ts
@@ -28,6 +28,36 @@ import {
addEventListenerDistortion,
} from "./distortions-event";
+// Host storage classes whose instances must never reach the guest. Near-Membrane
+// only rewrites function values, so a `Storage`/`IDBFactory`/`CacheStorage`
+// object would otherwise pass through untouched and stay readable by the guest —
+// named access (`store["k"]`) and enumeration aren't reachable by gating
+// prototype methods. We swap the instance itself for a throwing decoy instead.
+const HOST_STORAGE_CTORS = [
+ typeof Storage !== "undefined" && Storage,
+ typeof IDBFactory !== "undefined" && IDBFactory,
+ typeof CacheStorage !== "undefined" && CacheStorage,
+].filter(Boolean) as Array<new (...args: never[]) => object>;
+
+const isHostStorageInstance = (value: unknown): boolean =>
+ HOST_STORAGE_CTORS.some((ctor) => value instanceof ctor);
+
+// A stand-in for a host storage instance: every property read, membership
+// test, or enumeration throws, so the guest can neither read values nor call
+// `getItem`/`indexedDB.open`/`caches.match`/… on it.
+const makeBlockedStorageDecoy = (errorPrefix: string): object => {
+ const blocked = () => {
+ throw new Error(`[${errorPrefix}] blocked API call: host storage`);
+ };
+
+ return new Proxy(Object.create(null), {
+ get: blocked,
+ has: blocked,
+ ownKeys: blocked,
+ getOwnPropertyDescriptor: blocked,
+ });
+};
+
/**
* Build the common subset of a Near Membrane `distortionCallback` shared by
* every Metabase sandbox.
@@ -42,7 +72,9 @@ import {
* - blocked inline-event-handler attributes (`onclick="…"`) and
* `javascript:` URLs at the setAttribute boundary;
* - blocked `addEventListener` on `document`/`window` for typing /
- * clipboard / storage event types.
+ * clipboard / storage event types;
+ * - host `Storage`/`IDBFactory`/`CacheStorage` instances swapped for a
+ * throwing decoy so the guest can't read or enumerate host storage.
*
* It does NOT handle DOM-node scoping (decoy nodes outside a script's
* subtree, scope-aware `document.activeElement`). Scoping is consumer-
@@ -149,6 +181,10 @@ export function makeSandboxDistortionCallback(
return function distortionCallback(value: object): object {
if (typeof value !== "function") {
+ if (isHostStorageInstance(value)) {
+ return makeBlockedStorageDecoy(errorPrefix);
+ }
+
return value;
}
diff --git a/frontend/src/metabase/utils/scripts-sandbox/index.ts b/frontend/src/metabase/utils/scripts-sandbox/index.ts
index f92f6c952ef..f9b8ba0e39d 100644
--- a/frontend/src/metabase/utils/scripts-sandbox/index.ts
+++ b/frontend/src/metabase/utils/scripts-sandbox/index.ts
@@ -1,3 +1,3 @@
export { BLOCKED_NATIVE_REFS } from "./distortions-blocked-apis";
-export { BLOCKED_TAGS } from "./distortions-dom-mutate";
+export { BLOCKED_TAGS, getXmlElementLocalName } from "./distortions-dom-mutate";
export { makeSandboxDistortionCallback } from "./distortions";
diff --git a/frontend/src/metabase/visualizations/lib/chart-export-iframe-grant.ts b/frontend/src/metabase/visualizations/lib/chart-export-iframe-grant.ts
new file mode 100644
index 00000000000..57488d43f74
--- /dev/null
+++ b/frontend/src/metabase/visualizations/lib/chart-export-iframe-grant.ts
@@ -0,0 +1,17 @@
+type ExportRunner = <T>(fn: () => Promise<T>) => Promise<T>;
+
+// html2canvas rasterizes by cloning the DOM into a transient same-origin <iframe>.
+// The data-app sandbox guards <iframe> creation, so it installs a grant that lets
+// the chart export create it (safely — the sandbox collapses that iframe's realm to
+// its own gated realm). Everywhere else this is a pass-through.
+//
+// Kept in its own dependency-free module so the sandbox can wire the grant without
+// importing `save-chart-image` — which would pull the chart-export/branding chain
+// (including a `.svg?component` import) into the published SDK-package bundle.
+let runner: ExportRunner = (fn) => fn();
+
+export const setChartExportIframeGrant = (nextRunner: ExportRunner) => {
+ runner = nextRunner;
+};
+
+export const runWithinExportGrant: ExportRunner = (fn) => runner(fn);
diff --git a/frontend/src/metabase/visualizations/lib/save-chart-image.ts b/frontend/src/metabase/visualizations/lib/save-chart-image.ts
index dc3fcefc089..6611e9740b7 100644
--- a/frontend/src/metabase/visualizations/lib/save-chart-image.ts
+++ b/frontend/src/metabase/visualizations/lib/save-chart-image.ts
@@ -2,6 +2,7 @@ import EmbedFrameS from "metabase/embedding/theme.module.css";
import { isStorybookActive } from "metabase/env";
import { openImageBlobOnStorybook } from "metabase/utils/loki-utils";
+import { runWithinExportGrant } from "./chart-export-iframe-grant";
import {
createBrandingElement,
getBrandingConfig,
@@ -45,38 +46,40 @@ export const saveChartImage = async ({
await document.fonts.ready;
const { default: html2canvas } = await import("html2canvas-pro");
- const canvas = await html2canvas(node, {
- scale: 2,
- useCORS: true,
- cspNonce: window.MetabaseNonce,
- height: canvasHeight,
- onclone: (_doc: Document, node: HTMLElement) => {
- node.classList.add(SAVING_DOM_IMAGE_CLASS);
- node.classList.add(EmbedFrameS.WithThemeBackground);
+ const canvas = await runWithinExportGrant(() =>
+ html2canvas(node, {
+ scale: 2,
+ useCORS: true,
+ cspNonce: window.MetabaseNonce,
+ height: canvasHeight,
+ onclone: (_doc: Document, node: HTMLElement) => {
+ node.classList.add(SAVING_DOM_IMAGE_CLASS);
+ node.classList.add(EmbedFrameS.WithThemeBackground);
- node.style.borderRadius = "0px";
- node.style.border = "none";
+ node.style.borderRadius = "0px";
+ node.style.border = "none";
- if (includeBranding) {
- const branding = createBrandingElement(size);
- /**
- * The DOM node that encapsulates the dashboard card is absolutely positioned.
- * That node is the container for the chart, and for the branding element.
- * Unless we sanitize the container, we have to position the branding content
- * appropriately, or it will not be visible.
- */
- branding.style.position = "absolute";
- branding.style.left = "0";
- branding.style.bottom = `-${brandingHeight}px`;
- branding.style.zIndex = "1000";
+ if (includeBranding) {
+ const branding = createBrandingElement(size);
+ /**
+ * The DOM node that encapsulates the dashboard card is absolutely positioned.
+ * That node is the container for the chart, and for the branding element.
+ * Unless we sanitize the container, we have to position the branding content
+ * appropriately, or it will not be visible.
+ */
+ branding.style.position = "absolute";
+ branding.style.left = "0";
+ branding.style.bottom = `-${brandingHeight}px`;
+ branding.style.zIndex = "1000";
- node.appendChild(branding);
- }
+ node.appendChild(branding);
+ }
- resolveSvgVarPaint(node);
- restoreNestedSvgOverflow(node);
- },
- });
+ resolveSvgVarPaint(node);
+ restoreNestedSvgOverflow(node);
+ },
+ }),
+ );
if (isStorybookActive) {
// In storybook/loki we must wait for the blob and image to be ready
diff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.clj
index 6bb25173a21..f75473c6d8e 100644
--- a/src/metabase/server/middleware/security.clj
+++ b/src/metabase/server/middleware/security.clj
@@ -263,13 +263,13 @@
(when config/is-dev?
["'unsafe-eval'"
(str "http://localhost:" cljs-dev-port)])
- ;; Custom data apps run their uploaded bundle inside a Near-Membrane
- ;; sandbox, which executes the bundle source via `eval` (its sandbox
- ;; lives in a same-origin child iframe that inherits this document's
- ;; CSP). So the data-app entrypoint must allow 'unsafe-eval' — scoped
- ;; to this route only; the main app CSP stays strict.
- (when data-app-iframe?
- ["'unsafe-eval'"])
+ ;; NOTE: data-app routes deliberately do NOT get 'unsafe-eval'.
+ ;; Near-Membrane needs `eval` to run the app bundle, but it runs it
+ ;; inside a realm iframe served from `/api/apps/sandbox-host`, whose
+ ;; own CSP grants 'unsafe-eval' for that document alone. Granting it
+ ;; here instead would also hand `eval`/`Function` to anything running
+ ;; in the data-app document itself — including guest code that escaped
+ ;; the membrane.
(when-not config/is-dev?
(map (partial format "'sha256-%s'") inline-js-hashes)))
:child-src ["'self'"
@@ -302,13 +302,21 @@
:font-src (into (cond-> always-allowed-resource-hosts
config/is-dev? (conj frontend-address))
(application-font-files->hosts))
- :img-src (cond-> (if (server.settings/csp-img-enabled)
- (cond-> (into (parse-allowed-resource-hosts (server.settings/csp-img-allowed-hosts))
- (map-tile-server->hosts))
- config/is-dev? (conj frontend-address))
- (into ["*"] always-allowed-resource-hosts))
- ;; Data apps need blob: to load icons for custom viz
- data-app-iframe? (conj "blob:"))
+ :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)))
:connect-src (into
["'self'"
;; Google Identity Services
@@ -356,11 +364,16 @@
(cond-> (update (content-security-policy-header nonce data-app-iframe? data-app-connect-hosts)
"Content-Security-Policy"
#(format "%s frame-ancestors %s;" % (frame-ancestors-value frame-ancestors-mode)))
- ;; Restrict native `<form action="…">` submissions to the app's declared
- ;; `allowed_hosts` (mirroring `connect-src`); with none declared this is
- ;; `'none'`, blocking every native submit. `form-action` does not fall back to
- ;; `default-src`, so it must be set explicitly. Client-side `onSubmit` handlers
- ;; are unaffected — they `preventDefault`, so no submission is ever checked.
+ ;; MANDATORY for data apps — do not remove/weaken. Sole barrier (no JS backstop)
+ ;; against a hostile bundle native-submitting a HOST `<form action="/api/user">`
+ ;; to provision an admin: the backend takes `:form-params` before the JSON body
+ ;; and a `:normal-cookie` session needs no anti-CSRF token, so `form-action` is
+ ;; what stops it. Restricts native submits to the app's `allowed_hosts` (any
+ ;; entry that would match the instance origin — exact or wildcard — is filtered
+ ;; out upstream by `drop-instance-origin`), or `'none'` when none are declared;
+ ;; it does not fall back to `default-src`, so it must be set explicitly.
+ ;; Client-side `onSubmit` (preventDefault) is unaffected. Covered by
+ ;; security-test/data-app-form-action-test; keep in sync if duplicated downstream.
data-app-iframe? (update "Content-Security-Policy"
#(str % " form-action "
(if (seq data-app-connect-hosts)
@@ -523,16 +536,22 @@
:port (let [p (.getPort uri)] (when-not (neg? p) (str p)))}))
(catch Exception _ nil))))
+(defn- covers-instance-origin?
+ "True if `allowed_hosts` entry `host` (possibly a `*.company.com` wildcard) matches the
+ instance's own origin `self`, using the same host-source matching as [[approved-origin?]]."
+ [self host]
+ (when-let [pattern (parse-url host)]
+ (and (approved-domain? (:domain self) (:domain pattern))
+ (approved-protocol? (:protocol self) (:protocol pattern))
+ (approved-port? (:port self) (:port pattern)))))
+
(defn- drop-instance-origin
- "Removes any `allowed_hosts` entry that resolves to this Metabase instance's own
- origin. A native `<form>` submit or frame to the instance would carry the
- user's session cookies, and the SDK is the only sanctioned way to reach
- Metabase — so we keep the instance out of the app's `form-action`/`frame-src`/
- `connect-src` even when an app mistakenly lists it (mirroring the JS fetch/XHR
- sandbox, which blocks the instance origin regardless)."
+ "Removes any `allowed_hosts` entry that would match this instance's own origin (exact or
+ wildcard). A native `<form>`/frame to the instance carries the user's session cookies, so
+ the instance is kept out of the app's `form-action`/`frame-src`/`connect-src`."
[hosts]
(if-let [self (site-origin)]
- (remove #(= self (parse-url %)) hosts)
+ (remove #(covers-instance-origin? self %) hosts)
hosts))
(defn- add-security-headers* [request response]
diff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.clj
index 6f979827251..c59b2344e39 100644
--- a/test/metabase/server/middleware/security_test.clj
+++ b/test/metabase/server/middleware/security_test.clj
@@ -117,7 +117,16 @@
(filter #(str/starts-with? % (str directive " ")))
first))
+;; `form-action` is the SOLE barrier (no JS backstop) against a hostile bundle
+;; native-submitting a HOST `<form action="/api/user">` to provision an admin — the
+;; backend takes `:form-params` before the JSON body and a normal-cookie session
+;; needs no anti-CSRF token. So on a data-app iframe document it must ALWAYS be set,
+;; and must never resolve to a value that reaches the instance origin.
(deftest data-app-form-action-test
+ (testing "form-action is ALWAYS set on a data-app iframe document (its absence = admin provisioning)"
+ (doseq [hosts [[] ["https://api.example.com"]]]
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly hosts)]
+ (is (some? (csp-directive-for "/embed/apps/sales" "form-action"))))))
(testing "with no allowed_hosts, native <form action> submits are blocked (client-side onSubmit still works)"
(with-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
(is (= "form-action 'none'" (csp-directive-for "/embed/apps/sales" "form-action")))
@@ -132,6 +141,21 @@
(doseq [uri ["/embed/dashboard/abc" "/public/question/abc" "/apps/sales"]]
(is (nil? (csp-directive-for uri "form-action"))))))
+(deftest data-app-unsafe-eval-test
+ ;; Near-Membrane needs `eval` to run the app bundle, but it runs it inside a realm
+ ;; iframe served from `/api/apps/sandbox-host`, which carries the grant in its own
+ ;; CSP. Granting it on the data-app document too would hand `eval`/`Function` to
+ ;; anything running there — including guest code that escaped the membrane.
+ (testing "the data-app document does not get 'unsafe-eval'"
+ (with-redefs [config/is-dev? false]
+ (doseq [uri ["/embed/apps/sales" "/embed/apps/sales/sub/route" "/apps/sales"]]
+ (is (not (str/includes? (csp-directive-for uri "script-src") "'unsafe-eval'"))
+ (str uri " should not grant 'unsafe-eval'")))))
+ (testing "and neither does any other document"
+ (with-redefs [config/is-dev? false]
+ (is (not (str/includes? (csp-directive-for "/embed/dashboard/abc" "script-src")
+ "'unsafe-eval'"))))))
+
(deftest data-app-frame-src-test
(testing "a data app's frame-src is a per-app allowlist: only 'self' + its allowed_hosts"
;; A global iframe host (wikipedia) is configured but must NOT leak into a data
@@ -173,6 +197,34 @@
(is (not (str/includes? frame-src "https://mymetabase.example")))
(is (not (str/includes? connect-src "https://mymetabase.example")))))))))
+(deftest data-app-instance-origin-wildcard-excluded-test
+ (testing "a wildcard allowed_hosts entry covering the instance origin is dropped from the app allowlist"
+ ;; The instance is hosted on a subdomain that a broad wildcard would cover. Left in
+ ;; place, `form-action https://*.company.com` matches `mb.company.com`, letting a
+ ;; hostile bundle native-submit a `<form action="…/api/user">` and provision an admin.
+ (mt/with-temporary-setting-values [site-url "https://mb.company.com"]
+ (with-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://*.company.com" ; covers mb.company.com -> must be dropped
+ "https://*.othercdn.com" ; unrelated wildcard -> must survive
+ "https://api.allowed.test"])]
+ (let [form-action (csp-directive-for "/embed/apps/sales" "form-action")
+ frame-src (csp-directive-for "/embed/apps/sales" "frame-src")
+ connect-src (csp-directive-for "/embed/apps/sales" "connect-src")]
+ (testing "the wildcard covering the instance origin is stripped from every directive"
+ (doseq [[directive value] {"form-action" form-action
+ "frame-src" frame-src
+ "connect-src" connect-src}]
+ (is (not (str/includes? value "*.company.com"))
+ (str directive " must not admit a wildcard covering the instance origin"))))
+ (testing "an unrelated wildcard and a genuinely-external host are preserved"
+ (doseq [[directive value] {"form-action" form-action
+ "frame-src" frame-src
+ "connect-src" connect-src}]
+ (is (str/includes? value "https://*.othercdn.com")
+ (str directive " must keep an unrelated wildcard"))
+ (is (str/includes? value "https://api.allowed.test")
+ (str directive " must keep an external host")))))))))
+
(deftest data-app-connect-src-test
(testing "a data app's allowed_hosts are added to the iframe document's connect-src"
(with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
@@ -243,23 +295,10 @@
(is (str/includes? data-script-src "'nonce-"))
(is (not (str/includes? data-script-src "'unsafe-inline'")))))))
-(deftest data-app-unsafe-eval-csp-test
- (testing "Only data-app iframe responses allow 'unsafe-eval' in script-src"
- ;; Data apps run their uploaded bundle through a Near-Membrane sandbox whose
- ;; same-origin child iframe inherits this document's CSP and evaluates the
- ;; bundle source via `eval`, so the data-app entrypoint must permit
- ;; 'unsafe-eval' while the main app CSP stays strict.
- (with-redefs [config/is-dev? false]
- (let [wrapped-handler (mw.security/add-security-headers
- (fn [_request respond _raise]
- (respond {:status 200 :headers {} :body "ok"})))
- script-src-for (fn [uri]
- (-> (wrapped-handler {:uri uri :headers {}} identity identity)
- (csp-directive-from-response "script-src")))]
- (is (not (str/includes? (script-src-for "/") "'unsafe-eval'")))
- (is (str/includes? (script-src-for "/embed/apps/boba") "'unsafe-eval'"))
- ;; sub-routes under the data-app entrypoint are the same SPA shell
- (is (str/includes? (script-src-for "/embed/apps/boba/sub/route") "'unsafe-eval'"))))))
+;; NOTE: `unsafe-eval` was removed from the data-app iframe document (it now lives
+;; only in the sandbox-host realm's own CSP). `data-app-unsafe-eval-test` above
+;; asserts the data-app document does NOT get it; the old contradicting test that
+;; expected it here was removed.
(deftest data-app-blob-img-csp-test
(testing "Only data-app iframe responses allow the blob: scheme in img-src"
@@ -274,6 +313,31 @@
(is (str/includes? (img-src-for "/embed/apps/boba") "blob:"))
(is (str/includes? (img-src-for "/embed/apps/boba/sub/route") "blob:"))))))
+;; A sandboxed data-app document must never get `img-src *`: the `img` tag can't be
+;; blocked (the SDK renders images), and `new Image()`/`<img>` under `*` would beacon
+;; the viewing user's data off-origin. It uses the restricted allowlist regardless of
+;; `csp-img-enabled`, still respecting the admin's "Allowed domains for images".
+(deftest data-app-img-src-no-wildcard-test
+ (mt/with-temporary-setting-values [csp-img-enabled false]
+ ;; Check the standalone `*` token, not the substring — a map-tile host like
+ ;; `*.tile.openstreetmap.org` legitimately contains `*`.
+ (let [wildcard? (fn [uri] (contains? (set (str/split (csp-directive-for uri "img-src") #" +")) "*"))]
+ (testing "with csp-img-enabled off, a data-app img-src drops the `*` the rest of the app gets"
+ (is (wildcard? "/embed/dashboard/abc"))
+ (is (not (wildcard? "/embed/apps/sales")) "data-app img-src must not contain the bare wildcard")
+ (let [img-src (csp-directive-for "/embed/apps/sales" "img-src")]
+ (is (str/includes? img-src "'self'"))
+ (is (str/includes? img-src "blob:")))))
+ (testing "and it still honors the admin's Allowed domains for images (csp-img-allowed-hosts)"
+ (mt/with-temporary-setting-values [csp-img-allowed-hosts "https://cdn.example.com"]
+ (is (str/includes? (csp-directive-for "/embed/apps/sales" "img-src")
+ "https://cdn.example.com"))))
+ (testing "and the app's own allowed_hosts (mirroring connect-src/frame-src), plus 'self'"
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.myapp.com"])]
+ (let [img-src (csp-directive-for "/embed/apps/sales" "img-src")]
+ (is (str/includes? img-src "https://api.myapp.com"))
+ (is (str/includes? img-src "'self'")))))))
+
(deftest ^:parallel test-parse-url
(testing "Should parse valid urls"
(are [url expected] (= expected