The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
restrict CSP for img (#74347)
Jakub Chodorowicz102682e36f06
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 6b5653e7734..7b526fdc871 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1977,6 +1977,7 @@tracingusersutil+ enterprise/custom-viz-pluginenterprise/sso}:model-imports #{:model/Session}}@@ -2895,7 +2896,8 @@enterprise/custom-viz-plugin{:team "Gadget":api #{metabase-enterprise.custom-viz-plugin.api- metabase-enterprise.custom-viz-plugin.init}+ metabase-enterprise.custom-viz-plugin.init+ metabase-enterprise.custom-viz-plugin.settings}:uses #{apiconfigeventsdiff --git a/docs/configuring-metabase/config-template.md b/docs/configuring-metabase/config-template.mdindex 0332a34f567..cf7ef1bf5b9 100644--- a/docs/configuring-metabase/config-template.md+++ b/docs/configuring-metabase/config-template.md@@ -112,6 +112,8 @@ config:can-run-adhoc-query-check-threshold: 250check-for-updates: trueconfig-from-file-sync-databases: true+ csp-img-allowed-hosts: ''+ csp-img-enabled: falsecsv-field-separator: ','custom-formatting: {}custom-geojson: nulldiff --git a/docs/configuring-metabase/environment-variables.md b/docs/configuring-metabase/environment-variables.mdindex b0911e2fd58..009d303d93e 100644--- a/docs/configuring-metabase/environment-variables.md+++ b/docs/configuring-metabase/environment-variables.md@@ -128,6 +128,24 @@ x.com`Allowed iframe hosts.+### `MB_CSP_IMG_ENABLED`++- Type: boolean+- Default: `false`+- [Exported as](../installation-and-operation/serialization.md): `csp-img-enabled`.+- [Configuration file name](./config-file.md): `csp-img-enabled`++When on, the browser Content Security Policy restricts `img-src` so images can only load from this Metabase instance and the domains listed in `MB_CSP_IMG_ALLOWED_HOSTS`. Must be turned on to enable Custom Visualizations.++### `MB_CSP_IMG_ALLOWED_HOSTS`++- Type: string+- Default: `""`+- [Exported as](../installation-and-operation/serialization.md): `csp-img-allowed-hosts`.+- [Configuration file name](./config-file.md): `csp-img-allowed-hosts`++Comma-separated list of domains that images can load from in dashboard text cards, entity descriptions, and custom visualizations when `MB_CSP_IMG_ENABLED` is on. Empty by default, which restricts images to those hosted by your Metabase instance. See [Allowed domains for images](./settings.md#allowed-domains-for-images).+### `MB_ANALYTICS_PII_RETENTION_ENABLED`> Only available on Metabase [Pro](https://www.metabase.com/product/pro) and [Enterprise](https://www.metabase.com/product/enterprise) plans.diff --git a/docs/configuring-metabase/settings.md b/docs/configuring-metabase/settings.mdindex a364f1fb96a..3c065a5a3b4 100644--- a/docs/configuring-metabase/settings.md+++ b/docs/configuring-metabase/settings.md@@ -84,3 +84,17 @@ docs.example.comMetabase would only allow iframes from `data.example.com` and `docs.example.com`. Metabase would block iframes from all other domains, including iframes from `example.com` and its other subdomains.See [iframes in dashboards](../dashboards/introduction.md#iframe-cards).++## Restrict image domains++When on, Metabase restricts the browser's Content Security Policy so images can only load from this Metabase instance or the domains listed in [Allowed domains for images](#allowed-domains-for-images).++By default, images from any domain are allowed.++## Allowed domains for images++When the [Restrict image domains](#restrict-image-domains) setting is on, Metabase will only allow images served from this Metabase instance, and any domains listed here.++Leave this input empty to only allow images hosted by your Metabase instance.++Add multiple domains separated by a comma. Domains follow the same matching rules as [Allowed domains for iframes in dashboards](#allowed-domains-for-iframes-in-dashboards): listing a domain like `example.com` also allows its subdomains, while listing a subdomain like `images.example.com` allows only that subdomain.diff --git a/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts b/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.tsindex 4dcbd77efd8..33a85f89948 100644--- a/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts+++ b/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts@@ -77,13 +77,28 @@ describe("admin > custom visualizations", () => {H.visitCustomVizSettings();+ cy.log(+ "Enabling custom viz is blocked until the image CSP setting is on",+ );+ H.main()+ .findByRole("button", { name: /Enable custom visualizations/ })+ .should("be.disabled");+ H.main()+ .findByText(/Turn on "Restrict image domains"/)+ .should("be.visible");++ cy.log("Turn on the image CSP setting, then custom viz can be enabled");+ H.updateSetting("csp-img-enabled", true);+ cy.reload();+H.main().findByRole("button", { name: /Enable custom visualizations/ })- .should("be.visible")+ .should("be.enabled").click();H.getAddVisualizationLink().should("be.visible");+ cy.log("Deactivate custom visualizations");H.main().findByRole("button", { name: /More options/ }).click();@@ -124,6 +139,7 @@ describe("admin > custom visualizations", () => {});H.activateToken("bleeding-edge");+ H.updateSetting("csp-img-enabled", true);H.updateSetting("custom-viz-enabled", true);H.visitCustomVizSettings();H.getAddVisualizationLink().click();@@ -167,6 +183,7 @@ describe("admin > custom visualizations", () => {describe("admin settings page", () => {beforeEach(() => {H.activateToken("bleeding-edge");+ H.updateSetting("csp-img-enabled", true);H.updateSetting("custom-viz-enabled", true);});@@ -518,6 +535,7 @@ describe("admin > custom visualizations", () => {describe("using a plugin — question", () => {beforeEach(() => {H.activateToken("bleeding-edge");+ H.updateSetting("csp-img-enabled", true);H.updateSetting("custom-viz-enabled", true);H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);@@ -775,6 +793,7 @@ describe("admin > custom visualizations", () => {describe("using a plugin — dashboard", () => {beforeEach(() => {H.activateToken("bleeding-edge");+ H.updateSetting("csp-img-enabled", true);H.updateSetting("custom-viz-enabled", true);H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);});@@ -1044,6 +1063,7 @@ describe("admin > custom visualizations", () => {beforeEach(() => {H.activateToken("bleeding-edge");+ H.updateSetting("csp-img-enabled", true);H.updateSetting("custom-viz-enabled", true);H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);@@ -1174,6 +1194,7 @@ describe("admin > custom visualizations", () => {beforeEach(() => {H.activateToken("bleeding-edge");+ H.updateSetting("csp-img-enabled", true);H.updateSetting("custom-viz-enabled", true);H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);@@ -1396,6 +1417,7 @@ describe("admin > custom visualizations", () => {H.restore("postgres-writable");cy.signInAsAdmin();H.activateToken("bleeding-edge");+ H.updateSetting("csp-img-enabled", true);H.updateSetting("custom-viz-enabled", true);});@@ -1577,6 +1599,7 @@ describe("sandbox", () => {H.restore("postgres-writable");cy.signInAsAdmin();H.activateToken("bleeding-edge");+ H.updateSetting("csp-img-enabled", true);H.updateSetting("custom-viz-enabled", true);H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ);H.createQuestion(@@ -2505,10 +2528,6 @@ describe("sandbox", () => {});it("blocks forbidden apis in widget settings", () => {- H.restore("postgres-writable");- H.activateToken("bleeding-edge");- cy.signInAsAdmin();- H.updateSetting("custom-viz-enabled", true);H.addCustomVizPlugin(H.CUSTOM_VIZ_FIXTURE_TGZ_3_SECURITY);H.createQuestion(diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/settings.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/settings.cljindex 6b497efaa2c..95a099b0221 100644--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/settings.clj@@ -1,8 +1,9 @@(ns metabase-enterprise.custom-viz-plugin.settings(:require[metabase.premium-features.core :refer [defenterprise]]- [metabase.settings.core :refer [defsetting]]- [metabase.util.i18n :refer [deferred-tru]]))+ [metabase.server.settings :as server.settings]+ [metabase.settings.core :as setting :refer [defsetting]]+ [metabase.util.i18n :refer [deferred-tru tru]]))(defsetting custom-viz-plugin-dev-mode-enabled(deferred-tru "Whether custom visualization plugin dev mode is enabled. When false, the dev endpoints are disabled.")@@ -20,7 +21,16 @@:feature :custom-viz:visibility :admin:export? true- :audit :getter)+ :audit :getter+ :setter (fn [new-value]+ (let [enabling? (if (string? new-value)+ (setting/string->boolean new-value)+ new-value)]+ (when (and enabling?+ (not (server.settings/csp-img-enabled)))+ (throw (ex-info (tru "Turn on the image CSP setting before enabling Custom Visualizations.")+ {:status-code 400})))+ (setting/set-value-of-type! :boolean :custom-viz-enabled new-value))))(defenterprise enable-custom-viz?"Enterprise implementation: custom visualizations are enabled when the admin has opted in via thediff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.cljindex 14ecd4d0eec..0e138b35a54 100644--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj@@ -124,7 +124,8 @@:schema-viewer false:workspaces false:writable_connection true}- (mt/with-temporary-setting-values [custom-viz-enabled true]+ (mt/with-temporary-setting-values [csp-img-enabled true+ custom-viz-enabled true](:token-features (mt/user-http-request :crowberto :get 200 "session/properties")))))))(deftest security-center-token-feature-testdiff --git a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.cljindex 0e2a5a50746..2ab96de2a23 100644--- a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj@@ -18,7 +18,8 @@(use-fixtures :each(fn [thunk]- (mt/with-temporary-setting-values [custom-viz-enabled true]+ (mt/with-temporary-setting-values [csp-img-enabled true+ custom-viz-enabled true](thunk))))(defmacro ^:private with-dev-mode-enabled [& body]diff --git a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cache_test.clj b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cache_test.cljindex ad67a065c8a..8eae07e1179 100644--- a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cache_test.clj+++ b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cache_test.clj@@ -13,7 +13,8 @@(use-fixtures :each(fn [thunk]- (mt/with-temporary-setting-values [custom-viz-enabled true]+ (mt/with-temporary-setting-values [csp-img-enabled true+ custom-viz-enabled true](thunk))));;; ------------------------------------------------ validate-bundle! ------------------------------------------------diff --git a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cross_setting_test.clj b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cross_setting_test.cljnew file mode 100644index 00000000000..c0fdd168de1--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/cross_setting_test.clj@@ -0,0 +1,52 @@+(ns metabase-enterprise.custom-viz-plugin.cross-setting-test+ "Cross-setting constraints between `custom-viz-enabled` (enterprise) and+ `csp-img-enabled` (OSS)."+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.custom-viz-plugin.settings :as custom-viz.settings]+ [metabase.premium-features.test-util :as tu]+ [metabase.server.settings :as server.settings]+ [metabase.test :as mt]))++(set! *warn-on-reflection* true)++(deftest custom-viz-enabled-requires-csp-img-enabled-test+ (testing "Enabling custom-viz-enabled while csp-img-enabled is false is rejected"+ (tu/with-premium-features #{:custom-viz}+ (mt/with-temporary-setting-values [csp-img-enabled false+ custom-viz-enabled false]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Turn on the image CSP setting"+ (custom-viz.settings/custom-viz-enabled! true)))+ (is (false? (custom-viz.settings/custom-viz-enabled))))))+ (testing "Enabling custom-viz-enabled succeeds when csp-img-enabled is true"+ (tu/with-premium-features #{:custom-viz}+ (mt/with-temporary-setting-values [csp-img-enabled true+ custom-viz-enabled false]+ (custom-viz.settings/custom-viz-enabled! true)+ (is (true? (custom-viz.settings/custom-viz-enabled)))+ (custom-viz.settings/custom-viz-enabled! false))))+ (testing "Disabling custom-viz-enabled is always allowed"+ (tu/with-premium-features #{:custom-viz}+ (mt/with-temporary-setting-values [csp-img-enabled false+ custom-viz-enabled false]+ (custom-viz.settings/custom-viz-enabled! false)+ (is (false? (custom-viz.settings/custom-viz-enabled)))))))++(deftest csp-img-enabled-locked-while-custom-viz-on-test+ (testing "Cannot disable csp-img-enabled while custom-viz-enabled is true"+ (tu/with-premium-features #{:custom-viz}+ (mt/with-temporary-setting-values [csp-img-enabled true+ custom-viz-enabled true]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Cannot disable the image CSP setting"+ (server.settings/csp-img-enabled! false)))+ (is (true? (server.settings/csp-img-enabled))))))+ (testing "Can disable csp-img-enabled once custom-viz-enabled is off"+ (tu/with-premium-features #{:custom-viz}+ (mt/with-temporary-setting-values [csp-img-enabled true+ custom-viz-enabled false]+ (server.settings/csp-img-enabled! false)+ (is (false? (server.settings/csp-img-enabled)))))))diff --git a/enterprise/backend/test/metabase_enterprise/premium_features/settings_test.clj b/enterprise/backend/test/metabase_enterprise/premium_features/settings_test.cljindex 95b736f1567..d40caeac066 100644--- a/enterprise/backend/test/metabase_enterprise/premium_features/settings_test.clj+++ b/enterprise/backend/test/metabase_enterprise/premium_features/settings_test.clj@@ -12,11 +12,13 @@(is (false? (premium-features/enable-custom-viz?)))))(testing "enable-custom-viz? is true when admin opts in via the setting"(tu/with-premium-features #{:custom-viz}- (mt/with-temporary-setting-values [custom-viz-enabled true]+ (mt/with-temporary-setting-values [csp-img-enabled true+ custom-viz-enabled true](is (true? (premium-features/enable-custom-viz?))))))(testing "enable-custom-viz? is false without the :custom-viz token feature, even when the setting is on"(tu/with-premium-features #{}- (mt/with-temporary-setting-values [custom-viz-enabled true]+ (mt/with-temporary-setting-values [csp-img-enabled true+ custom-viz-enabled true](is (false? (premium-features/enable-custom-viz?))))))(testing "MB_CUSTOM_VIZ_ENABLED env var can toggle the setting"(tu/with-premium-features #{:custom-viz}diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.tsindex f69e6182cbb..3bbf32c68f2 100644--- a/frontend/src/metabase-types/api/mocks/settings.ts+++ b/frontend/src/metabase-types/api/mocks/settings.ts@@ -175,6 +175,8 @@ export const createMockSettings = ("custom-viz-enabled": false,"custom-viz-plugin-dev-mode-enabled": false,"allowed-iframe-hosts": "*",+ "csp-img-allowed-hosts": "",+ "csp-img-enabled": false,"anon-tracking-enabled": false,"metaplow-tracking-enabled": false,"metaplow-url": null,diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.tsindex 14408cc0323..ed9ab3b3d49 100644--- a/frontend/src/metabase-types/api/settings.ts+++ b/frontend/src/metabase-types/api/settings.ts@@ -548,6 +548,8 @@ type PrivilegedSettings = AdminSettings & SettingsManagerSettings;interface PublicSettings {"allowed-iframe-hosts": string;+ "csp-img-allowed-hosts": string;+ "csp-img-enabled": boolean;"ai-features-enabled?": boolean;"agent-api-enabled?": boolean;"analytics-uuid": string;diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/CustomVisualizationsSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/CustomVisualizationsSettingsPage.tsxindex 7a697b9b11c..1a076062105 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/CustomVisualizationsSettingsPage.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/CustomVisualizationsSettingsPage.tsx@@ -1,12 +1,14 @@-import { t } from "ttag";+import { jt, t } from "ttag";import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";import { UpsellCustomViz } from "metabase/admin/upsells";import { useAdminSetting } from "metabase/api/utils";+import { Link } from "metabase/common/components/Link";import { useHasTokenFeature } from "metabase/common/hooks";import { useMetadataToasts } from "metabase/metadata/hooks";import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";import {+ Alert,Button,Card,Group,@@ -17,6 +19,7 @@ import {Text,Title,} from "metabase/ui";+import * as Urls from "metabase/urls";import type { IconName } from "metabase-types/api";export function CustomVisualizationsManagePage() {const customVizLoaded = useHasTokenFeature("custom-viz");@@ -80,9 +83,11 @@ export function CustomVisualizationsDevelopmentPage() {}const CUSTOM_VIZ_ENABLED_SETTING = "custom-viz-enabled";+const CSP_IMG_ENABLED_SETTING = "csp-img-enabled";function CustomVizEmptyState() {const { updateSetting } = useAdminSetting(CUSTOM_VIZ_ENABLED_SETTING);+ const { value: cspImgEnabled } = useAdminSetting(CSP_IMG_ENABLED_SETTING);const { sendErrorToast } = useMetadataToasts();const handleEnable = async () => {@@ -109,15 +114,33 @@ function CustomVizEmptyState() {<Text c="text-secondary" lh="1.25rem">{t`Show your data the way you need to with custom visualizations. Use the custom viz SDK to build visualization plugins and upload them here as packaged bundles (.tgz).`}</Text>- <Text fw="bold" lh="1.25rem">+ <Alert title={t`Security risk`} icon={<Icon name="warning" />}>{t`Be aware that custom visualizations can execute arbitrary code, and should only be added from trusted sources.`}- </Text>+ </Alert>++ {!cspImgEnabled && (+ <Text c="text-secondary" lh="1.25rem">+ {jt`Turn on "Restrict image domains" in ${(+ <Link+ key="link"+ to={Urls.generalSettings()}+ variant="brand"+ >+ {t`General settings`}+ </Link>+ )} before enabling custom visualizations.`}+ </Text>+ )}</Stack>- <Group gap="sm">- <Button variant="filled" onClick={handleEnable}>+ <Stack align="flex-start">+ <Button+ variant="filled"+ onClick={handleEnable}+ disabled={!cspImgEnabled}+ >{t`Enable custom visualizations`}</Button>- </Group>+ </Stack></Stack><SimpleGrid cols={2} spacing="sm"><FeatureCarddiff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsxindex 120286e5b06..12160c1aded 100644--- a/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/GeneralSettingsPage.tsx@@ -6,9 +6,12 @@ import {} from "metabase/admin/components/SettingsSection";import { CollectUserDataInput } from "metabase/admin/settings/components/widgets/UsageTracking/CollectUserDataInput";import { UpsellDevInstances } from "metabase/admin/upsells";+import { useAdminSetting } from "metabase/api/utils";import { ExternalLink } from "metabase/common/components/ExternalLink";+import { Link } from "metabase/common/components/Link";import { useDocsUrl, useHasTokenFeature } from "metabase/common/hooks";import { PLUGIN_SEMANTIC_SEARCH } from "metabase/plugins";+import * as Urls from "metabase/urls";import { DevInstanceBanner } from "../GeneralSettings/DevInstanceBanner";import { AdminSettingInput } from "../widgets/AdminSettingInput";@@ -21,9 +24,15 @@ 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`}>@@ -83,6 +92,38 @@ export function GeneralSettingsPage() {}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.tsxindex b4850fd0837..25a12a9745e 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@@ -1,5 +1,6 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";+import { Route } from "react-router";import {findRequests,@@ -34,15 +35,28 @@ const generalSettings = {"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,-}: { isCloudPlan?: boolean; hasAuditApp?: boolean } = {}) => {+ 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,@@ -74,10 +88,16 @@ const setup = async ({});renderWithProviders(- <>- <GeneralSettingsPage />- <UndoListing />- </>,+ <Route+ path="*"+ component={() => (+ <>+ <GeneralSettingsPage />+ <UndoListing />+ </>+ )}+ />,+ { withRouter: true, initialRoute: "/admin/settings/general" },);await screen.findByText("Site name");@@ -98,6 +118,8 @@ describe("GeneralSettingsPage", () => {"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();});@@ -168,6 +190,45 @@ 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/urls/admin.ts b/frontend/src/metabase/urls/admin.tsindex 7db51e78e75..9be2668cbd4 100644--- a/frontend/src/metabase/urls/admin.ts+++ b/frontend/src/metabase/urls/admin.ts@@ -139,6 +139,10 @@ export function dataModelSegmentRevisions(segmentId: SegmentId) {return `${dataModelSegment(segmentId)}/revisions`;}+export function generalSettings() {+ return "/admin/settings/general";+}+export function uploadsSettings() {return "/admin/settings/uploads";}diff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.cljindex 2ba35e205de..6eedd6b95b8 100644--- a/src/metabase/server/middleware/security.clj+++ b/src/metabase/server/middleware/security.clj@@ -17,6 +17,7 @@[metabase.util.malli :as mu][ring.util.codec :refer [base64-encode]])(:import+ (java.net URI)(java.security MessageDigest SecureRandom)))(set! *warn-on-reflection* true)@@ -115,17 +116,63 @@"https://www.metabase.com/""https://metabase.com/"])-(defn- parse-allowed-iframe-hosts*+(def ^:private always-allowed-resource-hosts+ "Implicitly-allowed `img-src`/`font-src` hosts: our own origin and `data:` URIs."+ ["'self'" "data:"])++(defn- parse-hosts-string+ "Split a comma/whitespace-separated `hosts-string` into individual hosts, adding wildcard prefixes as needed."[hosts-string]- (->> (str/split hosts-string #"[ ,\s\r\n]+")+ (->> (str/split (or hosts-string "") #"[ ,\s\r\n]+")(remove str/blank?)- (mapcat add-wildcard-entries)- (into always-allowed-iframe-hosts)))+ (mapcat add-wildcard-entries)))++(defn- parse-allowed-iframe-hosts*+ [hosts-string]+ (into always-allowed-iframe-hosts (parse-hosts-string hosts-string)))(def ^{:doc "Parse the string of allowed iframe hosts, adding wildcard prefixes as needed."}parse-allowed-iframe-hosts(memoize parse-allowed-iframe-hosts*))+(defn- parse-allowed-resource-hosts*+ [hosts-string]+ (into always-allowed-resource-hosts (parse-hosts-string hosts-string)))++(def ^{:doc "Parse a string of allowed resource hosts (e.g. for `img-src`), adding wildcard prefixes as needed."}+ parse-allowed-resource-hosts+ (memoize parse-allowed-resource-hosts*))++(defn- bracket-ipv6-host+ "`URI#getHost` returns IPv6 literals unbracketed, but CSP origins require the brackets."+ [host]+ (if (and (str/includes? host ":") (not (str/starts-with? host "[")))+ (str "[" host "]")+ host))++(defn- font-file-src->origin+ "Extract the `scheme://host[:port]` origin from a custom font file `src` URL, or nil if it is+ blank, relative, or unparseable."+ [src]+ (when (and (string? src) (not (str/blank? src)))+ (try+ (let [uri (URI. src)+ scheme (.getScheme uri)+ host (some-> uri .getHost bracket-ipv6-host)+ port (.getPort uri)]+ (when (and scheme host)+ (str scheme "://" host (when (pos? port) (str ":" port)))))+ (catch Exception _ nil))))++(defn- application-font-files->hosts+ "Origins of any custom font files configured via the `application-font-files` setting, so that+ `font-src` allows the fonts an admin has explicitly opted into without a separate setting."+ []+ (->> (setting/get-value-of-type :json :application-font-files)+ (keep (comp font-file-src->origin :src))+ distinct+ vec))+(def ^:private frontend-dev-port (or (env/env :mb-frontend-dev-port) "8080"))(def ^:private frontend-address (str "http://localhost:" frontend-dev-port))(def ^:private cljs-dev-port (or (env/env :mb-cljs-dev-port) "9630"))@@ -175,9 +222,13 @@"https://accounts.google.com"]:style-src-attr ["'self'"]:frame-src (parse-allowed-iframe-hosts (server.settings/allowed-iframe-hosts))- :font-src ["*"]- :img-src ["*"- "'self' data:"]+ :font-src (into (cond-> always-allowed-resource-hosts+ config/is-dev? (conj frontend-address))+ (application-font-files->hosts))+ :img-src (if (server.settings/csp-img-enabled)+ (cond-> (parse-allowed-resource-hosts (server.settings/csp-img-allowed-hosts))+ config/is-dev? (conj frontend-address))+ (into ["*"] always-allowed-resource-hosts)):connect-src ["'self'";; Google Identity Services"https://accounts.google.com"diff --git a/src/metabase/server/settings.clj b/src/metabase/server/settings.cljindex b5ee3c3558e..bab0d65b9b7 100644--- a/src/metabase/server/settings.clj+++ b/src/metabase/server/settings.clj@@ -3,6 +3,7 @@off a separate `response` module."(:require[clojure.string :as str]+ [metabase.config.core :as config][metabase.settings.core :as setting :refer [defsetting]][metabase.system.core :as system][metabase.util.i18n :refer [deferred-tru tru]]@@ -40,6 +41,33 @@ x.com"):visibility :public:export? true)+(defsetting csp-img-allowed-hosts+ (deferred-tru "Comma-separated list of hosts that images may load from (e.g. in dashboard text, entity descriptions, and custom visualizations) when `csp-img-enabled` is on. Empty by default, which restricts images to this Metabase instance.")+ :encryption :no+ :default ""+ :audit :getter+ :visibility :public+ :export? true)++(defsetting csp-img-enabled+ (deferred-tru "Restrict the browser Content Security Policy so images can only load from this Metabase instance or the hosts listed in `csp-img-allowed-hosts`. Must be on to enable Custom Visualizations.")+ :type :boolean+ :default false+ :visibility :public+ :audit :getter+ :export? true+ :setter (fn [new-value]+ (let [disabling? (not (cond-> new-value (string? new-value) setting/string->boolean))]+ (when (and disabling?+ config/ee-available?+ (when-let [custom-viz-enabled?+ (requiring-resolve+ 'metabase-enterprise.custom-viz-plugin.settings/custom-viz-enabled)]+ (custom-viz-enabled?)))+ (throw (ex-info (tru "Cannot disable the image CSP setting while Custom Visualizations are enabled.")+ {:status-code 400})))+ (setting/set-value-of-type! :boolean :csp-img-enabled new-value))))+(defsetting redirect-all-requests-to-https(deferred-tru "Force all traffic to use HTTPS via a redirect, if the site URL is HTTPS"):visibility :publicdiff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.cljindex 892f830545c..2d24f5d963c 100644--- a/test/metabase/server/middleware/security_test.clj+++ b/test/metabase/server/middleware/security_test.clj@@ -544,3 +544,82 @@"Cross-Origin-Resource-Policy should be in the response")(is (= "require-corp" (get-in response [:headers "Cross-Origin-Embedder-Policy"]))"Cross-Origin-Embedder-Policy should be in the response"))))))++(deftest csp-header-img-src-tests+ (testing "img-src defaults to permissive wildcard, data, self when csp-img-enabled is false"+ (mt/with-temporary-setting-values [csp-img-enabled false+ csp-img-allowed-hosts "example.com"]+ (is (= "img-src * 'self' data:" (csp-directive "img-src")))))+ (testing "with csp-img-enabled, img-src is restricted to 'self' and data: by default"+ (mt/with-temporary-setting-values [csp-img-enabled true+ csp-img-allowed-hosts ""]+ (is (= "img-src 'self' data:" (csp-directive "img-src")))))+ (testing "nil csp-img-allowed-hosts behaves like empty input"+ (mt/with-temporary-setting-values [csp-img-enabled true+ csp-img-allowed-hosts nil]+ (is (= "img-src 'self' data:" (csp-directive "img-src")))))+ (testing "csp-img-allowed-hosts widens img-src (with wildcard expansion)"+ (mt/with-temporary-setting-values [csp-img-enabled true+ csp-img-allowed-hosts "example.com, https://cdn.foo.com/"]+ (is (= "img-src 'self' data: example.com *.example.com https://cdn.foo.com"+ (csp-directive "img-src"))))))++(deftest csp-header-font-src-tests+ (testing "font-src is restricted to 'self' and data: when no custom fonts are configured"+ (mt/with-premium-features #{:whitelabel}+ (mt/with-temporary-setting-values [application-font-files nil]+ (is (= "font-src 'self' data:" (csp-directive "font-src"))))))+ (testing "font-src dynamically includes the origin of each custom font file"+ (mt/with-premium-features #{:whitelabel}+ (mt/with-temporary-setting-values [application-font-files [{:src "https://fonts.example.com/a.woff2" :fontFormat "woff2" :fontWeight 400}+ {:src "https://fonts.example.com/b.woff2" :fontFormat "woff2" :fontWeight 700}+ {:src "https://cdn.other.com:8443/c.ttf" :fontFormat "ttf" :fontWeight 400}]]+ (is (= "font-src 'self' data: https://fonts.example.com https://cdn.other.com:8443"+ (csp-directive "font-src"))+ "duplicate origins are de-duplicated and ports preserved"))))+ (testing "font-src keeps IPv6 hosts bracketed"+ (mt/with-premium-features #{:whitelabel}+ (mt/with-temporary-setting-values [application-font-files [{:src "https://[2001:db8::1]:8443/c.ttf" :fontFormat "ttf" :fontWeight 400}]]+ (is (= "font-src 'self' data: https://[2001:db8::1]:8443"+ (csp-directive "font-src"))))))+ (testing "malformed / relative / missing font srcs are skipped without error"+ (mt/with-premium-features #{:whitelabel}+ (mt/with-temporary-setting-values [application-font-files [{:src "/relative/font.woff"}+ {:src nil}+ {:fontWeight 400}+ {:src "https://ok.example.com/d.woff2"}]]+ (is (= "font-src 'self' data: https://ok.example.com"+ (csp-directive "font-src")))))))++(deftest csp-header-dev-asset-host-tests+ (testing "in dev, the webpack dev server origin is allowed for img-src and font-src (assets like logos load from there)"+ (mt/with-temporary-setting-values [csp-img-enabled true]+ (with-redefs [config/is-dev? true]+ (is (str/includes? (csp-directive "img-src") @#'mw.security/frontend-address))+ (is (str/includes? (csp-directive "font-src") @#'mw.security/frontend-address)))))+ (testing "in prod the dev server origin is not added"+ (mt/with-temporary-setting-values [csp-img-enabled true]+ (with-redefs [config/is-dev? false]+ (is (= "img-src 'self' data:" (csp-directive "img-src")))+ (is (= "font-src 'self' data:" (csp-directive "font-src")))))))++(deftest ^:parallel parse-allowed-resource-hosts-test+ (testing "parses like the iframe parser, seeded with the always-allowed resource hosts"+ (is (= (concat @#'mw.security/always-allowed-resource-hosts+ ["mysite.com" "*.mysite.com" "http://localhost:8000" "cdn.deep.example.com"])+ (mw.security/parse-allowed-resource-hosts "mysite.com, http://localhost:8000, cdn.deep.example.com"))))+ (testing "empty / blank input yields just the seed hosts"+ (is (= @#'mw.security/always-allowed-resource-hosts (mw.security/parse-allowed-resource-hosts nil)))+ (is (= @#'mw.security/always-allowed-resource-hosts (mw.security/parse-allowed-resource-hosts "")))+ (is (= @#'mw.security/always-allowed-resource-hosts (mw.security/parse-allowed-resource-hosts " "))))+ (testing "invalid hosts are dropped"+ (is (= @#'mw.security/always-allowed-resource-hosts+ (mw.security/parse-allowed-resource-hosts "asdf/wasd/:8000 */localhost:*")))))++(deftest csp-img-enabled-setter-oss-test+ (testing "csp-img-enabled can be turned on/off freely when no enterprise custom-viz setter is loaded"+ (mt/with-temporary-setting-values [csp-img-enabled false]+ (server.settings/csp-img-enabled! true)+ (is (true? (server.settings/csp-img-enabled)))+ (server.settings/csp-img-enabled! false)+ (is (false? (server.settings/csp-img-enabled))))))diff --git a/test_resources/serialization_baseline/settings.yaml b/test_resources/serialization_baseline/settings.yamlindex 69506836068..420d389acb4 100644--- a/test_resources/serialization_baseline/settings.yaml+++ b/test_resources/serialization_baseline/settings.yaml@@ -14,6 +14,8 @@ available-fonts: nullavailable-locales: nullavailable-timezones: nullbreakout-bins-num: null+csp-img-allowed-hosts: null+csp-img-enabled: nullcsv-field-separator: nilcustom-formatting: nullcustom-geojson: null