Skip to content

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

Enter the metric-expansion admin context once, not once per metric (#79064)

Alexander Polyankin4eddba236df1
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj
index c975bc2adb3..66f0a40b0e2 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj
@@ -128,3 +128,43 @@
groups (dimension-group-names dims)]
(testing "dimensions from the sandboxed Venues table should be blocked"
(is (not (contains? groups "Venues")))))))))))
+
+;;; ------------------------------------------------- Running Sandboxed Metrics -------------------------------------------------
+
+(defn- venues-count-metric
+ "A `:metric` Card counting Venues, or counting `inner-metric-id` when one is given."
+ [inner-metric-id]
+ {:name (if inner-metric-id "Venues Count, Again" "Venues Count")
+ :type :metric
+ :database_id (data/id)
+ :table_id (data/id :venues)
+ :dataset_query {:database (data/id)
+ :type :query
+ :query {:source-table (data/id :venues)
+ :aggregation [(if inner-metric-id
+ [:metric inner-metric-id]
+ [:count])]}}})
+
+(deftest metric-on-metric-on-natively-sandboxed-table-test
+ (testing "A :metric defined in terms of another :metric on a natively-sandboxed table should run (#76044)"
+ ;; Metric expansion preprocesses each definition as an admin, so sandboxing leaves it alone and only the
+ ;; consuming query gets sandboxed. That elevation has to reach the nested definition too — otherwise sandboxing
+ ;; swaps the inner metric's source table for the sandbox's source card and expansion dies on "Incompatible
+ ;; metric". Nesting is what distinguishes this from the single-level case in
+ ;; `metabase-enterprise.sandbox.query-processor.middleware.sandboxing-test`.
+ (met/with-gtaps! {:gtaps {:venues {:query (mt/native-query
+ {:query "SELECT * FROM VENUES WHERE CATEGORY_ID = {{cat}}"
+ :template_tags {:cat {:name "cat"
+ :display_name "cat"
+ :type "number"
+ :required true}}})
+ :remappings {:cat ["variable" ["template-tag" "cat"]]}}}
+ :attributes {"cat" 50}}
+ (mt/with-temp [:model/Card {inner-id :id} (venues-count-metric nil)
+ :model/Card {outer-id :id} (venues-count-metric inner-id)]
+ (is (= [[10]]
+ (mt/rows (mt/user-http-request :rasta :post 202 "dataset"
+ {:database (data/id)
+ :type :query
+ :query {:source-table (data/id :venues)
+ :aggregation [[:metric outer-id]]}}))))))))
diff --git a/src/metabase/query_processor/middleware/metrics.clj b/src/metabase/query_processor/middleware/metrics.clj
index f3753f61a14..4441375ae1b 100644
--- a/src/metabase/query_processor/middleware/metrics.clj
+++ b/src/metabase/query_processor/middleware/metrics.clj
@@ -3,6 +3,7 @@
(:require
[medley.core :as m]
[metabase.analytics-interface.core :as analytics]
+ [metabase.api.common :refer [*is-superuser?*]]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.options :as lib.options]
@@ -172,32 +173,36 @@
[x]
(first (find-metric-ids x)))
+(defn- fetch-metric
+ [query card-metadata]
+ (let [metric-query (->> (:dataset-query card-metadata)
+ (lib/query query)
+ ((requiring-resolve 'metabase.query-processor.preprocess/preprocess))
+ (lib/query query)
+ metric-query-filters->aggregation)]
+ (if-let [aggregation (first (lib/aggregations metric-query))]
+ [(:id card-metadata)
+ {:query metric-query
+ ;; Aggregation inherits `:name` of original aggregation used in a metric query. The original name is added
+ ;; in `preprocess` above if metric is defined using unnamed aggregation.
+ :aggregation aggregation
+ :name (:name card-metadata)}]
+ (throw (ex-info "Source metric missing aggregation" {:source metric-query})))))
+
(defn- fetch-metrics
+ "Preprocess the definitions of `metric-ids`, keyed by metric ID.
+
+ Preprocessing happens as admin so user-context middleware leaves the definitions alone; the consuming query goes
+ through those passes itself and sandboxes the spliced result (#76044). Sandboxing and impersonation both stand down
+ for superusers, which is what `as-admin` makes us, so being one already — whether for real or inside the context an
+ enclosing metric established — means there is nothing to elevate. Entering it again would only re-read the current
+ user and hand out empty request-scoped caches."
[query metric-ids]
- (->> metric-ids
- (lib.metadata/bulk-metadata-or-throw query :metadata/card)
- (into {}
- (map (fn [card-metadata]
- ;; Preprocess the metric query as admin so user-context middleware (sandboxing,
- ;; impersonation) leaves it untouched. The outer query still goes through those passes
- ;; normally, and will sandbox the spliced result. This matches how the sandboxing
- ;; middleware preprocesses its own source query (#76044).
- (let [metric-query (request/as-admin
- (->> (:dataset-query card-metadata)
- (lib/query query)
- ((requiring-resolve 'metabase.query-processor.preprocess/preprocess))
- (lib/query query)
- metric-query-filters->aggregation))
- metric-name (:name card-metadata)]
- (if-let [aggregation (first (lib/aggregations metric-query))]
- [(:id card-metadata)
- {:query metric-query
- ;; Aggregation inherits `:name` of original aggregation used in a metric query. The original
- ;; name is added in `preprocess` above if metric is defined using unnamed aggregation.
- :aggregation aggregation
- :name metric-name}]
- (throw (ex-info "Source metric missing aggregation" {:source metric-query})))))))
- not-empty))
+ (let [cards (lib.metadata/bulk-metadata-or-throw query :metadata/card metric-ids)
+ fetch #(not-empty (into {} (map (fn [card] (fetch-metric query card))) cards))]
+ (if *is-superuser?*
+ (fetch)
+ (request/as-admin (fetch)))))
(defn- fetch-referenced-metrics
[query stage]