Skip to content

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

Add ability to report near membrane sandboxing blocks to a listener (#78344)

Timofey Kachalov35444ee8a5a6
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 36cdd599992..9a2fa4b30ad 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
@@ -16,16 +16,7 @@
* sandboxed browser realm — so keep the two in sync if either changes.
*/
-/**
- * The slice of the sandbox's realm the network wrappers touch: the native
- * `fetch`/`XMLHttpRequest` they wrap, and the location a relative request URL
- * resolves against. A real `Window & typeof globalThis` satisfies it.
- */
-export interface SandboxRealm {
- fetch: typeof fetch;
- XMLHttpRequest: typeof XMLHttpRequest;
- location: { href: string; origin: string };
-}
+import type { SandboxBlockedNetworkListener, SandboxRealm } from "./types";
interface AllowedOrigin {
protocol: string; // "https:" | "http:"
@@ -38,7 +29,7 @@ interface AllowedOrigin {
* A valid `allowed_hosts` entry is *origin-only*: an http(s) scheme + host (+ an
* optional port), with no path, query, fragment, or credentials.
*/
-function isRawHttpOrigin(url: URL): boolean {
+const isRawHttpOrigin = (url: URL): boolean => {
return (
(url.protocol === "https:" || url.protocol === "http:") &&
url.pathname === "/" &&
@@ -47,9 +38,9 @@ function isRawHttpOrigin(url: URL): boolean {
url.username === "" &&
url.password === ""
);
-}
+};
-function parseAllowedOrigin(entry: string): AllowedOrigin | null {
+const parseAllowedOrigin = (entry: string): AllowedOrigin | null => {
let url: URL;
try {
// The standard URL parser lowercases the host, normalizes away the default
@@ -72,9 +63,9 @@ function parseAllowedOrigin(entry: string): AllowedOrigin | null {
host: wildcard ? url.hostname.slice(2) : url.hostname,
port: url.port,
};
-}
+};
-function originMatches(url: URL, origin: AllowedOrigin): boolean {
+const isOriginMatches = (url: URL, origin: AllowedOrigin): boolean => {
if (url.protocol !== origin.protocol) {
return false;
}
@@ -89,17 +80,17 @@ function originMatches(url: URL, origin: AllowedOrigin): boolean {
return origin.wildcard
? host.endsWith(`.${origin.host}`)
: host === origin.host;
-}
+};
-export function isHostAllowed(url: URL, allowedHosts: string[]): boolean {
+export const isHostAllowed = (url: URL, allowedHosts: string[]): boolean => {
return allowedHosts.some((entry) => {
const origin = parseAllowedOrigin(entry);
- return origin ? originMatches(url, origin) : false;
+ return origin ? isOriginMatches(url, origin) : false;
});
-}
+};
-function toUrl(input: unknown, base: string): URL | null {
+const toUrl = (input: RequestInfo | URL, base: string): URL | null => {
try {
if (typeof input === "string") {
return new URL(input, base);
@@ -117,24 +108,16 @@ function toUrl(input: unknown, base: string): URL | null {
}
return null;
-}
+};
-/**
- * The single decision the `fetch` and `XMLHttpRequest` wrappers share: resolve
- * the request URL and decide whether the sandbox may make it. Returns `null`
- * when the request is allowed, or a human-readable reason when it is blocked.
- *
- * A request is allowed only when its origin is in `allowedHosts` AND is not the
- * Metabase origin — raw access to Metabase is *always* denied (the SDK is the
- * sanctioned channel), even if an admin mistakenly lists it in `allowed_hosts`.
- */
-function blockedReason(
- input: unknown,
+const getBlockedReason = (
+ input: RequestInfo | URL,
base: string,
allowedHosts: string[],
metabaseOrigin: string,
-): string | null {
+): string | null => {
const url = toUrl(input, base);
+
if (!url) {
return "an unparseable URL";
}
@@ -148,18 +131,29 @@ function blockedReason(
}
return null;
-}
+};
-/**
- * A `fetch` that only reaches `allowedHosts` (rejecting everything else,
- * including the Metabase origin). Returns `null` when the allowlist is empty so
- * the caller keeps the sandbox's default hard block.
- */
-export function makeSandboxFetch(
+const reportBlockedEvent = (
+ onBlocked: SandboxBlockedNetworkListener | undefined,
+ event: Parameters<SandboxBlockedNetworkListener>[0],
+): void => {
+ try {
+ onBlocked?.(event);
+ } catch {
+ // A broken reporter is not the app's problem.
+ }
+};
+
+const buildRequestUrl = (input: RequestInfo | URL, base: string): string => {
+ return toUrl(input, base)?.href ?? String(input);
+};
+
+export const makeSandboxFetch = (
targetWindow: SandboxRealm,
allowedHosts: string[],
label: string,
-): typeof fetch | null {
+ onBlocked?: SandboxBlockedNetworkListener,
+): typeof fetch | null => {
if (allowedHosts.length === 0) {
return null;
}
@@ -169,9 +163,15 @@ export function makeSandboxFetch(
const metabaseOrigin = targetWindow.location.origin;
return function dataAppFetch(input: RequestInfo | URL, init?: RequestInit) {
- const reason = blockedReason(input, base, allowedHosts, metabaseOrigin);
+ const reason = getBlockedReason(input, base, allowedHosts, metabaseOrigin);
if (reason) {
+ reportBlockedEvent(onBlocked, {
+ api: "fetch",
+ url: buildRequestUrl(input, base),
+ reason,
+ });
+
return Promise.reject(
new Error(`[data-app ${label}] blocked fetch to ${reason}`),
);
@@ -179,18 +179,14 @@ export function makeSandboxFetch(
return realFetch(input, init);
};
-}
+};
-/**
- * An `XMLHttpRequest` subclass that gates `open()` against `allowedHosts` (and
- * always denies the Metabase origin). Returns `null` when the allowlist is empty
- * (keeps the default hard block).
- */
-export function makeSandboxXhr(
+export const makeSandboxXhr = (
targetWindow: SandboxRealm,
allowedHosts: string[],
label: string,
-): typeof XMLHttpRequest | null {
+ onBlocked?: SandboxBlockedNetworkListener,
+): typeof XMLHttpRequest | null => {
if (allowedHosts.length === 0) {
return null;
}
@@ -206,9 +202,15 @@ export function makeSandboxXhr(
username?: string | null,
password?: string | null,
): void {
- const reason = blockedReason(url, base, allowedHosts, metabaseOrigin);
+ 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}`,
);
@@ -220,4 +222,4 @@ export function makeSandboxXhr(
// 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;
-}
+};
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 42db9ddf5ab..cea333cd2d4 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,9 +1,9 @@
import {
- type SandboxRealm,
isHostAllowed,
makeSandboxFetch,
makeSandboxXhr,
} from "./allowed-hosts";
+import type { SandboxRealm } from "./types";
const u = (href: string) => new URL(href);
@@ -179,3 +179,60 @@ describe("makeSandboxXhr", () => {
);
});
});
+
+describe("onBlocked reporting", () => {
+ const base = "https://mb.example.com/embed/apps/sales";
+ const origin = "https://mb.example.com";
+ const fakeWindow = (fetch: typeof global.fetch): SandboxRealm => ({
+ fetch,
+ XMLHttpRequest,
+ location: { href: base, origin },
+ });
+
+ it("reports a blocked fetch, and stays silent when no listener is given", async () => {
+ const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));
+ const onBlocked = jest.fn();
+
+ const reporting = makeSandboxFetch(
+ fakeWindow(realFetch),
+ ["https://api.example.com"],
+ "sales",
+ onBlocked,
+ )!;
+ await expect(reporting("https://evil.example.org/x")).rejects.toThrow();
+
+ expect(onBlocked).toHaveBeenCalledWith(
+ // `type: "network"` is added a layer up, in `distortions.ts`.
+ expect.objectContaining({
+ api: "fetch",
+ url: "https://evil.example.org/x",
+ reason: expect.stringContaining("not in allowed_hosts"),
+ }),
+ );
+
+ // Production passes no listener; that path must be unchanged.
+ const silent = makeSandboxFetch(
+ fakeWindow(realFetch),
+ ["https://api.example.com"],
+ "sales",
+ )!;
+ await expect(silent("https://evil.example.org/x")).rejects.toThrow();
+ expect(realFetch).not.toHaveBeenCalled();
+ });
+
+ it("still blocks when the listener throws", async () => {
+ const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));
+ const sandboxFetch = makeSandboxFetch(
+ fakeWindow(realFetch),
+ ["https://api.example.com"],
+ "sales",
+ () => {
+ throw new Error("listener exploded");
+ },
+ )!;
+
+ // A broken reporter must not become a way through the allowlist.
+ await expect(sandboxFetch("https://evil.example.org/")).rejects.toThrow();
+ expect(realFetch).not.toHaveBeenCalled();
+ });
+});
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 f0ddc0c7aca..0ed5f0ddaf0 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts
@@ -1,11 +1,12 @@
import { makeSandboxDistortionCallback } from "metabase/utils/scripts-sandbox";
-import {
- type SandboxRealm,
- makeSandboxFetch,
- makeSandboxXhr,
-} from "./allowed-hosts";
+import { makeSandboxFetch, makeSandboxXhr } from "./allowed-hosts";
import { makeCreateElementDistortion } from "./create-element";
+import type {
+ SandboxBlockedListener,
+ SandboxBlockedNetworkInfo,
+ SandboxRealm,
+} from "./types";
/**
* Data-app Near Membrane distortion callback.
@@ -27,10 +28,15 @@ export function makeDistortionCallback(
label: string,
targetWindow: SandboxRealm,
allowedHosts: string[],
+ onBlocked?: SandboxBlockedListener,
) {
const shared = makeSandboxDistortionCallback(
`data-app ${label}`,
(message) => {
+ if (onBlocked) {
+ onBlocked({ type: "api", message });
+ return;
+ }
// The thrown error usually reaches the developer only as an opaque
// cross-realm `#<Object>` (an unhandled async rejection), so log the real
// reason here — at the block point, where the console stack still points at
@@ -38,8 +44,22 @@ export function makeDistortionCallback(
console.error(message);
},
);
- const sandboxFetch = makeSandboxFetch(targetWindow, allowedHosts, label);
- const sandboxXhr = makeSandboxXhr(targetWindow, allowedHosts, label);
+ const onBlockedNetwork =
+ onBlocked &&
+ ((info: SandboxBlockedNetworkInfo) =>
+ onBlocked({ type: "network", ...info }));
+ const sandboxFetch = makeSandboxFetch(
+ targetWindow,
+ allowedHosts,
+ label,
+ onBlockedNetwork,
+ );
+ const sandboxXhr = makeSandboxXhr(
+ targetWindow,
+ allowedHosts,
+ label,
+ onBlockedNetwork,
+ );
return function distortionCallback(value: object): object {
const createElementDistortion = makeCreateElementDistortion(value, shared);
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 dcbbe60e4c2..e18d842575c 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
@@ -1,5 +1,5 @@
-import type { SandboxRealm } from "./allowed-hosts";
import { makeDistortionCallback } from "./distortions";
+import type { SandboxRealm } from "./types";
// A minimal stand-in for the iframe window the data-app sandbox is built on.
// `fetch`/`XMLHttpRequest` are the native refs the membrane passes to the
@@ -97,4 +97,78 @@ describe("makeDistortionCallback", () => {
const other = { some: "object" };
expect(callback(other)).toBe(other);
});
+
+ describe("onBlocked", () => {
+ it("reports a blocked API instead of logging it", () => {
+ const consoleErrorSpy = jest
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+ const onBlocked = jest.fn();
+ const callback = makeDistortionCallback(
+ "sales",
+ fakeWindow(),
+ [],
+ onBlocked,
+ );
+ // Same signature erasure as above.
+ const createElement = callback(
+ Document.prototype.createElement,
+ ) as typeof Document.prototype.createElement;
+
+ expect(() => createElement.call(document, "script")).toThrow();
+
+ expect(onBlocked).toHaveBeenCalledWith({
+ type: "api",
+ message: expect.stringContaining("blocked createElement: script"),
+ });
+ expect(consoleErrorSpy).not.toHaveBeenCalled();
+ consoleErrorSpy.mockRestore();
+ });
+
+ it("reports a blocked fetch with the resolved url and reason", async () => {
+ 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.fetch) as typeof fetch;
+
+ await expect(distorted("https://evil.example.org/")).rejects.toThrow();
+
+ expect(onBlocked).toHaveBeenCalledWith({
+ type: "network",
+ api: "fetch",
+ url: "https://evil.example.org/",
+ 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/sandbox.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts
index dbb5385a3b0..cf97b031fe0 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts
@@ -2,7 +2,7 @@ import createVirtualEnvironment from "@locker/near-membrane-dom";
import { makeDistortionCallback } from "./distortions";
import { DATA_APP_GLOBAL_NAMES } from "./globals";
-import type { DataAppFactory } from "./types";
+import type { DataAppFactory, SandboxBlockedListener } from "./types";
/**
* The realm objects the sandbox exposes to the bundle as globals.
@@ -46,6 +46,11 @@ export interface CreateDataAppSandboxOptions {
allowedHosts?: string[];
/** The realm's React/SDK exposed to the bundle. See [[DataAppSandboxEndowments]]. */
endowments: DataAppSandboxEndowments;
+ /**
+ * Structured listener for sandbox blocks (dev toolbar). When absent the
+ * sandbox keeps its default reporting (`console.error` / reject).
+ */
+ onBlocked?: SandboxBlockedListener;
}
function isLiveTarget(target: object): boolean {
@@ -61,6 +66,7 @@ export function createDataAppSandbox({
targetWindow = window,
allowedHosts = [],
endowments,
+ onBlocked,
}: CreateDataAppSandboxOptions) {
let captured: unknown;
@@ -69,6 +75,7 @@ export function createDataAppSandbox({
label,
targetWindow,
allowedHosts,
+ onBlocked,
),
liveTargetCallback: isLiveTarget,
// Global names come from the shared `DATA_APP_GLOBAL_NAMES`, so the bundle's
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts
index 491d82d354f..a1e7c3a15f5 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts
@@ -10,12 +10,6 @@ export const DATA_APP_PROVIDER_PROP_KEYS = [
"errorComponent",
] as const satisfies readonly (keyof DataAppMetabaseProviderProps)[];
-/**
- * Structural mirror of the `MetabaseProviderProps` subset a data app may
- * customize. Declared here (not as a `Pick` of the bundle type) so this
- * contract has no app-tier dependency; keep it in sync with
- * `MetabaseProviderProps` by hand until the props move to a shared tier.
- */
export type DataAppMetabaseProviderProps = {
theme?: MetabaseEmbeddingTheme;
allowedCustomVisualizations?: `custom:${string}`[];
@@ -35,3 +29,30 @@ export type DataAppFactory = () => {
component: React.ComponentType<Record<string, unknown>>;
providerProps?: DataAppMetabaseProviderProps;
};
+
+/**
+ * The slice of the sandbox's realm the network wrappers touch: the native
+ * `fetch`/`XMLHttpRequest` they wrap, and the location a relative request URL
+ * resolves against. A real `Window & typeof globalThis` satisfies it.
+ */
+export interface SandboxRealm {
+ fetch: typeof fetch;
+ XMLHttpRequest: typeof XMLHttpRequest;
+ location: { href: string; origin: string };
+}
+
+export interface SandboxBlockedNetworkInfo {
+ api: "fetch" | "xhr";
+ url: string;
+ reason: string;
+}
+
+export type SandboxBlockedNetworkListener = (
+ info: SandboxBlockedNetworkInfo,
+) => void;
+
+export type SandboxBlockedEvent =
+ | { type: "api"; message: string }
+ | ({ type: "network" } & SandboxBlockedNetworkInfo);
+
+export type SandboxBlockedListener = (event: SandboxBlockedEvent) => void;