Skip to content

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

Prompt to reload after changing settings that update CSP (#80906)

Kevin Kelleher8819a72555a9
diff --git a/frontend/src/metabase-types/api/icon.ts b/frontend/src/metabase-types/api/icon.ts
index e20dcf13277..b5459f9b796 100644
--- a/frontend/src/metabase-types/api/icon.ts
+++ b/frontend/src/metabase-types/api/icon.ts
@@ -165,6 +165,7 @@ export type IconName =
| "mail"
| "mail_at"
| "mail_filled"
+ | "map"
| "mcp"
| "medallion"
| "message_circle"
diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
index 20c554b0b73..1c18aa2b1d6 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
@@ -57,6 +57,7 @@ export function SettingsNav() {
{hasJwt && <SettingsNavItem path="authentication/jwt" label="JWT" />}
{hasOidc && <SettingsNavItem path="authentication/oidc" label="OIDC" />}
</SettingsNavItem>
+ <SettingsNavItem path="domains" label={t`Domains`} icon="globe" />
{PLUGIN_REMOTE_SYNC.isEnabled ? (
<PLUGIN_REMOTE_SYNC.LibraryNav />
) : !isPro ? (
@@ -80,14 +81,14 @@ export function SettingsNav() {
<SettingsNavItem
path="localization"
label={t`Localization`}
- icon="globe"
+ icon="pinmap"
/>
{/* do not allow users with "Settings access" permissions to access custom viz pages */}
{isAdmin && <CustomVisualizationsNav />}
{/* TODO(v65): data apps launch in v65 — drop the isEnabled gate then so
the nav item (and its upsell gem) shows without the token feature */}
{isAdmin && PLUGIN_DATA_APPS.isEnabled && <DataAppsNav />}
- <SettingsNavItem path="maps" label={t`Maps`} icon="pinmap" />
+ <SettingsNavItem path="maps" label={t`Maps`} icon="map" />
<SettingsNavItem
path={!hasWhitelabel ? "whitelabel" : undefined}
folderPattern="whitelabel"
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/CustomVisualizationsSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/CustomVisualizationsSettingsPage.tsx
index 43eb4d934a8..768c2f50c95 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsPages/CustomVisualizationsSettingsPage.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/CustomVisualizationsSettingsPage.tsx
@@ -124,10 +124,10 @@ function CustomVizEmptyState() {
{jt`Turn on "Restrict image domains" in ${(
<Link
key="link"
- to={Urls.generalSettings()}
+ to={Urls.domainsSettings()}
variant="brand"
>
- {t`General settings`}
+ {t`Domains settings`}
</Link>
)} before enabling custom visualizations.`}
</Text>
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/DomainsSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/DomainsSettingsPage.tsx
new file mode 100644
index 00000000000..8ecfa53e8f6
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/DomainsSettingsPage.tsx
@@ -0,0 +1,202 @@
+import type { FormikHelpers } from "formik";
+import { flushSync } from "react-dom";
+import { jt, t } from "ttag";
+
+import {
+ SettingsPageWrapper,
+ SettingsSection,
+} from "metabase/admin/components/SettingsSection";
+import { isSettingSetFromEnvVar } from "metabase/admin/settings/settings";
+import { ExternalLink } from "metabase/common/components/ExternalLink";
+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";
+import { Link } from "metabase/common/components/Link";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { SetByEnvVar } from "metabase/common/components/SetByEnvVar";
+import { useDocsUrl, useHasTokenFeature } from "metabase/common/hooks";
+import {
+ Form,
+ FormErrorMessage,
+ FormProvider,
+ FormSubmitButton,
+ FormSwitch,
+ FormTextarea,
+} from "metabase/forms";
+import { useAdminSetting, useAdminSettings } from "metabase/settings";
+import { Box, Stack } from "metabase/ui";
+import * as Urls from "metabase/urls";
+import { reload } from "metabase/utils/dom";
+
+import { SettingHeader } from "../SettingHeader";
+
+import {
+ type DomainsSettings,
+ isDomainSettingsDirty,
+ isEmptyString,
+ normalizeDomainSettings,
+} from "./domainSettingsUtils";
+
+export function DomainsSettingsPage() {
+ const { values, details, updateSettings, isLoading, error } =
+ useAdminSettings([
+ "allowed-iframe-hosts",
+ "csp-img-enabled",
+ "csp-img-allowed-hosts",
+ ]);
+
+ const { url: iframeDocsUrl } = useDocsUrl("configuring-metabase/settings", {
+ anchor: "allowed-domains-for-iframes-in-dashboards",
+ });
+ const { url: imgDocsUrl } = useDocsUrl("configuring-metabase/settings", {
+ anchor: "allowed-domains-for-images",
+ });
+
+ const customVizAvailable = useHasTokenFeature("custom-viz-available");
+ const { value: customVizEnabled } = useAdminSetting("custom-viz-enabled");
+
+ const onSubmit = async (
+ values: DomainsSettings,
+ { resetForm }: FormikHelpers<DomainsSettings>,
+ ) => {
+ const { error } = await updateSettings({
+ ...normalizeDomainSettings(values),
+ toast: false,
+ });
+ if (error) {
+ throw error;
+ }
+ // CSP settings need a reload to take effect
+ // but reloading while the form is dirty triggers LeaveRouteConfirmModal
+ // so synchronously reset the form
+ flushSync(() => resetForm({ values }));
+ reload();
+ };
+
+ if (isLoading || error) {
+ return <LoadingAndErrorWrapper loading={isLoading} error={error} />;
+ }
+
+ return (
+ <SettingsPageWrapper title={t`Domains`}>
+ <SettingsSection>
+ <FormProvider
+ initialValues={{
+ ...values,
+ "allowed-iframe-hosts": isEmptyString(
+ values["allowed-iframe-hosts"],
+ )
+ ? ""
+ : values["allowed-iframe-hosts"],
+ }}
+ onSubmit={onSubmit}
+ >
+ {({ initialValues, values }) => {
+ const dirty = isDomainSettingsDirty(initialValues, values);
+ return (
+ <>
+ <Form disabled={!dirty}>
+ <Stack gap="lg">
+ <Box>
+ <SettingHeader
+ id="allowed-iframe-hosts"
+ title={t`Allowed domains for iframes in dashboards`}
+ description={
+ <>
+ {jt`You should make sure to trust the sources you allow your users to embed in dashboards. ${<ExternalLink key="docs" href={iframeDocsUrl}>{t`Learn more`}</ExternalLink>}`}
+ </>
+ }
+ />
+ {isSettingSetFromEnvVar(
+ details["allowed-iframe-hosts"],
+ ) ? (
+ <SetByEnvVar
+ varName={details["allowed-iframe-hosts"].env_name}
+ />
+ ) : (
+ <FormTextarea
+ id="allowed-iframe-hosts"
+ name="allowed-iframe-hosts"
+ nullable
+ />
+ )}
+ </Box>
+ <Box>
+ <SettingHeader
+ id="csp-img-enabled"
+ title={t`Restrict image domains`}
+ description={
+ customVizEnabled
+ ? jt`Required by Custom Visualizations. Turn off ${(
+ <Link
+ key="custom-viz"
+ to={Urls.customViz()}
+ variant="brand"
+ >
+ {t`Custom Visualizations`}
+ </Link>
+ )} before disabling this setting.`
+ : customVizAvailable
+ ? jt`Restrict the browser's Content Security Policy so images can only load from this Metabase instance or the domains you list below. Required to enable Custom Visualizations. ${<ExternalLink key="img-docs" href={imgDocsUrl}>{t`Learn more`}</ExternalLink>}`
+ : t`Restrict the browser's Content Security Policy so images can only load from this Metabase instance or the domains you list below.`
+ }
+ />
+ {isSettingSetFromEnvVar(details["csp-img-enabled"]) ? (
+ <SetByEnvVar
+ varName={details["csp-img-enabled"].env_name}
+ />
+ ) : (
+ <FormSwitch
+ id="csp-img-enabled"
+ name="csp-img-enabled"
+ label={
+ values["csp-img-enabled"] ? t`Enabled` : t`Disabled`
+ }
+ size="sm"
+ disabled={Boolean(customVizEnabled)}
+ />
+ )}
+ </Box>
+ <Box>
+ <SettingHeader
+ id="csp-img-allowed-hosts"
+ title={t`Allowed domains for images`}
+ description={
+ values["csp-img-enabled"]
+ ? customVizAvailable
+ ? jt`Domains that images can be loaded from in dashboard text, entity descriptions, and custom visualizations. Leave empty to only allow images hosted by this Metabase instance. ${<ExternalLink key="img-docs" href={imgDocsUrl}>{t`Learn more`}</ExternalLink>}`
+ : jt`Domains that images can be loaded from in dashboard text and entity descriptions. Leave empty to only allow images hosted by this Metabase instance. ${<ExternalLink key="img-docs" href={imgDocsUrl}>{t`Learn more`}</ExternalLink>}`
+ : t`Turn on the "Restrict image domains" setting above to enforce this allowlist.`
+ }
+ />
+ {isSettingSetFromEnvVar(
+ details["csp-img-allowed-hosts"],
+ ) ? (
+ <SetByEnvVar
+ varName={details["csp-img-allowed-hosts"].env_name}
+ />
+ ) : (
+ <FormTextarea
+ id="csp-img-allowed-hosts"
+ name="csp-img-allowed-hosts"
+ disabled={!values["csp-img-enabled"]}
+ nullable
+ />
+ )}
+ </Box>
+ <FormErrorMessage />
+ <FormSubmitButton
+ label={t`Save changes`}
+ variant="filled"
+ disabled={!dirty}
+ style={{ alignSelf: "flex-end" }}
+ />
+ </Stack>
+ </Form>
+ <LeaveRouteConfirmModal isEnabled={dirty} />
+ </>
+ );
+ }}
+ </FormProvider>
+ </SettingsSection>
+ </SettingsPageWrapper>
+ );
+}
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/DomainsSettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/DomainsSettingsPage.unit.spec.tsx
new file mode 100644
index 00000000000..2cd79ea5ff9
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/DomainsSettingsPage.unit.spec.tsx
@@ -0,0 +1,256 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ findRequests,
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+ setupUpdateSettingsEndpoint,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { Route } from "metabase/router";
+import * as domUtils from "metabase/utils/dom";
+import type { SettingDefinition } from "metabase-types/api";
+import {
+ createMockSettingDefinition,
+ createMockSettings,
+} from "metabase-types/api/mocks";
+
+import { DomainsSettingsPage } from "./DomainsSettingsPage";
+
+const IFRAME_HOSTS_LABEL = "Allowed domains for iframes in dashboards";
+const IMAGE_HOSTS_LABEL = "Allowed domains for images";
+const CSP_SWITCH_NAME = /Restrict image domains/i;
+
+type SetupOpts = {
+ iframeHosts?: string;
+ cspImgEnabled?: boolean;
+ imageHosts?: string;
+ customVizEnabled?: boolean;
+ settingDefinitions?: SettingDefinition[];
+ saveStatus?: number;
+};
+
+const setup = async ({
+ iframeHosts = "youtube.com",
+ cspImgEnabled = true,
+ imageHosts = "imgcdn.example.com",
+ customVizEnabled = false,
+ settingDefinitions,
+ saveStatus = 204,
+}: SetupOpts = {}) => {
+ const settings = createMockSettings({
+ "allowed-iframe-hosts": iframeHosts,
+ "csp-img-enabled": cspImgEnabled,
+ "csp-img-allowed-hosts": imageHosts,
+ "custom-viz-enabled": customVizEnabled,
+ });
+
+ setupPropertiesEndpoints(settings);
+ setupUpdateSettingsEndpoint({ status: saveStatus });
+ setupSettingsEndpoints(
+ settingDefinitions ?? [
+ createMockSettingDefinition({
+ key: "allowed-iframe-hosts",
+ value: iframeHosts,
+ }),
+ createMockSettingDefinition({
+ key: "csp-img-enabled",
+ value: cspImgEnabled,
+ }),
+ createMockSettingDefinition({
+ key: "csp-img-allowed-hosts",
+ value: imageHosts,
+ }),
+ ],
+ );
+
+ renderWithProviders(<Route path="*" element={<DomainsSettingsPage />} />, {
+ withRouter: true,
+ withUndos: true,
+ initialRoute: "/admin/settings/domains",
+ });
+
+ await screen.findByText("Domains");
+};
+
+const isUnloadGuarded = () => {
+ const event = new Event("beforeunload", { cancelable: true });
+ window.dispatchEvent(event);
+ return event.defaultPrevented;
+};
+
+describe("DomainsSettingsPage", () => {
+ beforeEach(() => {
+ jest.spyOn(domUtils, "reload").mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("should load existing values", async () => {
+ await setup();
+
+ expect(screen.getByLabelText(IFRAME_HOSTS_LABEL)).toHaveValue(
+ "youtube.com",
+ );
+ expect(screen.getByLabelText(IMAGE_HOSTS_LABEL)).toHaveValue(
+ "imgcdn.example.com",
+ );
+ expect(screen.getByRole("switch", { name: CSP_SWITCH_NAME })).toBeChecked();
+ expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();
+ });
+
+ it("should save changed settings and reload without a beforeunload prompt (metabase#80489)", async () => {
+ let wasUnloadGuardedAtReload = true;
+ // Check inside reload() — after it returns the form is already clean.
+ jest.spyOn(domUtils, "reload").mockImplementation(() => {
+ wasUnloadGuardedAtReload = isUnloadGuarded();
+ });
+
+ await setup();
+
+ await userEvent.clear(screen.getByLabelText(IFRAME_HOSTS_LABEL));
+ await userEvent.type(
+ screen.getByLabelText(IFRAME_HOSTS_LABEL),
+ "vimeo.com",
+ );
+
+ const save = screen.getByRole("button", { name: "Save changes" });
+ expect(save).toBeEnabled();
+ expect(domUtils.reload).not.toHaveBeenCalled();
+ expect(isUnloadGuarded()).toBe(true);
+
+ await userEvent.click(save);
+
+ await waitFor(async () => {
+ const puts = await findRequests("PUT");
+ expect(puts).toHaveLength(1);
+ });
+
+ const [{ url, body }] = await findRequests("PUT");
+ expect(url).toMatch(/\/api\/setting$/);
+ expect(body).toEqual({
+ "allowed-iframe-hosts": "vimeo.com",
+ "csp-img-enabled": true,
+ "csp-img-allowed-hosts": "imgcdn.example.com",
+ });
+ expect(domUtils.reload).toHaveBeenCalledTimes(1);
+ expect(wasUnloadGuardedAtReload).toBe(false);
+ });
+
+ it("should persist an empty iframe-hosts field as a single space so the default list does not return (metabase#55373)", async () => {
+ await setup();
+
+ await userEvent.clear(screen.getByLabelText(IFRAME_HOSTS_LABEL));
+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));
+
+ await waitFor(async () => {
+ const puts = await findRequests("PUT");
+ expect(puts).toHaveLength(1);
+ });
+
+ const [{ body }] = await findRequests("PUT");
+ expect(body["allowed-iframe-hosts"]).toBe(" ");
+ });
+
+ it("should show a blank iframe-hosts field when the saved value is a single space", async () => {
+ await setup({ iframeHosts: " " });
+
+ expect(screen.getByLabelText(IFRAME_HOSTS_LABEL)).toHaveValue("");
+ });
+
+ it("should not treat whitespace-only host values as dirty", async () => {
+ await setup({ iframeHosts: " ", imageHosts: "" });
+
+ const save = screen.getByRole("button", { name: "Save changes" });
+ const iframeHosts = screen.getByLabelText(IFRAME_HOSTS_LABEL);
+ const imageHosts = screen.getByLabelText(IMAGE_HOSTS_LABEL);
+
+ expect(iframeHosts).toHaveValue("");
+ expect(save).toBeDisabled();
+
+ await userEvent.type(iframeHosts, " ");
+ expect(save).toBeDisabled();
+
+ await userEvent.clear(iframeHosts);
+ expect(save).toBeDisabled();
+
+ await userEvent.type(iframeHosts, "vimeo.com");
+ expect(save).toBeEnabled();
+
+ await userEvent.clear(iframeHosts);
+ expect(save).toBeDisabled();
+
+ await userEvent.type(imageHosts, " ");
+ expect(save).toBeDisabled();
+ });
+
+ it("should show a form error and not reload when save fails", async () => {
+ jest.spyOn(console, "error").mockImplementation(() => undefined);
+
+ await setup({ saveStatus: 500 });
+
+ await userEvent.type(screen.getByLabelText(IFRAME_HOSTS_LABEL), ".extra");
+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "An error occurred",
+ );
+ expect(screen.getByRole("button", { name: "Failed" })).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Success" }),
+ ).not.toBeInTheDocument();
+ expect(domUtils.reload).not.toHaveBeenCalled();
+ });
+
+ it("should disable the image-hosts field until Restrict image domains is on", async () => {
+ await setup({ cspImgEnabled: false });
+
+ const imageHosts = screen.getByLabelText(IMAGE_HOSTS_LABEL);
+ const save = screen.getByRole("button", { name: "Save changes" });
+ expect(imageHosts).toBeDisabled();
+ expect(save).toBeDisabled();
+
+ await userEvent.click(
+ screen.getByRole("switch", { name: CSP_SWITCH_NAME }),
+ );
+ expect(imageHosts).toBeEnabled();
+ expect(save).toBeEnabled();
+ });
+
+ it("should disable Restrict image domains when custom visualizations are enabled", async () => {
+ await setup({ customVizEnabled: true });
+
+ expect(
+ screen.getByRole("switch", { name: CSP_SWITCH_NAME }),
+ ).toBeDisabled();
+ });
+
+ it("should show the env var message instead of the input when a setting is set from the environment", async () => {
+ await setup({
+ settingDefinitions: [
+ createMockSettingDefinition({
+ key: "allowed-iframe-hosts",
+ is_env_setting: true,
+ env_name: "MB_ALLOWED_IFRAME_HOSTS",
+ }),
+ createMockSettingDefinition({
+ key: "csp-img-enabled",
+ value: true,
+ }),
+ createMockSettingDefinition({
+ key: "csp-img-allowed-hosts",
+ value: "imgcdn.example.com",
+ }),
+ ],
+ });
+
+ expect(
+ await screen.findByText(/This has been set by the/),
+ ).toBeInTheDocument();
+ expect(screen.getByText("MB_ALLOWED_IFRAME_HOSTS")).toBeInTheDocument();
+ expect(screen.queryByLabelText(IFRAME_HOSTS_LABEL)).not.toBeInTheDocument();
+ expect(screen.getByLabelText(IMAGE_HOSTS_LABEL)).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx
index 01d29cefc86..71d94622d17 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx
@@ -1,4 +1,4 @@
-import { jt, t } from "ttag";
+import { t } from "ttag";
import {
SettingsPageWrapper,
@@ -6,12 +6,8 @@ import {
} from "metabase/admin/components/SettingsSection";
import { CollectUserDataInput } from "metabase/admin/settings/components/widgets/UsageTracking/CollectUserDataInput";
import { UpsellDevInstances } from "metabase/admin/upsells";
-import { ExternalLink } from "metabase/common/components/ExternalLink";
-import { Link } from "metabase/common/components/Link";
-import { useDocsUrl, useHasTokenFeature } from "metabase/common/hooks";
+import { useHasTokenFeature } from "metabase/common/hooks";
import { PLUGIN_SEMANTIC_SEARCH } from "metabase/plugins";
-import { useAdminSetting } from "metabase/settings";
-import * as Urls from "metabase/urls";
import { DevInstanceBanner } from "../GeneralSettings/DevInstanceBanner";
import { AdminSettingInput } from "../widgets/AdminSettingInput";
@@ -21,18 +17,9 @@ import { SiteUrlWidget } from "../widgets/SiteUrlWidget";
import { AnonymousTrackingInput } from "../widgets/UsageTracking/AnonymousTrackingInput";
export function GeneralSettingsPage() {
- const { url: iframeDocsUrl } = useDocsUrl("configuring-metabase/settings", {
- anchor: "allowed-domains-for-iframes-in-dashboards",
- });
- const { url: imgDocsUrl } = useDocsUrl("configuring-metabase/settings", {
- anchor: "allowed-domains-for-images",
- });
const hasHostingFeature = useHasTokenFeature("hosting");
const hasAuditAppFeature = useHasTokenFeature("audit_app");
- const customVizAvailable = useHasTokenFeature("custom-viz-available");
const enableAnonymousTracking = !hasHostingFeature;
- const { value: cspImgEnabled } = useAdminSetting("csp-img-enabled");
- const { value: customVizEnabled } = useAdminSetting("custom-viz-enabled");
return (
<SettingsPageWrapper title={t`General`}>
@@ -62,7 +49,7 @@ export function GeneralSettingsPage() {
/>
</SettingsSection>
- <SettingsSection title={t`Tables, X-Rays and domains`}>
+ <SettingsSection title={t`Tables and X-Rays`}>
<AdminSettingInput
name="humanization-strategy"
title={t`Friendly table and field names`}
@@ -81,49 +68,6 @@ export function GeneralSettingsPage() {
title={t`Enable X-Ray features`}
inputType="boolean"
/>
-
- <AdminSettingInput
- name="allowed-iframe-hosts"
- title={t`Allowed domains for iframes in dashboards`}
- description={
- <>
- {jt`You should make sure to trust the sources you allow your users to embed in dashboards. ${<ExternalLink key="docs" href={iframeDocsUrl}>{t`Learn more`}</ExternalLink>}`}
- </>
- }
- inputType="textarea"
- />
-
- <AdminSettingInput
- name="csp-img-enabled"
- title={t`Restrict image domains`}
- description={
- customVizEnabled
- ? jt`Required by Custom Visualizations. Turn off ${(
- <Link key="custom-viz" to={Urls.customViz()} variant="brand">
- {t`Custom Visualizations`}
- </Link>
- )} before disabling this setting.`
- : customVizAvailable
- ? jt`Restrict the browser's Content Security Policy so images can only load from this Metabase instance or the domains you list below. Required to enable Custom Visualizations. ${<ExternalLink key="img-docs" href={imgDocsUrl}>{t`Learn more`}</ExternalLink>}`
- : t`Restrict the browser's Content Security Policy so images can only load from this Metabase instance or the domains you list below.`
- }
- inputType="boolean"
- disabled={Boolean(customVizEnabled)}
- />
-
- <AdminSettingInput
- name="csp-img-allowed-hosts"
- title={t`Allowed domains for images`}
- description={
- cspImgEnabled
- ? customVizAvailable
- ? jt`Domains that images can be loaded from in dashboard text, entity descriptions, and custom visualizations. Leave empty to only allow images hosted by this Metabase instance. ${<ExternalLink key="img-docs" href={imgDocsUrl}>{t`Learn more`}</ExternalLink>}`
- : jt`Domains that images can be loaded from in dashboard text and entity descriptions. Leave empty to only allow images hosted by this Metabase instance. ${<ExternalLink key="img-docs" href={imgDocsUrl}>{t`Learn more`}</ExternalLink>}`
- : t`Turn on the "Restrict image domains" setting above to enforce this allowlist.`
- }
- inputType="textarea"
- disabled={!cspImgEnabled}
- />
</SettingsSection>
{/* On starter plan, both conditions are `false` */}
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx
index 49bcc839e39..8e813cf0e19 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.unit.spec.tsx
@@ -34,29 +34,18 @@ const generalSettings = {
"redirect-all-requests-to-https": false,
"humanization-strategy": "simple",
"enable-xrays": false,
- "allowed-iframe-hosts": "https://cooldashboards.limo",
- "csp-img-enabled": true,
- "csp-img-allowed-hosts": "https://imgcdn.example.com",
"search-engine": "appdb",
- "custom-viz-enabled": false,
} as const;
const setup = async ({
isCloudPlan,
hasAuditApp,
- cspImgEnabled,
- customVizEnabled,
}: {
isCloudPlan?: boolean;
hasAuditApp?: boolean;
- cspImgEnabled?: boolean;
- customVizEnabled?: boolean;
} = {}) => {
const settings = createMockSettings({
...generalSettings,
- "csp-img-enabled": cspImgEnabled ?? generalSettings["csp-img-enabled"],
- "custom-viz-enabled":
- customVizEnabled ?? generalSettings["custom-viz-enabled"],
"token-features": createMockTokenFeatures({
hosting: isCloudPlan ?? false,
audit_app: hasAuditApp ?? true,
@@ -118,9 +107,6 @@ describe("GeneralSettingsPage", () => {
"Collect user data to display in usage analytics",
"Friendly table and field names",
"Enable X-Ray features",
- "Allowed domains for iframes in dashboards",
- "Restrict image domains",
- "Allowed domains for images",
].forEach((text) => {
expect(screen.getByText(text)).toBeInTheDocument();
});
@@ -194,45 +180,6 @@ describe("GeneralSettingsPage", () => {
});
});
- it("should load and persist the allowed image domains setting", async () => {
- await setup();
-
- const imgInput = await screen.findByLabelText("Allowed domains for images");
- await userEvent.clear(imgInput);
- await userEvent.type(imgInput, "https://images.example.org");
- await userEvent.tab();
-
- await waitFor(async () => {
- const puts = await findRequests("PUT");
- expect(
- puts.some((req) =>
- req.url.includes("/api/setting/csp-img-allowed-hosts"),
- ),
- ).toBe(true);
- });
-
- const imgPut = (await findRequests("PUT")).find((req) =>
- req.url.includes("/api/setting/csp-img-allowed-hosts"),
- );
- expect(imgPut?.body).toEqual({ value: "https://images.example.org" });
- });
-
- it("should disable the allowed-hosts textarea when csp-img-enabled is off", async () => {
- await setup({ cspImgEnabled: false });
-
- const imgInput = await screen.findByLabelText("Allowed domains for images");
- expect(imgInput).toBeDisabled();
- });
-
- it("should disable the csp-img-enabled toggle when custom-viz is enabled", async () => {
- await setup({ cspImgEnabled: true, customVizEnabled: true });
-
- const toggle = await screen.findByRole("switch", {
- name: /Restrict image domains/i,
- });
- expect(toggle).toBeDisabled();
- });
-
it("should show Anonymous Tracking input for non-cloud plans", async () => {
await setup({ isCloudPlan: false });
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/domainSettingsUtils.ts b/frontend/src/metabase/admin/settings/components/SettingsPages/domainSettingsUtils.ts
new file mode 100644
index 00000000000..ffc91770b76
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/domainSettingsUtils.ts
@@ -0,0 +1,37 @@
+import _ from "underscore";
+
+import type { EnterpriseSettings } from "metabase-types/api";
+
+export type DomainsSettings = Pick<
+ EnterpriseSettings,
+ "allowed-iframe-hosts" | "csp-img-enabled" | "csp-img-allowed-hosts"
+>;
+
+// BE settings code does not support empty strings, so we use " " as a sentinel for ""
+const EMPTY_ALLOWED_IFRAME_HOSTS = " ";
+
+export function isDomainSettingsDirty(
+ initialValues: DomainsSettings,
+ values: DomainsSettings,
+) {
+ return !_.isEqual(
+ normalizeDomainSettings(initialValues),
+ normalizeDomainSettings(values),
+ );
+}
+
+export function normalizeDomainSettings(values: DomainsSettings) {
+ return {
+ "allowed-iframe-hosts": isEmptyString(values["allowed-iframe-hosts"])
+ ? EMPTY_ALLOWED_IFRAME_HOSTS
+ : values["allowed-iframe-hosts"],
+ "csp-img-enabled": values["csp-img-enabled"],
+ "csp-img-allowed-hosts": isEmptyString(values["csp-img-allowed-hosts"])
+ ? ""
+ : values["csp-img-allowed-hosts"],
+ };
+}
+
+export function isEmptyString(value?: string | null) {
+ return value == null || value.trim() === "";
+}
diff --git a/frontend/src/metabase/admin/settingsRoutes.tsx b/frontend/src/metabase/admin/settingsRoutes.tsx
index 909265b413c..f5d0038fb6b 100644
--- a/frontend/src/metabase/admin/settingsRoutes.tsx
+++ b/frontend/src/metabase/admin/settingsRoutes.tsx
@@ -89,6 +89,11 @@ const ldapAuth = () =>
/* webpackChunkName: "admin-settings" */ "./settings/components/SettingsLdapForm"
).then(({ SettingsLdapForm }) => ({ Component: SettingsLdapForm }));
+const domainsSettings = () =>
+ import(
+ /* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/DomainsSettingsPage"
+ ).then(({ DomainsSettingsPage }) => ({ Component: DomainsSettingsPage }));
+
const remoteSyncSettings = () =>
import(
/* webpackChunkName: "admin-settings" */ "./settings/components/SettingsPages/RemoteSyncSettingsPage"
@@ -219,6 +224,7 @@ export const getSettingsRoutes = (
path="authentication/oidc"
lazy={PLUGIN_AUTH_PROVIDERS.settingsOIDCForm}
/>
+ <Route path="domains" lazy={domainsSettings} />
<Route path="remote-sync" lazy={remoteSyncSettings} />
<Route path="maps" lazy={mapsSettings} />
<Route path="localization" lazy={localizationSettings} />
diff --git a/frontend/src/metabase/dashboard/visualizations/IFrameViz/IFrameViz.tsx b/frontend/src/metabase/dashboard/visualizations/IFrameViz/IFrameViz.tsx
index 3fcf2c4488e..5f4278b646d 100644
--- a/frontend/src/metabase/dashboard/visualizations/IFrameViz/IFrameViz.tsx
+++ b/frontend/src/metabase/dashboard/visualizations/IFrameViz/IFrameViz.tsx
@@ -11,6 +11,7 @@ import { fillParametersInText } from "metabase/dashboard/visualizations/paramete
import { useSelector } from "metabase/redux";
import { useSetting } from "metabase/settings";
import { Box, Button, Group, Icon, Stack, Text } from "metabase/ui";
+import * as Urls from "metabase/urls";
import {
getAllowedIframeAttributes,
isAllowedIframeUrl,
@@ -177,7 +178,7 @@ function ForbiddenDomainError({ url }: { url: string }) {
const renderMessage = () => {
if (isAdmin) {
- return jt`If you’re sure you trust this domain, you can add it to your ${<Link key="link" className={CS.link} to="/admin/settings/general#allowed-iframe-hosts" target="_blank">{t`allowed domains list`}</Link>} in admin settings.`;
+ return jt`If you’re sure you trust this domain, you can add it to your ${<Link key="link" className={CS.link} to={`${Urls.domainsSettings()}#allowed-iframe-hosts`} target="_blank">{t`allowed domains list`}</Link>} in admin settings.`;
}
return showMetabaseLinks
? jt`If you’re sure you trust this domain, you can ask an admin to add it to the ${<ExternalLink key="link" className={CS.link} href={docsUrl}>{t`allowed domains list`}</ExternalLink>}.`
diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx
index 3da973a30e3..d82917f34e5 100644
--- a/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx
@@ -148,6 +148,11 @@ describe("PaletteResults", () => {
expect(await screen.findByText("Settings - Email")).toBeInTheDocument();
});
+ it("should provide a link to Domains settings for admins", async () => {
+ setup({ query: "doma", isAdmin: true });
+ expect(await screen.findByText("Settings - Domains")).toBeInTheDocument();
+ });
+
it("should not provide links to settings pages for non-admins", async () => {
setup({ query: "setu", isAdmin: false });
expect(
diff --git a/frontend/src/metabase/palette/constants.ts b/frontend/src/metabase/palette/constants.ts
index 132cf3e9869..4614e938faf 100644
--- a/frontend/src/metabase/palette/constants.ts
+++ b/frontend/src/metabase/palette/constants.ts
@@ -79,6 +79,9 @@ export const getAdminSettingsSections = (
name: t`Api keys`,
adminOnly: true,
},
+ domains: {
+ name: t`Domains`,
+ },
maps: {
name: t`Maps`,
},
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
index ac1761918b4..84d39b43e52 100644
--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
@@ -166,6 +166,7 @@ import lock_filled_component from "./lock_filled.svg?component";
import mail_component from "./mail.svg?component";
import mail_at_component from "./mail_at.svg?component";
import mail_filled_component from "./mail_filled.svg?component";
+import map_component from "./map.svg?component";
import mcp_component from "./mcp.svg?component";
import medallion_component from "./medallion.svg?component";
import message_circle_component from "./message_circle.svg?component";
@@ -467,6 +468,7 @@ export const Icons: Record<IconName, React.VFC> = {
mail: mail_component,
mail_at: mail_at_component,
mail_filled: mail_filled_component,
+ map: map_component,
mcp: mcp_component,
medallion: medallion_component,
message_circle: message_circle_component,
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/map.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/map.svg
new file mode 100644
index 00000000000..b44f642fced
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/map.svg
@@ -0,0 +1,3 @@
+<svg viewBox="0 0 16 16" fill="currentcolor" xmlns="http://www.w3.org/2000/svg">
+ <path d="M6 1.407c.323 0 .642.075.932.22l2.807 1.404.063.027a.584.584 0 0 0 .459-.027l2.44-1.22a1.417 1.417 0 0 1 2.049 1.268v8.51l-.014.196a1.417 1.417 0 0 1-.6.97l-.17.1-3.034 1.518a2.084 2.084 0 0 1-1.864 0L6.261 12.97a.584.584 0 0 0-.46-.028l-.062.028-2.44 1.22a1.417 1.417 0 0 1-2.049-1.271V4.41c0-.263.074-.52.212-.744l.114-.16c.125-.15.28-.274.457-.362l3.035-1.518.223-.096c.227-.082.467-.124.709-.124zm.625 10.1c.105.033.208.072.307.12l2.443 1.222V4.493a2.079 2.079 0 0 1-.307-.12L6.625 3.15v8.357zm4.307-7.134c-.099.05-.202.087-.307.12v8.356l2.625-1.313V3.213l-2.318 1.16zm-8.182.09v8.324l2.318-1.16c.1-.048.202-.087.307-.12V3.15L2.75 4.463z" />
+</svg>
diff --git a/frontend/src/metabase/urls/admin.ts b/frontend/src/metabase/urls/admin.ts
index cac6842e06e..91f16a03e88 100644
--- a/frontend/src/metabase/urls/admin.ts
+++ b/frontend/src/metabase/urls/admin.ts
@@ -140,6 +140,10 @@ export function generalSettings() {
return "/admin/settings/general";
}
+export function domainsSettings() {
+ return "/admin/settings/domains";
+}
+
export function uploadsSettings() {
return "/admin/settings/uploads";
}
diff --git a/src/metabase/server/settings.clj b/src/metabase/server/settings.clj
index 258870493ed..dedac4e50b9 100644
--- a/src/metabase/server/settings.clj
+++ b/src/metabase/server/settings.clj
@@ -34,7 +34,7 @@ twitter.com,
x.com")
(defsetting allowed-iframe-hosts
- (deferred-tru "Allowed iframe hosts")
+ (deferred-tru "Allowed iframe hosts. Includes a list of popular hosts by default; set to '' '' to disable the default list.")
:encryption :when-encryption-key-set
:default default-allowed-iframe-hosts
:audit :getter