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
Guest embed filter dropdowns should use the router database (UXW-4881) (#78235)
John Swansonc5b6a38acb65
diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/embedding_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/embedding_test.cljindex b358bfe0046..72ad9c5a749 100644--- a/enterprise/backend/test/metabase_enterprise/database_routing/embedding_test.clj+++ b/enterprise/backend/test/metabase_enterprise/database_routing/embedding_test.clj@@ -4,6 +4,7 @@[buddy.sign.jwt :as jwt][clojure.test :refer [deftest is testing]][metabase-enterprise.database-routing.e2e-test :refer [execute-statement! with-routing-setup!]]+ [metabase-enterprise.test :as met][metabase.driver.settings :as driver.settings][metabase.test :as mt][metabase.test.http-client :as client]@@ -36,6 +37,11 @@:params {}}additional-token-keys)))+(defn dash-token [dash-or-id & [additional-token-keys]]+ (sign (merge {:resource {:dashboard (u/the-id dash-or-id)}+ :params {}}+ additional-token-keys)))+(deftest guest-embedding-with-database-routing-test(testing "Guest embedding should work with database routing by bypassing routing"(mt/with-premium-features #{:database-routing}@@ -57,3 +63,90 @@response (client/client :get 202 (str "embed/card/" token "/query"))](is (= [["router-data"]] (mt/rows response))"Guest embedding should return data from router database, not destination database"))))))))))++(deftest guest-embedding-dashboard-param-values-with-database-routing-test+ (testing "Guest embed dashboard filter dropdowns bypass routing and use the router database (UXW-4881)"+ (mt/with-premium-features #{:database-routing}+ (binding [driver.settings/*allow-testing-h2-connections* true]+ (with-routing-setup! [router-db [[destination-db "destination-db"]]]+ (let [table-id (t2/select-one-pk :model/Table :db_id (u/the-id router-db))+ field-id (t2/select-one-pk :model/Field :table_id table-id)]+ (mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)+ :user_attribute "db_name"}+ :model/Card card {:dataset_query {:database (u/the-id router-db)+ :type :query+ :query {:source-table table-id}}}+ :model/Dashboard dashboard {:enable_embedding true+ :embedding_params {:str "enabled"}+ :parameters [{:id "_STR_"+ :name "Str"+ :slug "str"+ :type "string/="}]}+ :model/DashboardCard _ {:dashboard_id (u/the-id dashboard)+ :card_id (u/the-id card)+ :parameter_mappings [{:parameter_id "_STR_"+ :card_id (u/the-id card)+ :target [:dimension [:field field-id nil]]}]}]+ (execute-statement! router-db "INSERT INTO \"my_database_name\" (str) VALUES ('router-data')")+ (execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('destination-data')")+ (with-embedding-enabled-and-new-secret-key!+ (testing "GET /api/embed/dashboard/:token/params/:param-key/values"+ (let [token (dash-token dashboard)+ response (client/client :get 200 (str "embed/dashboard/" token "/params/_STR_/values"))]+ (is (= {:values [["router-data"]]+ :has_more_values false}+ response)+ "Dropdown values should come from the router database, not a destination database")))))))))))++(deftest guest-embedding-card-param-values-with-database-routing-test+ (testing "Guest embed card filter dropdowns bypass routing and use the router database (UXW-4881)"+ (mt/with-premium-features #{:database-routing}+ (binding [driver.settings/*allow-testing-h2-connections* true]+ (with-routing-setup! [router-db [[destination-db "destination-db"]]]+ (let [table-id (t2/select-one-pk :model/Table :db_id (u/the-id router-db))+ field-id (t2/select-one-pk :model/Field :table_id table-id)]+ (mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)+ :user_attribute "db_name"}+ :model/Card card {:enable_embedding true+ :embedding_params {:str "enabled"}+ :dataset_query {:database (u/the-id router-db)+ :type :native+ :native {:query "SELECT count(*) FROM \"my_database_name\" WHERE {{str}}"+ :template-tags {"str" {:id "_STR_"+ :name "str"+ :display-name "Str"+ :type :dimension+ :dimension [:field field-id nil]+ :widget-type :string/=}}}}}]+ (execute-statement! router-db "INSERT INTO \"my_database_name\" (str) VALUES ('router-data')")+ (execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('destination-data')")+ (with-embedding-enabled-and-new-secret-key!+ (testing "GET /api/embed/card/:token/params/:param-key/values"+ (let [token (card-token card)+ response (client/client :get 200 (str "embed/card/" token "/params/_STR_/values"))]+ (is (=? {:values [["router-data"]]+ :has_more_values false}+ response)+ "Dropdown values should come from the router database, not a destination database")))))))))))++(deftest preview-embedding-uses-router-database-test+ (testing "Preview embed queries bypass routing so the preview matches the published embed (UXW-4881)"+ (mt/with-premium-features #{:database-routing}+ (binding [driver.settings/*allow-testing-h2-connections* true]+ (met/with-user-attributes!+ :crowberto+ {"db_name" "destination-db"}+ (with-routing-setup! [router-db [[destination-db "destination-db"]]]+ (mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)+ :user_attribute "db_name"}+ :model/Card card {:dataset_query {:database (u/the-id router-db)+ :type :query+ :query {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}}}]+ (execute-statement! router-db "INSERT INTO \"my_database_name\" (str) VALUES ('router-data')")+ (execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('destination-data')")+ (with-embedding-enabled-and-new-secret-key!+ (testing "GET /api/preview_embed/card/:token/query"+ (let [token (card-token card {:_embedding_params {}})+ response (mt/user-http-request :crowberto :get 202 (str "preview_embed/card/" token "/query"))]+ (is (= [["router-data"]] (mt/rows response))+ "Preview should show router-database data even though the admin's attribute routes to a destination")))))))))))diff --git a/src/metabase/embedding_rest/api/common.clj b/src/metabase/embedding_rest/api/common.cljindex c60f035d0f7..4424d81ceee 100644--- a/src/metabase/embedding_rest/api/common.clj+++ b/src/metabase/embedding_rest/api/common.clj@@ -5,6 +5,7 @@[medley.core :as m][metabase.api.common :as api][metabase.dashboards.schema :as dashboards.schema]+ [metabase.database-routing.core :as database-routing][metabase.eid-translation.core :as eid-translation][metabase.embedding.jwt :as embed][metabase.embedding.validation :as embedding.validation]@@ -17,6 +18,7 @@[metabase.query-processor.card :as qp.card][metabase.query-processor.middleware.constraints :as qp.constraints][metabase.query-processor.parameters.operators :as params.ops]+ [metabase.request.core :as request][metabase.tiles.api :as api.tiles][metabase.util :as u][metabase.util.i18n :refer [tru]]@@ -324,22 +326,36 @@:json :embedded-json-download:embedded-question))+;;; Embedded viewers have no Metabase account, so there are no user attributes to route by: embedded query execution+;;; always uses the router (primary) database. The `with-database-routing-off` wraps live here, in the shared+;;; execution helpers that every /api/embed and /api/preview_embed endpoint funnels through, so that individual+;;; endpoints cannot forget them. (For preview_embed this also means the preview shows what the published embed will+;;; show, rather than routing via the previewing admin's own user attribute.)+(defn process-query-for-card-with-params"Run the query associated with pre-loaded Card `card` using JWT `token-params`, user-supplied URL `query-params`,an `embedding-params` whitelist, and additional query `options`. Callers are responsible for selecting `card`- exactly once per request and threading it here. Returns `StreamingResponse` that should be returned as the API- endpoint result."+ exactly once per request and threading it here. Runs with database routing off (see above). Returns+ `StreamingResponse` that should be returned as the API endpoint result."[& {:keys [export-format card embedding-params token-params query-params qp constraints options]:or {qp qp.card/process-query-for-card-default-qp}}]{:pre [(map? card) (pos-int? (:id card)) (u/maybe? map? embedding-params) (map? token-params) (map? query-params)]}(let [merged-slug->value (validate-and-merge-params embedding-params token-params (normalize-query-params query-params))parameters (apply-slug->value (resolve-card-parameters card) merged-slug->value)]- (m/mapply api.public/process-query-for-card-with-id- card export-format parameters- :context (get-embed-card-context export-format)- :constraints constraints- :qp qp- options)))+ (database-routing/with-database-routing-off+ (m/mapply api.public/process-query-for-card-with-id+ card export-format parameters+ :context (get-embed-card-context export-format)+ :constraints constraints+ :qp qp+ options))))++(defn process-tiles-query-for-card+ "Like [[metabase.tiles.api/process-tiles-query-for-card]], but takes a pre-loaded Card entity and runs with database+ routing off (see above). Used by the embed tiles endpoints. Returns a Ring response."+ [card parameters zoom x y lat-field lon-field]+ (database-routing/with-database-routing-off+ (api.tiles/process-tiles-query-for-card card parameters zoom x y lat-field lon-field)));;; -------------------------- Dashboard Fns used by both /api/embed and /api/preview_embed --------------------------@@ -404,8 +420,8 @@(defn process-query-for-dashcard"Return results for running the query belonging to a DashboardCard. Callers are responsible for selecting the- `dashboard`, `dashcard`, and `card` entities exactly once per request and threading them here. Returns a- `StreamingResponse`."+ `dashboard`, `dashcard`, and `card` entities exactly once per request and threading them here. Runs with database+ routing off (see the comment above [[process-query-for-card-with-params]]). Returns a `StreamingResponse`."[& {:keys [dashboard dashcard card export-format embedding-params token-params middlewarequery-params constraints qp]:or {constraints (qp.constraints/default-query-constraints)@@ -414,24 +430,26 @@(map? token-params) (map? query-params)]}(let [slug->value (validate-and-merge-params embedding-params token-params (normalize-query-params query-params))parameters (resolve-dashboard-parameters dashboard slug->value)]- (api.public/process-query-for-dashcard- :dashboard dashboard- :card card- :dashcard dashcard- :export-format export-format- :parameters parameters- :qp qp- :context (get-embed-dashboard-context export-format)- :constraints constraints- :middleware middleware)))+ (database-routing/with-database-routing-off+ (api.public/process-query-for-dashcard+ :dashboard dashboard+ :card card+ :dashcard dashcard+ :export-format export-format+ :parameters parameters+ :qp qp+ :context (get-embed-dashboard-context export-format)+ :constraints constraints+ :middleware middleware))))(defn process-tiles-query-for-dashcard"Like [[metabase.tiles.api/process-tiles-query-for-dashcard]], but takes pre-loaded Dashboard/DashboardCard/Card- entities. Used by the embed tiles endpoints. Callers select each entity exactly once and thread it here. Returns- a Ring response."+ entities and runs with database routing off (see the comment above [[process-query-for-card-with-params]]). Used by+ the embed tiles endpoints. Callers select each entity exactly once and thread it here. Returns a Ring response."[dashboard dashcard card parameters zoom x y lat-field lon-field]- (api.tiles/process-tiles-query-for-dashcard dashboard dashcard card- parameters zoom x y lat-field lon-field))+ (database-routing/with-database-routing-off+ (api.tiles/process-tiles-query-for-dashcard dashboard dashcard card+ parameters zoom x y lat-field lon-field)))(defn card-param-values"Search for card parameter values. Does security checks to ensure the parameter is on the card and then gets param@@ -453,9 +471,10 @@(throw (ex-info (tru "You can''t specify a value for {0} if it''s already set in the JWT." (pr-str searched-param-slug)){:status-code 400})))(try- (binding [api/*current-user-permissions-set* (atom #{"/"})- api/*is-superuser?* true]- (queries/card-param-values card param-key search-prefix))+ ;; guest embeds always use the router (primary) database, never a routed destination+ (database-routing/with-database-routing-off+ (request/as-admin+ (queries/card-param-values card param-key search-prefix)))(catch Throwable e(throw (ex-info (.getMessage e){:card-id (u/the-id card)@@ -498,9 +517,9 @@(pr-str searched-param-slug)){:status-code 400})))(try- (binding [api/*current-user-permissions-set* (atom #{"/"})- api/*is-superuser?* true]- (queries/card-param-remapped-value card param-key value))+ (database-routing/with-database-routing-off+ (request/as-admin+ (queries/card-param-remapped-value card param-key value)))(catch Throwable e(throw (ex-info (.getMessage e){:card-id (u/the-id card)@@ -558,9 +577,9 @@;; ok, at this point we can run the query(let [merged-id-params (param-values-merged-params id->slug slug->id embedding-params slug-token-params id-query-params)](try- (binding [api/*current-user-permissions-set* (atom #{"/"})- api/*is-superuser?* true]- (parameters.dashboard/param-values dashboard searched-param-id merged-id-params prefix))+ (database-routing/with-database-routing-off+ (request/as-admin+ (parameters.dashboard/param-values dashboard searched-param-id merged-id-params prefix)))(catch Throwable e(throw (ex-info (.getMessage e){:merged-id-params merged-id-params}@@ -615,6 +634,6 @@{:status-code 400})))(let [constraints (-> (param-values-merged-params id->slug slug->id embedding-params slug-token-params {})(select-keys locked-param-ids))]- (binding [api/*current-user-permissions-set* (atom #{"/"})- api/*is-superuser?* true]- (parameters.dashboard/dashboard-param-remapped-value dashboard param-key value constraints))))))+ (database-routing/with-database-routing-off+ (request/as-admin+ (parameters.dashboard/dashboard-param-remapped-value dashboard param-key value constraints)))))))diff --git a/src/metabase/embedding_rest/api/embed.clj b/src/metabase/embedding_rest/api/embed.cljindex 895d6c4799d..33615358af4 100644--- a/src/metabase/embedding_rest/api/embed.clj+++ b/src/metabase/embedding_rest/api/embed.clj@@ -17,7 +17,6 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]- [metabase.database-routing.core :as database-routing][metabase.eid-translation.core :as eid-translation][metabase.embedding-rest.api.common :as api.embed.common][metabase.embedding.jwt :as embedding.jwt]@@ -27,7 +26,6 @@[metabase.query-processor.pivot :as qp.pivot][metabase.query-processor.schema :as qp.schema][metabase.request.core :as request]- [metabase.tiles.api :as api.tiles][metabase.util :as u][metabase.util.json :as json][metabase.util.malli :as mu]@@ -93,16 +91,15 @@(let [card-id (api.embed.common/unsigned-token->card-id unsigned-token)card (api/check-404 (t2/select-one :model/Card card-id))](api.embed.common/check-embedding-enabled-for-card card)- (database-routing/with-database-routing-off- (api.embed.common/process-query-for-card-with-params- :export-format export-format- :card card- :token-params (embedding.jwt/get-in-unsigned-token-or-throw unsigned-token [:params])- :embedding-params (:embedding_params card)- :query-params (api.embed.common/parse-query-params (dissoc query-params :format_rows :pivot_results))- :qp qp- :constraints constraints- :options options))))+ (api.embed.common/process-query-for-card-with-params+ :export-format export-format+ :card card+ :token-params (embedding.jwt/get-in-unsigned-token-or-throw unsigned-token [:params])+ :embedding-params (:embedding_params card)+ :query-params (api.embed.common/parse-query-params (dissoc query-params :format_rows :pivot_results))+ :qp qp+ :constraints constraints+ :options options)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -190,18 +187,17 @@dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))card (api/check-404 (t2/select-one :model/Card card-id))](api.embed.common/check-embedding-enabled-for-dashboard dashboard)- (database-routing/with-database-routing-off- (api.embed.common/process-query-for-dashcard- :export-format export-format- :dashboard dashboard- :dashcard dashcard- :card card- :embedding-params (:embedding_params dashboard)- :token-params (embedding.jwt/get-in-unsigned-token-or-throw unsigned-token [:params])- :query-params (api.embed.common/parse-query-params (dissoc query-params :format_rows :pivot_results))- :constraints constraints- :qp qp- :middleware middleware))))+ (api.embed.common/process-query-for-dashcard+ :export-format export-format+ :dashboard dashboard+ :dashcard dashcard+ :card card+ :embedding-params (:embedding_params dashboard)+ :token-params (embedding.jwt/get-in-unsigned-token-or-throw unsigned-token [:params])+ :query-params (api.embed.common/parse-query-params (dissoc query-params :format_rows :pivot_results))+ :constraints constraints+ :qp qp+ :middleware middleware)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -411,7 +407,7 @@lon-field (json/decode+kw lonField)](api.embed.common/check-embedding-enabled-for-card card)(request/as-admin- (api.tiles/process-tiles-query-for-card card parameters zoom x y lat-field lon-field))))+ (api.embed.common/process-tiles-query-for-card card parameters zoom x y lat-field lon-field))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happendiff --git a/src/metabase/embedding_rest/api/preview_embed.clj b/src/metabase/embedding_rest/api/preview_embed.cljindex c8e4d71b903..8f68bf9561f 100644--- a/src/metabase/embedding_rest/api/preview_embed.clj+++ b/src/metabase/embedding_rest/api/preview_embed.clj@@ -16,7 +16,6 @@[metabase.embedding.validation :as embedding.validation][metabase.query-processor.pivot :as qp.pivot][metabase.request.core :as request]- [metabase.tiles.api :as api.tiles][metabase.util.json :as json][metabase.util.malli.schema :as ms][ring.util.codec :as codec]@@ -248,7 +247,7 @@lat-field (json/decode+kw latField)lon-field (json/decode+kw lonField)](request/as-admin- (api.tiles/process-tiles-query-for-card card parameters zoom x y lat-field lon-field))))+ (api.embed.common/process-tiles-query-for-card card parameters zoom x y lat-field lon-field))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen