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
Require auth for data app bundle and iframe routes (#82417)
Timofey Kachalovbbcf4b7d456b
diff --git a/e2e/test/scenarios/data-apps/user-access.cy.spec.ts b/e2e/test/scenarios/data-apps/user-access.cy.spec.tsindex a5f3d0765b2..d5feefe605f 100644--- a/e2e/test/scenarios/data-apps/user-access.cy.spec.ts+++ b/e2e/test/scenarios/data-apps/user-access.cy.spec.ts@@ -18,6 +18,9 @@ const DATA_APP_NAME = "user-access-test";const { ORDERS_ID, PRODUCTS_ID } = SAMPLE_DATABASE;+const SYNCED_APP_SLUG = "good";+const ALLOWED_HOST = "https://secret-api.data-app.test";+const NORMAL_USER_NAME = `${USERS.normal.first_name} ${USERS.normal.last_name}`;const NODATA_USER_NAME = `${USERS.nodata.first_name} ${USERS.nodata.last_name}`;@@ -340,6 +343,86 @@ describe("scenarios > data apps > user access (EMB-2328)", () => {}).should("not.exist");});});++ describe("signed-out visitors", () => {+ beforeEach(() => {+ H.setupGitSync();+ H.copySyncedCollectionFixture();+ H.copySyncedDataAppsFixture();+ cy.task("writeDataAppFiles", {+ files: {+ [`${H.LOCAL_GIT_PATH}/data_apps/${SYNCED_APP_SLUG}/data_app.yaml`]: [+ "name: Good App",+ "path: ./index.js",+ "allowed_hosts:",+ ` - ${ALLOWED_HOST}`,+ "",+ ].join("\n"),+ },+ });+ H.commitToRepo("Add a data app with an allowed host");+ H.configureGitAndPullChanges("read-write");++ cy.request(`/embed/apps/${SYNCED_APP_SLUG}`).then((res) => {+ expect(String(res.headers["content-security-policy"])).to.contain(+ ALLOWED_HOST,+ );+ });++ cy.signOut();+ });++ it("does not serve the iframe document or its allowed hosts", () => {+ cy.request({+ url: `/embed/apps/${SYNCED_APP_SLUG}`,+ failOnStatusCode: false,+ followRedirect: false,+ }).then((res) => {+ expect(res.status).to.eq(302);+ expect(String(res.headers["location"])).to.contain("/auth/login");+ expect(+ String(res.headers["content-security-policy"] ?? ""),+ ).not.to.contain(ALLOWED_HOST);+ });+ });++ it("does not put the allowed hosts on the top-level app page", () => {+ cy.request({+ url: `/apps/${SYNCED_APP_SLUG}`,+ failOnStatusCode: false,+ followRedirect: false,+ }).then((res) => {+ // The SPA shell is still served; the React app sends the visitor to+ // login. Anchor on it so a 404 or an empty response can't pass the+ // negative check below.+ expect(res.status).to.eq(200);+ expect(String(res.headers["content-type"])).to.contain("text/html");+ expect(res.headers["content-security-policy"]).to.be.a("string");+ expect(res.headers["content-security-policy"]).not.to.contain(+ ALLOWED_HOST,+ );+ });+ });++ it("refuses the bundle and app metadata", () => {+ cy.request({+ url: `/api/apps/${SYNCED_APP_SLUG}/bundle`,+ failOnStatusCode: false,+ }).then((res) => {+ expect(res.status).to.eq(401);+ expect(res.headers).not.to.have.property(+ "x-metabase-data-app-allowed-hosts",+ );+ });++ cy.request({+ url: `/api/apps/${SYNCED_APP_SLUG}`,+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 401);+ });+ });});const dataAppRow = () =>diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/csp_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/csp_test.cljindex 721c735eb52..16801a2fd62 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/csp_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/csp_test.clj@@ -10,16 +10,18 @@(defn- connect-src-for!"The `connect-src` directive of the CSP that the security middleware emits for- a request to `uri`."- [uri]- (with-redefs [config/is-dev? false]- (let [handler (mw.security/add-security-headers- (fn [_req respond _raise] (respond {:status 200 :headers {} :body "ok"})))- response (handler {:uri uri :headers {}} identity identity)- csp (get-in response [:headers "Content-Security-Policy"])]- (->> (str/split csp #";\s*")- (filter #(str/starts-with? % "connect-src "))- first))))+ a signed-in request to `uri` (a signed-out one never carries an app's hosts)."+ ([uri]+ (connect-src-for! uri {:metabase-user-id (mt/user->id :rasta)}))+ ([uri request]+ (with-redefs [config/is-dev? false]+ (let [handler (mw.security/add-security-headers+ (fn [_req respond _raise] (respond {:status 200 :headers {} :body "ok"})))+ response (handler (merge {:uri uri :headers {}} request) identity identity)+ csp (get-in response [:headers "Content-Security-Policy"])]+ (->> (str/split csp #";\s*")+ (filter #(str/starts-with? % "connect-src "))+ first)))))(deftest data-app-connect-src-allowed-hosts-test(mt/with-premium-features #{:data-apps-preview}@@ -40,6 +42,9 @@(is (not (str/includes? (connect-src-for! "/") "https://api.example.com"))))(testing "an unknown app contributes no hosts"(is (not (str/includes? (connect-src-for! "/embed/apps/nope")+ "api.example.com"))))+ (testing "a signed-out visitor never gets them, even for a real app"+ (is (not (str/includes? (connect-src-for! "/embed/apps/boba" {})"api.example.com")))))))(deftest data-app-connect-src-hosts-fn-testdiff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.cljindex cb56b3879fd..5e7771b8d9e 100644--- a/src/metabase/server/middleware/security.clj+++ b/src/metabase/server/middleware/security.clj@@ -653,9 +653,16 @@:data-app-iframe? (data-app-iframe-request? request);; Per-app `allowed_hosts` → `connect-src`/`form-action` (iframe;; doc) and `frame-src` (both the iframe doc and the top page,- ;; whose `frame-src` gates the iframe's own navigations).+ ;; whose `frame-src` gates the iframe's own navigations). The+ ;; hosts are looked up only for a signed-in user: the header would+ ;; otherwise hand an app's `allowed_hosts` to anyone who can guess+ ;; its slug, and let them probe which slugs exist. A signed-out+ ;; request still gets the data-app policy with an empty allowlist,+ ;; not the broader instance-wide one.:data-app-connect-hosts (when-let [slug (data-app-slug request)]- (drop-instance-origin (data-app-connect-src-hosts slug)))+ (if (:metabase-user-id request)+ (drop-instance-origin (data-app-connect-src-hosts slug))+ []));; Data apps and the EAJS embed page both render custom viz icons as blob: <img> URLs:allow-blob-img? (or (data-app-iframe-request? request)(request/embed-sdk-eajs-entrypoint? request)))diff --git a/src/metabase/server/routes/index.clj b/src/metabase/server/routes/index.cljindex 2679c5a231c..ca8d0d5b6e9 100644--- a/src/metabase/server/routes/index.clj+++ b/src/metabase/server/routes/index.clj@@ -18,6 +18,7 @@[metabase.util.json :as json][metabase.util.log :as log][metabase.util.memoize :as memoize]+ [ring.util.codec :as codec][ring.util.response :as response][stencil.core :as stencil])(:import@@ -132,12 +133,26 @@"Raw `/embed/apps/:name` iframe HTML entrypoint, before feature gating."(partial entrypoint "data-app" :embeddable))+(defn- login-redirect+ "302 to the login page, returning the user to the top-level `/apps/...` page for the+ `/embed/apps/...` iframe document they asked for (the bare iframe shell is not a page+ a person would want to land on). `site-url` is nil until a superuser's first request+ sets it, and this is reached by signed-out visitors: `str` drops the nil, so the+ redirect is then relative."+ [{:keys [uri query-string]}]+ (let [target (cond-> (str/replace-first uri #"^/embed/" "/")+ (seq query-string) (str "?" query-string))]+ (response/redirect (str (system/site-url) "/auth/login?redirect=" (codec/url-encode target)))))+(defn data-app"`/embed/apps/:name` iframe entrypoint. Served only when the `:data-apps-preview` feature isenabled; without it, responds nil so routing falls through to the generic embed handler — theinstance then behaves exactly as if data apps did not exist, keeping the feature gate with the- data-app entrypoint rather than in the top-level route table."+ data-app entrypoint rather than in the top-level route table. A signed-out visitor is sent to+ the login page: the document's CSP carries the app's `allowed_hosts`, which only signed-in+ users may see."[request respond raise]- (if (premium-features/enable-data-apps?)- (data-app-shell request respond raise)- (respond nil)))+ (cond+ (not (premium-features/enable-data-apps?)) (respond nil)+ (nil? (:metabase-user-id request)) (respond (login-redirect request))+ :else (data-app-shell request respond raise)))diff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.cljindex 941870ca757..ba9081dfd23 100644--- a/test/metabase/server/middleware/security_test.clj+++ b/test/metabase/server/middleware/security_test.clj@@ -134,12 +134,17 @@(is (= (str "ALLOW-FROM " (first embedding-app-origins))(x-frame-options-header))))))))-(defn- headers-for-uri- "Run the security-headers middleware for a request to `uri` and return its headers."- [uri]+(defn- headers-for-request+ "Run the security-headers middleware for `request` and return its headers."+ [request](let [handler (mw.security/add-security-headers(fn [_request respond _raise] (respond {:status 200 :headers {} :body "ok"})))]- (:headers (handler {:uri uri :headers {}} identity identity))))+ (:headers (handler (merge {:headers {}} request) identity identity))))++(defn- headers-for-uri+ "Run the security-headers middleware for a signed-in request to `uri` and return its headers."+ [uri]+ (headers-for-request {:uri uri :metabase-user-id 1}))(defn- frame-ancestors-for [uri](->> (str/split (get (headers-for-uri uri) "Content-Security-Policy") #"; *")@@ -228,6 +233,34 @@(is (str/includes? frame-src "wikipedia"))(is (not (str/includes? frame-src "https://example.com"))))))))+(deftest data-app-hosts-only-for-signed-in-users-test+ (testing "a signed-out request never sees an app's allowed_hosts in its CSP, and never triggers the lookup"+ (let [lookups (atom 0)]+ (with-redefs [mw.security/data-app-connect-src-hosts (fn [_slug] (swap! lookups inc) ["https://example.com"])]+ (doseq [uri ["/embed/apps/sales" "/embed/apps/sales/sub/route" "/apps/sales"]]+ (let [csp (get (headers-for-request {:uri uri}) "Content-Security-Policy")]+ (is (not (str/includes? csp "https://example.com")) uri)))+ (is (= "form-action 'none'"+ (-> (headers-for-request {:uri "/embed/apps/sales"})+ (get "Content-Security-Policy")+ (header->directive "form-action"))))+ (is (zero? @lookups)))))+ (testing "a signed-out request keeps the data-app policy with an empty allowlist rather than the instance-wide one"+ (mt/with-temporary-setting-values [allowed-iframe-hosts "https://widgets.example"]+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]+ (doseq [uri ["/embed/apps/sales" "/apps/sales"]]+ (is (= "frame-src 'self'"+ (-> (headers-for-request {:uri uri})+ (get "Content-Security-Policy")+ (header->directive "frame-src")))+ uri)))))+ (testing "a signed-in request gets them"+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]+ (doseq [uri ["/embed/apps/sales" "/apps/sales"]]+ (is (str/includes? (get (headers-for-request {:uri uri :metabase-user-id 1}) "Content-Security-Policy")+ "https://example.com")+ uri)))))+(deftest data-app-instance-origin-excluded-test(testing "the Metabase instance origin is dropped from a data app's allowlist even if listed"(mt/with-temporary-setting-values [site-url "https://mymetabase.example"]diff --git a/test/metabase/server/routes_test.clj b/test/metabase/server/routes_test.cljindex 898d5786a6d..c796a85fa6a 100644--- a/test/metabase/server/routes_test.clj+++ b/test/metabase/server/routes_test.clj@@ -28,6 +28,11 @@(get "Location"))"/api/embed/card/token-string/query/csv?"))))+(defn- serve-data-app [request]+ (let [p (promise)]+ (index/data-app request #(deliver p %) #(deliver p %))+ @p))+(deftest data-app-entrypoint-is-gated-by-the-data-apps-feature-test(testing "the /embed/apps/:name entrypoint is served only with :data-apps-preview; without it itresponds nil so routing falls through to the generic embed handler — exactly as if data@@ -35,14 +40,29 @@;; Stub the raw shell so the test needs no built frontend HTML; the feature gate lives in;; `index/data-app` itself, which is what we're exercising here.(with-redefs [index/data-app-shell (fn [_req respond _raise] (respond {:status 200 :body "DATA-APP"}))]- (let [serve (fn []- (let [p (promise)]- (index/data-app {} #(deliver p %) #(deliver p %))- @p))]+ (let [request {:uri "/embed/apps/sales" :metabase-user-id (mt/user->id :rasta)}];; `enable-data-apps?` also requires the EE code to be present (`config/ee-available?`), so the;; served path exists only on EE; on OSS the entrypoint always falls through.(mt/when-ee-evailable(mt/with-premium-features #{:data-apps-preview}- (is (= "DATA-APP" (:body (serve))) "with the feature, serves the data-app shell")))+ (is (= "DATA-APP" (:body (serve-data-app request))) "with the feature, serves the data-app shell")))(mt/with-premium-features #{}- (is (nil? (serve)) "without the feature, responds nil so routing falls through"))))))+ (is (nil? (serve-data-app request)) "without the feature, responds nil so routing falls through"))))))++(deftest data-app-entrypoint-requires-a-signed-in-user-test+ (testing "a signed-out visitor is redirected to the login page instead of getting the iframe document,+ whose CSP carries the app's allowed_hosts; the redirect returns them to the top-level page"+ (mt/when-ee-evailable+ (mt/with-premium-features #{:data-apps-preview}+ (with-redefs [index/data-app-shell (fn [_req respond _raise] (respond {:status 200 :body "DATA-APP"}))]+ (let [response (serve-data-app {:uri "/embed/apps/sales/sub/route" :query-string "tab=1"})]+ (is (= 302 (:status response)))+ (is (str/ends-with? (get-in response [:headers "Location"])+ "/auth/login?redirect=%2Fapps%2Fsales%2Fsub%2Froute%3Ftab%3D1")))+ (testing "with site-url not yet set, the redirect is relative rather than prefixed with nil"+ (mt/with-temporary-setting-values [site-url nil]+ (is (= "/auth/login?redirect=%2Fapps%2Fsales"+ (get-in (serve-data-app {:uri "/embed/apps/sales"}) [:headers "Location"]))))))))+ (testing "without the feature it still falls through, so the instance reveals nothing about data apps"+ (mt/with-premium-features #{}+ (is (nil? (serve-data-app {:uri "/embed/apps/sales"})))))))