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
[EMB-2398] serve custom illustration images by a dedicated endpoint (#83211)
Nicolò Pretto554ebdc5aa82
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 58ff04a2f08..6cec68e0da7 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -2532,6 +2532,7 @@:uses #{apiapi-scopeapp-db+ appearancechanneleventslib.schemadiff --git a/e2e/test/scenarios/admin/whitelabel.cy.spec.js b/e2e/test/scenarios/admin/whitelabel.cy.spec.jsindex dffe28bbad5..c4291459ee0 100644--- a/e2e/test/scenarios/admin/whitelabel.cy.spec.js+++ b/e2e/test/scenarios/admin/whitelabel.cy.spec.js@@ -13,6 +13,34 @@ function checkLogo() {});}+function illustrationUrlPattern(settingKey) {+ return new RegExp(`api/session/illustration/${settingKey}\\?v=[0-9a-f]{16}`);+}++function checkIllustrationResponse({ url, imageBase64 }) {+ cy.request({ url, encoding: "base64" }).then((response) => {+ expect(response.headers["content-type"]).to.eq("image/jpeg");+ expect(response.body).to.eq(imageBase64);+ });+}++function checkBackgroundIllustration({ testId, settingKey, imageBase64 }) {+ cy.findByTestId(testId)+ .should("have.css", "background-image")+ .and("match", illustrationUrlPattern(settingKey))+ .then((backgroundImage) => {+ const url = String(backgroundImage).match(/url\("(.+)"\)/)[1];+ checkIllustrationResponse({ url, imageBase64 });+ });+}++function checkNoResultsIllustration({ altText, settingKey, imageBase64 }) {+ cy.findByAltText(altText)+ .should("have.prop", "src")+ .and("match", illustrationUrlPattern(settingKey))+ .then((src) => checkIllustrationResponse({ url: src, imageBase64 }));+}+const MB = 1024 * 1024;describe("formatting > whitelabel", { tags: "@EE" }, () => {@@ -268,23 +296,24 @@ describe("formatting > whitelabel", { tags: "@EE" }, () => {cy.readFile("e2e/support/assets/logo.jpeg", "base64").then((logo_data) => {- const backgroundImage = `url("data:image/jpeg;base64,${logo_data}")`;cy.signOut();+ cy.log("the login page loads the image from its URL");cy.visit("/");- cy.findByTestId("login-page-illustration").should(- "have.css",- "background-image",- backgroundImage,- );+ checkBackgroundIllustration({+ testId: "login-page-illustration",+ settingKey: "login-page-illustration-custom",+ imageBase64: logo_data,+ });+ cy.log("the unsubscribe page loads the image from its URL");cy.visit("/unsubscribe?hash=hash&email=email&pulse-id=pulse-id",);- cy.findByTestId("unsubscribe-page-illustration").should(- "have.css",- "background-image",- backgroundImage,- );+ checkBackgroundIllustration({+ testId: "unsubscribe-page-illustration",+ settingKey: "login-page-illustration-custom",+ imageBase64: logo_data,+ });},);@@ -333,13 +362,12 @@ describe("formatting > whitelabel", { tags: "@EE" }, () => {cy.readFile("e2e/support/assets/logo.jpeg", "base64").then((logo_data) => {- const backgroundImage = `url("data:image/jpeg;base64,${logo_data}")`;cy.visit("/");- cy.findByTestId("landing-page-illustration").should(- "have.css",- "background-image",- backgroundImage,- );+ checkBackgroundIllustration({+ testId: "landing-page-illustration",+ settingKey: "landing-page-illustration-custom",+ imageBase64: logo_data,+ });},);@@ -413,26 +441,24 @@ describe("formatting > whitelabel", { tags: "@EE" }, () => {cy.log("test custom illustration");+ cy.readFile("e2e/support/assets/logo.jpeg", "base64").as("logoData");+H.visitDashboard("@dashboardId");- cy.readFile("e2e/support/assets/logo.jpeg", "base64").then(- (logo_data) => {- const imageDataUrl = `data:image/jpeg;base64,${logo_data}`;- cy.wrap(imageDataUrl).as("imageDataUrl");- cy.findByAltText("No results").should(- "have.attr",- "src",- imageDataUrl,- );- },- );+ cy.get("@logoData").then((logo_data) => {+ checkNoResultsIllustration({+ altText: "No results",+ settingKey: "no-data-illustration-custom",+ imageBase64: logo_data,+ });+ });H.visitQuestion("@questionId");- cy.get("@imageDataUrl").then((imageDataUrl) => {- cy.findByAltText("No results").should(- "have.attr",- "src",- imageDataUrl,- );+ cy.get("@logoData").then((logo_data) => {+ checkNoResultsIllustration({+ altText: "No results",+ settingKey: "no-data-illustration-custom",+ imageBase64: logo_data,+ });});cy.log("test no illustration");@@ -485,23 +511,20 @@ describe("formatting > whitelabel", { tags: "@EE" }, () => {H.popover().findByText("Dashboard").click();H.modal().findByTestId("collection-picker-button").click();H.entityPickerModal().within(() => {- cy.readFile("e2e/support/assets/logo.jpeg", "base64").then(- (logo_data) => {- const imageDataUrl = `data:image/jpeg;base64,${logo_data}`;- cy.wrap(imageDataUrl).as("imageDataUrl");- },+ cy.readFile("e2e/support/assets/logo.jpeg", "base64").as(+ "logoData",);cy.log("test search not found illustration");cy.findByPlaceholderText("Search…").type("This aren't the objects you're looking for",);- cy.get("@imageDataUrl").then((imageDataUrl) => {- cy.findByAltText("No results").should(- "have.attr",- "src",- imageDataUrl,- );+ cy.get("@logoData").then((logo_data) => {+ checkNoResultsIllustration({+ altText: "Nothing found",+ settingKey: "no-object-illustration-custom",+ imageBase64: logo_data,+ });});});@@ -519,13 +542,13 @@ describe("formatting > whitelabel", { tags: "@EE" }, () => {H.modal().findByTestId("collection-picker-button").click();H.entityPickerModal().within(() => {cy.findByText(emptyCollectionName).click();- cy.findByAltText("No results").should("not.exist");+ cy.findByAltText("Nothing found").should("not.exist");cy.log("test search not found illustration");cy.findByPlaceholderText("Search…").type("This aren't the objects you're looking for",);- cy.findByAltText("No results").should("not.exist");+ cy.findByAltText("Nothing found").should("not.exist");});});});diff --git a/enterprise/frontend/src/metabase-enterprise/settings/selectors.ts b/enterprise/frontend/src/metabase-enterprise/settings/selectors.tsindex dbb6c6fb4f2..0c4405cafbf 100644--- a/enterprise/frontend/src/metabase-enterprise/settings/selectors.ts+++ b/enterprise/frontend/src/metabase-enterprise/settings/selectors.ts@@ -1,7 +1,11 @@import noResultsSource from "assets/img/no_results.svg";import type { IllustrationValue } from "metabase/plugins";import type { State } from "metabase/redux/store";-import { getSetting, getSettings } from "metabase/settings";+import {+ getCustomIllustrationUrl,+ getSetting,+ getSettings,+} from "metabase/settings";import type {EnterpriseSettings,IllustrationSettingValue,@@ -62,12 +66,13 @@ export function getLoginPageIllustration(state: State): IllustrationValue {case "none":return null;- case "custom":- return {- // Unjustified type cast. FIXME- src: getSetting(state, "login-page-illustration-custom") as string,- isDefault: false,- };+ case "custom": {+ const src = getCustomIllustrationUrl(+ state,+ "login-page-illustration-custom",+ );+ return src ? { src, isDefault: false } : null;+ }}}@@ -88,12 +93,13 @@ export function getLandingPageIllustration(state: State): IllustrationValue {case "none":return null;- case "custom":- return {- // Unjustified type cast. FIXME- src: getSetting(state, "landing-page-illustration-custom") as string,- isDefault: false,- };+ case "custom": {+ const src = getCustomIllustrationUrl(+ state,+ "landing-page-illustration-custom",+ );+ return src ? { src, isDefault: false } : null;+ }}}@@ -112,8 +118,9 @@ export function getNoDataIllustration(state: State): string | null {return null;case "custom":- // Unjustified type cast. FIXME- return getSetting(state, "no-data-illustration-custom") as string;+ return (+ getCustomIllustrationUrl(state, "no-data-illustration-custom") ?? null+ );}}@@ -132,7 +139,8 @@ export function getNoObjectIllustration(state: State): string | null {return null;case "custom":- // Unjustified type cast. FIXME- return getSetting(state, "no-object-illustration-custom") as string;+ return (+ getCustomIllustrationUrl(state, "no-object-illustration-custom") ?? null+ );}}diff --git a/frontend/src/metabase/common/components/errors/NoObjectError.tsx b/frontend/src/metabase/common/components/errors/NoObjectError.tsxindex e09e6102bf1..2dc70f578a5 100644--- a/frontend/src/metabase/common/components/errors/NoObjectError.tsx+++ b/frontend/src/metabase/common/components/errors/NoObjectError.tsx@@ -10,7 +10,7 @@ export function NoObjectError(props: ImageProps) {return noObjectIllustration ? (<Image- alt={t`No results`}+ alt={t`Nothing found`}w={120}h={120}src={noObjectIllustration}diff --git a/frontend/src/metabase/settings/index.ts b/frontend/src/metabase/settings/index.tsindex 16b35d99027..1bfa94373f1 100644--- a/frontend/src/metabase/settings/index.ts+++ b/frontend/src/metabase/settings/index.ts@@ -13,6 +13,7 @@ export {useUpdateSettingsMutation,} from "./api";export {+ getCustomIllustrationUrl,getSetting,getSettings,getSettingsLoading,diff --git a/frontend/src/metabase/settings/selectors.ts b/frontend/src/metabase/settings/selectors.tsindex 0dab4d52f27..10fb3c80dce 100644--- a/frontend/src/metabase/settings/selectors.ts+++ b/frontend/src/metabase/settings/selectors.ts@@ -1,4 +1,5 @@import type { State } from "metabase/redux/store";+import { getSubpathSafeUrl } from "metabase/urls/utils";import type {EnterpriseSettingKey,EnterpriseSettings,@@ -51,3 +52,21 @@ export const getTokenFeature = (state: State, feature: TokenFeature) => {const tokenFeatures = getSetting(state, "token-features");return tokenFeatures[feature];};++type CustomIllustrationSettingKey =+ | "login-page-illustration-custom"+ | "landing-page-illustration-custom"+ | "no-data-illustration-custom"+ | "no-object-illustration-custom";++const IMAGE_URL_PREFIX = "api/session/illustration/";++// Prefix the relative URLs of images served by `GET /api/session/illustration/:key`+// with the basename, so they also work in the embedding SDK and on subpaths.+export const getCustomIllustrationUrl = (+ state: State,+ key: CustomIllustrationSettingKey,+) => {+ const value = getSetting(state, key);+ return value?.startsWith(IMAGE_URL_PREFIX) ? getSubpathSafeUrl(value) : value;+};diff --git a/frontend/src/metabase/settings/selectors.unit.spec.ts b/frontend/src/metabase/settings/selectors.unit.spec.tsnew file mode 100644index 00000000000..fd690c3606b--- /dev/null+++ b/frontend/src/metabase/settings/selectors.unit.spec.ts@@ -0,0 +1,77 @@+import { setupBasename } from "__support__/basename";+import { createMockSettingsState, createMockState } from "__support__/state";+import { setBasename } from "metabase/utils/basename";+import type { EnterpriseSettings } from "metabase-types/api";++import { getCustomIllustrationUrl } from "./selectors";++const IMAGE_URL =+ "api/session/illustration/no-data-illustration-custom?v=0123456789abcdef";++const setup = (settings: Partial<EnterpriseSettings> = {}) =>+ createMockState({+ settings: createMockSettingsState({+ "no-data-illustration-custom": IMAGE_URL,+ ...settings,+ }),+ });++describe("getCustomIllustrationUrl", () => {+ describe.each([+ ["", IMAGE_URL],+ ["/metabase", `/metabase/${IMAGE_URL}`],+ [+ "https://mb.example.com/metabase",+ `https://mb.example.com/metabase/${IMAGE_URL}`,+ ],+ ])("with basename %j", (basename, expectedUrl) => {+ setupBasename(basename);++ it("prefixes an uploaded image URL with the basename", () => {+ const state = setup();++ expect(+ getCustomIllustrationUrl(state, "no-data-illustration-custom"),+ ).toBe(expectedUrl);+ });++ it("does not change other values", () => {+ const state = setup({+ // legacy format, can still happen in theory: the backend returns a data+ // URI it can't parse (here not base64) unchanged+ "login-page-illustration-custom":+ "data:image/svg+xml,%3Csvg%3E%3C/svg%3E",+ // the admin UI only uploads files, an env var or the API can set a URL+ "no-object-illustration-custom": "https://example.com/image.png",+ // missing for anonymous users, this setting needs a login+ "landing-page-illustration-custom": undefined,+ });++ expect(+ getCustomIllustrationUrl(state, "login-page-illustration-custom"),+ ).toBe("data:image/svg+xml,%3Csvg%3E%3C/svg%3E");+ expect(+ getCustomIllustrationUrl(state, "no-object-illustration-custom"),+ ).toBe("https://example.com/image.png");+ expect(+ getCustomIllustrationUrl(state, "landing-page-illustration-custom"),+ ).toBeUndefined();+ });+ });++ describe("when the basename changes", () => {+ setupBasename("/metabase");++ it("resolves the URL again", () => {+ const state = setup();+ expect(+ getCustomIllustrationUrl(state, "no-data-illustration-custom"),+ ).toBe(`/metabase/${IMAGE_URL}`);++ setBasename("/other");+ expect(+ getCustomIllustrationUrl(state, "no-data-illustration-custom"),+ ).toBe(`/other/${IMAGE_URL}`);+ });+ });+});diff --git a/src/metabase/appearance/core.clj b/src/metabase/appearance/core.cljindex f9547ee9782..19d9dbf886c 100644--- a/src/metabase/appearance/core.clj+++ b/src/metabase/appearance/core.clj@@ -17,9 +17,11 @@custom-formattingcustom-homepagecustom-homepage-dashboard+ custom-illustration-settingsexample-dashboard-idhelp-linkhelp-link-custom-destination+ illustration-imagelanding-pagelanding-page-illustrationlanding-page-illustration-customdiff --git a/src/metabase/appearance/settings.clj b/src/metabase/appearance/settings.cljindex b4b7416350b..995396c96f9 100644--- a/src/metabase/appearance/settings.clj+++ b/src/metabase/appearance/settings.clj@@ -1,12 +1,15 @@(ns metabase.appearance.settings(:require+ [buddy.core.codecs :as codecs]+ [buddy.core.hash :as buddy-hash][clojure.java.io :as io][clojure.string :as str][metabase.appearance.db :as appearance.db][metabase.settings.core :as setting :refer [defsetting]][metabase.util :as u][metabase.util.fonts :as u.fonts]- [metabase.util.i18n :refer [deferred-tru tru]]))+ [metabase.util.i18n :refer [deferred-tru tru]]+ [metabase.util.jvm :as u.jvm]))(set! *warn-on-reflection* true)@@ -223,6 +226,57 @@ See [fonts](../configuring-metabase/fonts.md)."):feature :whitelabel:default "default")+(def ^:private image-data-uri-header+ ;; possessive `*+`: a plain `*` recurses per parameter and overflows the stack on long headers+ #"(?i)(image/[\w.+-]+)((?:;[\w.+-]+=[\w.+-]+)*+);base64")++(defn- parse-image-data-uri+ "Parse a base64 `data:image/...` URI into `{:content-type :media-type :bytes :hash}`, or nil if `s` is not one."+ [^String s]+ (when-let [comma (and (str/starts-with? s "data:") (str/index-of s ","))]+ (when-let [[_ media-type params] (re-matches image-data-uri-header (subs s 5 comma))]+ (try+ {:content-type (str (u/lower-case-en media-type) params)+ :media-type (u/lower-case-en media-type)+ :bytes (u.jvm/decode-base64-to-bytes (subs s (inc comma)))+ :hash (subs (codecs/bytes->hex (buddy-hash/sha256 s)) 0 16)}+ (catch IllegalArgumentException _+ nil)))))++(def custom-illustration-settings+ "The settings that hold a custom illustration, uploaded as a data URI or given as a URL."+ #{:login-page-illustration-custom+ :landing-page-illustration-custom+ :no-data-illustration-custom+ :no-object-illustration-custom})++(def ^:private parsed-illustrations+ "The last raw value of each custom illustration setting and its parsed image, as `{setting-key [raw parsed]}`."+ (atom {}))++(defn- parsed-illustration+ [setting-key raw]+ (let [[cached-raw cached] (get @parsed-illustrations setting-key)+ ;; `raw` is usually the same String instance, but any setting change reloads all settings and gives a new+ ;; instance. with only `=`, the cache would keep the old instance (same content, different reference), so+ ;; every later read would do a content comparison. that's why we also use `identical?` to store the new+ ;; instance: it costs one content comparison per reload, then reads only compare references. with only+ ;; `identical?`, every reload would parse the image again.+ parsed (if (= raw cached-raw) cached (some-> raw parse-image-data-uri))]+ (when-not (identical? raw cached-raw)+ (swap! parsed-illustrations assoc setting-key [raw parsed]))+ parsed))++;; keep uploaded images out of the bootstrap and session properties, they are served by+;; `GET /api/session/illustration/:key`+(defn- illustration-getter+ [setting-key]+ (fn []+ (let [raw (setting/get-value-of-type :string setting-key)]+ (if-let [{image-hash :hash} (parsed-illustration setting-key raw)]+ (str "api/session/illustration/" (name setting-key) "?v=" image-hash)+ raw))))+(defsetting login-page-illustration-custom(deferred-tru "The custom illustration for the login page."):encryption :no@@ -230,7 +284,8 @@ See [fonts](../configuring-metabase/fonts.md)."):export? true:type :string:audit :getter- :feature :whitelabel)+ :feature :whitelabel+ :getter (illustration-getter :login-page-illustration-custom))(defsetting landing-page-illustration(deferred-tru "Options for displaying the illustration on the landing page.")@@ -249,7 +304,8 @@ See [fonts](../configuring-metabase/fonts.md)."):export? true:type :string:audit :getter- :feature :whitelabel)+ :feature :whitelabel+ :getter (illustration-getter :landing-page-illustration-custom))(defsetting no-data-illustration(deferred-tru "Options for displaying the illustration when there are no results after running a question.")@@ -268,7 +324,8 @@ See [fonts](../configuring-metabase/fonts.md)."):export? true:type :string:audit :getter- :feature :whitelabel)+ :feature :whitelabel+ :getter (illustration-getter :no-data-illustration-custom))(defsetting no-object-illustration(deferred-tru "Options for displaying the illustration when there are no results after searching.")@@ -287,7 +344,16 @@ See [fonts](../configuring-metabase/fonts.md)."):export? true:type :string:audit :getter- :feature :whitelabel)+ :feature :whitelabel+ :getter (illustration-getter :no-object-illustration-custom))++(defn illustration-image+ "The uploaded image of the custom illustration setting `setting-key` as `{:content-type :media-type :bytes :hash}`,+ or nil if there is none."+ [setting-key]+ (when (and (contains? custom-illustration-settings setting-key)+ (setting/get setting-key))+ (parsed-illustration setting-key (setting/get-value-of-type :string setting-key))))(def ^:private help-link-options#{:metabase :hidden :custom})diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.cljindex a6601ed242a..1d7f2718f71 100644--- a/src/metabase/session/api.clj+++ b/src/metabase/session/api.clj@@ -6,6 +6,7 @@[metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.open-api :as open-api]+ [metabase.appearance.core :as appearance][metabase.auth-identity.core :as auth-identity][metabase.channel.email.messages :as messages][metabase.channel.settings :as channel.settings]@@ -464,6 +465,28 @@[](setting/user-readable-values-map (setting/current-user-readable-visibilities)))+(api.macros/defendpoint :get "/illustration/:key" :- :any+ "Fetch the uploaded image of a custom illustration setting, e.g. `login-page-illustration-custom`."+ [{setting-name :key} :- [:map {:closed true}+ [:key ms/NonBlankString]]+ {:keys [v]} :- [:map {:closed true}+ [:v {:optional true} :string]]]+ (let [setting-key (keyword setting-name)+ _ (api/check-404 (contains? appearance/custom-illustration-settings setting-key))+ _ (api/check (setting/can-read-setting? setting-key (setting/current-user-readable-visibilities))+ [401 (tru "Unauthenticated")])+ {:keys [content-type media-type], image-bytes :bytes, image-hash :hash}+ (api/check-404 (appearance/illustration-image setting-key))+ headers (cond-> {"Content-Type" content-type+ ;; `v` is the hash in the URL the setting getter returns, so that URL can be cached forever.+ ;; `private` because middleware adds cookies to the response.+ "Cache-Control" (if (= v image-hash)+ "private, max-age=31536000, immutable"+ "private, no-cache")}+ (= media-type "image/svg+xml")+ (assoc "Content-Security-Policy" "default-src 'none'; style-src 'unsafe-inline'; sandbox"))]+ {:status 200, :headers headers, :body image-bytes}))+;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API;;;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers todiff --git a/test/metabase/appearance/settings_test.clj b/test/metabase/appearance/settings_test.cljindex 92bd6c2a91f..4e69b25d818 100644--- a/test/metabase/appearance/settings_test.clj+++ b/test/metabase/appearance/settings_test.clj@@ -2,11 +2,122 @@(:require[clojure.test :refer :all][metabase.appearance.settings :as appearance.settings]+ [metabase.settings.core :as setting][metabase.test :as mt]- [metabase.test.fixtures :as fixtures]))+ [metabase.test.fixtures :as fixtures]+ [metabase.test.util :as tu]+ [metabase.util.jvm :as u.jvm]))(use-fixtures :once (fixtures/initialize :db))+(defn- image-data-uri [content-type content]+ (str "data:" content-type ";base64," (u.jvm/encode-base64 content)))++(defn- do-with-raw-value! [setting-key value thunk]+ (tu/do-with-temporary-setting-value! setting-key value thunk :raw-setting? true))++(deftest custom-illustration-url-test+ (mt/with-premium-features #{:whitelabel}+ (doseq [setting-key appearance.settings/custom-illustration-settings]+ (testing setting-key+ (do-with-raw-value!+ setting-key (image-data-uri "image/png" "first")+ (fn []+ (let [url (setting/get setting-key)]+ (testing "an uploaded image is returned as a URL"+ (is (re-matches (re-pattern (str "api/session/illustration/" (name setting-key) "\\?v=[0-9a-f]{16}"))+ url)))+ (testing "the stored value is still the data URI"+ (is (= (image-data-uri "image/png" "first")+ (setting/get-value-of-type :string setting-key))))+ (testing "the same image gives the same URL"+ (is (= url (setting/get setting-key))))+ (testing "another image gives another URL"+ (do-with-raw-value! setting-key (image-data-uri "image/png" "second")+ #(is (not= url (setting/get setting-key))))))))))))++(deftest custom-illustration-other-values-test+ (mt/with-premium-features #{:whitelabel}+ (doseq [setting-key appearance.settings/custom-illustration-settings]+ (testing setting-key+ (testing "other values are returned unchanged"+ (doseq [value ["https://example.com/login.png"+ (image-data-uri "text/plain" "not an image")+ "data:image/png;base64,%%%"+ "data:image/svg+xml,%3Csvg%3E%3C/svg%3E"]]+ (do-with-raw-value! setting-key value #(is (= value (setting/get setting-key))))))+ (testing "no value"+ (do-with-raw-value! setting-key nil #(is (nil? (setting/get setting-key)))))))))++(deftest custom-illustration-feature-test+ (testing "without the whitelabel feature there is no value and no image"+ (mt/with-premium-features #{}+ (doseq [setting-key appearance.settings/custom-illustration-settings]+ (testing setting-key+ (do-with-raw-value! setting-key (image-data-uri "image/png" "first")+ (fn []+ (is (nil? (setting/get setting-key)))+ (is (nil? (appearance.settings/illustration-image setting-key))))))))))++(deftest illustration-image-test+ (mt/with-premium-features #{:whitelabel}+ (testing "returns the decoded image of each setting"+ (mt/with-temporary-raw-setting-values [login-page-illustration-custom (image-data-uri "IMAGE/PNG" "login")+ landing-page-illustration-custom (image-data-uri "image/png" "landing")+ no-data-illustration-custom (image-data-uri "image/png" "no data")+ no-object-illustration-custom (image-data-uri "image/png" "no object")]+ (doseq [[setting-key content] {:login-page-illustration-custom "login"+ :landing-page-illustration-custom "landing"+ :no-data-illustration-custom "no data"+ :no-object-illustration-custom "no object"}]+ (testing setting-key+ (let [{:keys [content-type], image-bytes :bytes, image-hash :hash}+ (appearance.settings/illustration-image setting-key)]+ (is (= "image/png" content-type))+ (is (= content (String. ^bytes image-bytes "UTF-8")))+ (is (= (str "api/session/illustration/" (name setting-key) "?v=" image-hash)+ (setting/get setting-key))))))))))++(deftest illustration-image-media-type-test+ (mt/with-premium-features #{:whitelabel}+ (testing "media type parameters are kept"+ (mt/with-temporary-raw-setting-values [login-page-illustration-custom+ (image-data-uri "image/svg+xml;charset=iso-8859-1" "<svg/>")]+ (is (= {:content-type "image/svg+xml;charset=iso-8859-1", :media-type "image/svg+xml"}+ (select-keys (appearance.settings/illustration-image :login-page-illustration-custom)+ [:content-type :media-type])))))+ (testing "a header with many parameters does not overflow the regex"+ (let [media-type (apply str "image/png" (for [i (range 5000)] (str ";p" i "=b")))]+ (mt/with-temporary-raw-setting-values [login-page-illustration-custom (image-data-uri media-type "first")]+ (is (= "image/png" (:media-type (appearance.settings/illustration-image :login-page-illustration-custom)))))))+ (testing "a header with invalid characters is returned unchanged"+ (let [value (str "data:image/png;x=a\r\nb;base64," (u.jvm/encode-base64 "first"))]+ (mt/with-temporary-raw-setting-values [login-page-illustration-custom value]+ (is (= value (appearance.settings/login-page-illustration-custom))))))))++(deftest illustration-image-nil-test+ (mt/with-premium-features #{:whitelabel}+ (testing "nil when the value is not an uploaded image"+ (mt/with-temporary-raw-setting-values [login-page-illustration-custom "https://example.com/login.png"]+ (is (nil? (appearance.settings/illustration-image :login-page-illustration-custom)))))+ (testing "nil for other settings"+ (mt/with-temporary-raw-setting-values [application-logo-url (image-data-uri "image/png" "logo")]+ (is (nil? (appearance.settings/illustration-image :application-logo-url)))))))++(deftest parsed-illustration-cache-reload-test+ (let [setting-key :login-page-illustration-custom+ raw (image-data-uri "image/png" "first")+ reloaded (String. ^String raw)+ cache (atom {})]+ (with-redefs [appearance.settings/parsed-illustrations cache]+ (let [parsed (#'appearance.settings/parsed-illustration setting-key raw)]+ (is (some? parsed))+ (is (= raw reloaded))+ (is (not (identical? raw reloaded)))+ (is (identical? parsed+ (#'appearance.settings/parsed-illustration setting-key reloaded)))+ (is (identical? reloaded (first (get @cache setting-key))))))))+(deftest help-link-setting-test(mt/discard-setting-changes [help-link](mt/with-premium-features #{:whitelabel}diff --git a/test/metabase/session/api_test.clj b/test/metabase/session/api_test.cljindex fc939034924..6223ca1ac46 100644--- a/test/metabase/session/api_test.clj+++ b/test/metabase/session/api_test.clj@@ -4,6 +4,7 @@[clj-http.client :as http][clojure.test :refer :all][medley.core :as m]+ [metabase.appearance.core :as appearance][metabase.auth-identity.core :as auth-identity][metabase.driver.h2 :as h2][metabase.login-history.db :as login-history.db]@@ -20,8 +21,10 @@[metabase.test.data.users :as test.users][metabase.test.fixtures :as fixtures][metabase.test.http-client :as client]+ [metabase.test.util :as tu][metabase.util :as u][metabase.util.json :as json]+ [metabase.util.jvm :as u.jvm][metabase.util.malli.schema :as ms][metabase.util.string :as string][toucan2.core :as t2]))@@ -625,6 +628,92 @@(-> (mt/user-http-request :crowberto :get 200 "session/properties"):test-session-api-setting)))))))+(defn- image-data-uri [content-type content]+ (str "data:" content-type ";base64," (u.jvm/encode-base64 content)))++(defn- do-with-raw-value! [setting-key value thunk]+ (tu/do-with-temporary-setting-value! setting-key value thunk :raw-setting? true))++(defn- illustration-request+ "Call the API as rasta for the landing page illustration, which needs a logged in user, else anonymously."+ [setting-key & args]+ (if (= setting-key :landing-page-illustration-custom)+ (apply mt/user-http-request-full-response :rasta args)+ (apply mt/client-full-response args)))++(defn- fetch-illustration [setting-key expected-status & args]+ (apply illustration-request setting-key :get expected-status (str "session/illustration/" (name setting-key)) args))++(defn- do-with-each-uploaded-illustration!+ "Upload an image to each custom illustration setting and call `(f setting-key image-hash)`."+ [f]+ (mt/with-premium-features #{:whitelabel}+ (doseq [setting-key appearance/custom-illustration-settings]+ (testing setting-key+ (do-with-raw-value! setting-key (image-data-uri "image/png" "png bytes")+ #(f setting-key (second (re-find #"v=(.+)$" (setting/get setting-key)))))))))++(deftest illustration-test+ (do-with-each-uploaded-illustration!+ (fn [setting-key _image-hash]+ (let [{:keys [body headers]} (fetch-illustration setting-key 200)]+ (is (= "png bytes" body))+ (is (= "image/png" (get headers "Content-Type")))+ (testing "no Cross-Origin-Resource-Policy, the React SDK loads it from the host app origin"+ (is (nil? (get headers "Cross-Origin-Resource-Policy"))))))))++(deftest illustration-session-properties-test+ (testing "session properties contain the URL, not the image"+ (do-with-each-uploaded-illustration!+ (fn [setting-key image-hash]+ (is (= (str "api/session/illustration/" (name setting-key) "?v=" image-hash)+ (get-in (illustration-request setting-key :get 200 "session/properties") [:body setting-key])))))))++(deftest illustration-cache-test+ (do-with-each-uploaded-illustration!+ (fn [setting-key image-hash]+ (let [cached "private, max-age=31536000, immutable"]+ (testing "the URL without a hash is not cached"+ (is (= "private, no-cache" (get-in (fetch-illustration setting-key 200) [:headers "Cache-Control"]))))+ (testing "the URL with the current hash is cached"+ (is (= cached (get-in (fetch-illustration setting-key 200 :v image-hash) [:headers "Cache-Control"]))))+ (testing "a URL with another hash is not cached"+ (is (= "private, no-cache"+ (get-in (fetch-illustration setting-key 200 :v "0000000000000000") [:headers "Cache-Control"]))))))))++(deftest illustration-authentication-test+ (testing "the landing page illustration needs a logged in user"+ (mt/with-premium-features #{:whitelabel}+ (mt/with-temporary-raw-setting-values [landing-page-illustration-custom (image-data-uri "image/png" "png bytes")]+ (mt/client-full-response :get 401 "session/illustration/landing-page-illustration-custom")))))++(deftest illustration-svg-test+ (testing "SVG images get a sandbox CSP"+ (mt/with-premium-features #{:whitelabel}+ (doseq [content-type ["image/svg+xml" "image/svg+xml;charset=iso-8859-1"]]+ (testing (str "Content-Type = " content-type)+ (mt/with-temporary-raw-setting-values [login-page-illustration-custom (image-data-uri content-type "<svg/>")]+ (let [{:keys [headers]} (fetch-illustration :login-page-illustration-custom 200)]+ (is (= content-type (get headers "Content-Type")))+ (is (= "default-src 'none'; style-src 'unsafe-inline'; sandbox"+ (get headers "Content-Security-Policy"))))))))))++(deftest illustration-not-found-test+ (mt/with-premium-features #{:whitelabel}+ (testing "404 when there is no uploaded image"+ (doseq [setting-key appearance/custom-illustration-settings+ value [nil "https://example.com/login.png"]]+ (testing [setting-key value]+ (do-with-raw-value! setting-key value #(fetch-illustration setting-key 404)))))+ (testing "404 for other settings"+ (mt/with-temporary-raw-setting-values [application-logo-url (image-data-uri "image/png" "png bytes")]+ (fetch-illustration :application-logo-url 404)+ (fetch-illustration :not-a-setting 404))))+ (testing "404 without the whitelabel feature"+ (mt/with-premium-features #{}+ (mt/with-temporary-raw-setting-values [login-page-illustration-custom (image-data-uri "image/png" "png bytes")]+ (fetch-illustration :login-page-illustration-custom 404)))))+(deftest properties-i18n-test(testing "GET /session/properties"(testing "Setting the X-Metabase-Locale header should result give you properties in that locale"