Skip to content

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

5.6 KB
Raw Blame
import { makeSandboxDistortionCallback } from "metabase/utils/scripts-sandbox";

import { makeSandboxFetch } from "./allowed-hosts";
import { makeCreateElementDistortion } from "./create-element";
import type {
  SandboxBlockedListener,
  SandboxBlockedNetworkInfo,
  SandboxRealm,
} from "./types";

const REALM_CREATING_CTOR_NAMES = [
  "HTMLIFrameElement",
  "HTMLFrameElement",
  "HTMLObjectElement",
  "HTMLEmbedElement",
] as const;

/**
 * Data-app Near-Membrane distortion callback. Reuses the shared
 * `utils/scripts-sandbox` callback (same fetch/XHR/DOM blocking as custom-viz), but
 * allows `fetch` to the analytics proxy and the app's `allowed_hosts`. `XMLHttpRequest` is
 * never allowlisted (it can't opt out of following a redirect to the instance), so
 * `blockHostRealmXhr` hard-blocks it. No per-plugin DOM scoping like custom-viz: a
 * data app is a full-page route owned by one bundle, with no sibling DOM.
 */
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
      // the data-app code that called the blocked API.
      console.error(message);
    },
  );
  const onBlockedNetwork =
    onBlocked &&
    ((info: SandboxBlockedNetworkInfo) =>
      onBlocked({ type: "network", ...info }));
  const sandboxFetch = makeSandboxFetch(
    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 to the gated target, and hide the frame
  // element so DOM traversal libraries don't escape into the parent document.
  // Captured before the membrane is built, while the ancestors are 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 = (target: object, key: string) => {
    let current: object | null = target;

    while (current) {
      const getter = Object.getOwnPropertyDescriptor(current, key)?.get;

      if (getter) {
        return getter;
      }

      current = Object.getPrototypeOf(current);
    }
  };

  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.opener) {
      ancestors.add(realm.opener);
    }
  } catch {
    // opener unreachable — nothing to redirect
  }

  // An adopted element keeps whichever realm's prototype Chrome last built its
  // wrapper on, so capture every reachable realm's getters, not just this one's.
  const realmCreatingProtos = [realm, ...ancestors].flatMap((win) => {
    try {
      // `ancestors` holds `unknown`, and these aren't indexable on `Window`.
      const globals = win as Record<string, { prototype?: object }>;

      return REALM_CREATING_CTOR_NAMES.map(
        (name) => globals[name]?.prototype,
      ).filter((proto): proto is object => !!proto);
    } catch {
      // Cross-origin realm — unreachable for the guest too.
      return [];
    }
  });
  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 frameElementGetter = getterOf(realm, "frameElement");
  const getGatedRealm = () => realm;
  const getNull = () => null;

  return function distortionCallback(value: object): object {
    const createElementDistortion = makeCreateElementDistortion(value, shared);

    if (createElementDistortion) {
      return createElementDistortion;
    }

    if (value === targetWindow.fetch) {
      return sandboxFetch;
    }

    if (ancestors.has(value)) {
      return realm;
    }

    if (frameElementGetter && value === frameElementGetter) {
      return getNull;
    }

    // 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);
  };
}