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
Hide dimensions and filters without access in the metric explorer (#71692)
John Swanson93db322a840e
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 67a0d60f442..b769d9fbedc 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1236,11 +1236,13 @@lib-metricmodelsparameters+ permissions+ premium-featuresquery-processorrequestserverutil}- :model-imports #{:model/Card :model/Field :model/Measure}}+ :model-imports #{:model/Card :model/Field :model/Measure :model/Table}}model-persistence{:team "Graphy"diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.cljnew file mode 100644index 00000000000..4968e0b55a9--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj@@ -0,0 +1,63 @@+(ns metabase-enterprise.sandbox.api.metric+ "Enterprise sandbox filtering for metric dimensions.+ Overrides `metabase.metrics.permissions/sandbox-restricted-fields` to restrict+ dimensions from sandboxed tables to only fields in the sandbox source card."+ (:require+ [metabase.permissions.core :as perms]+ [metabase.premium-features.core :as premium-features :refer [defenterprise]]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn- source-card-allowed-field-ids+ "Extract the set of allowed field IDs from a sandbox source card's result_metadata.+ Tries field IDs first; falls back to resolving column names against the table's fields+ (for native query source cards whose result_metadata lacks :id).+ Returns nil when result_metadata is absent (attribute-only sandbox or missing card)."+ [table-id {:keys [result_metadata]}]+ (when (seq result_metadata)+ (let [by-id (into #{} (keep u/id) result_metadata)]+ (if (seq by-id)+ by-id+ ;; Native card fallback: resolve column names → field IDs via the table+ (let [col-names (into #{} (keep :name) result_metadata)+ name->fid (when (seq col-names)+ (into {}+ (map (juxt :name :id))+ (t2/select [:model/Field :id :name]+ :table_id table-id+ :name [:in col-names])))]+ (not-empty (set (vals name->fid))))))))++(defenterprise sandbox-restricted-fields+ "For sandboxed tables, returns {table-id -> #{allowed-field-ids}} for tables with+ column-level sandbox restrictions. Tables not in the map have no column restriction.+ Returns nil if no sandboxes apply.++ Uses :feature :none so this code runs even when the :sandboxes feature is unavailable.+ When the feature is off but sandboxes are configured, returns empty sets to block all+ dimensions from sandboxed tables (fail closed). When the feature is on, resolves+ allowed fields from source card result_metadata."+ :feature :none+ [table-ids]+ (when-let [sandboxes (seq (filter #(contains? table-ids (:table_id %))+ (perms/sandboxes-for-user)))]+ (if-not (premium-features/has-feature? :sandboxes)+ ;; Feature unavailable — block all dimensions from every sandboxed table+ (into {} (map (fn [{:keys [table_id]}] [table_id #{}])) sandboxes)+ ;; Feature available — resolve allowed fields from source cards+ (let [card-ids (into #{} (keep :card_id) sandboxes)+ cards-by-id (when (seq card-ids)+ (into {}+ (map (juxt :id identity))+ (t2/select [:model/Card :id :result_metadata :card_schema]+ :id [:in card-ids])))]+ (not-empty+ (into {}+ (keep (fn [{:keys [table_id card_id]}]+ (if-not card_id+ ;; Attribute-only sandbox — no column restriction+ nil+ ;; Source-card sandbox — resolve allowed fields, or block all if unresolvable+ [table_id (or (source-card-allowed-field-ids table_id (get cards-by-id card_id))+ #{})])))+ sandboxes))))))diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.cljnew file mode 100644index 00000000000..4dcb33c8fdb--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/metric_test.clj@@ -0,0 +1,131 @@+(ns metabase-enterprise.sandbox.api.metric-test+ (:require+ [clojure.test :refer :all]+ [metabase-enterprise.sandbox.test-util :as met]+ [metabase.test :as mt]+ [metabase.test.data :as data]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++;;; ------------------------------------------------- Helpers -------------------------------------------------++(defn- metric-dimensions+ "Fetch a metric via the API and return just its dimensions."+ [user-kw metric-id]+ (:dimensions (mt/user-http-request user-kw :get 200 (str "metric/" metric-id))))++(defn- dimension-names+ "Extract the set of display-name (or name) values from a seq of dimensions."+ [dims]+ (into #{} (map #(or (:display-name %) (:name %))) dims))++(defn- dimension-group-names+ "Extract the set of group display-names from a seq of dimensions."+ [dims]+ (into #{} (map #(get-in % [:group :display-name])) dims))++;;; ------------------------------------------------- Sandbox Column Filtering Tests -------------------------------------------------++(deftest sandbox-filters-dimension-columns-test+ (testing "Sandboxed user only sees dimensions for columns allowed by the sandbox source card"+ (met/with-gtaps!+ {:gtaps {:venues {:query (data/$ids venues+ {:database (data/id)+ :type :query+ :query {:source-table $$venues+ :fields [$id $name $category_id]}})}}}+ (mt/with-temp [:model/Card metric {:name "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 [[:count]]}}}]+ (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric)))+ (let [dims (metric-dimensions :rasta (:id metric))+ dim-names (dimension-names dims)]+ (testing "should include columns from sandbox source card"+ (is (contains? dim-names "Name"))+ (is (contains? dim-names "Category ID")))+ (testing "should NOT include columns excluded from sandbox source card"+ (is (not (contains? dim-names "Price")))+ (is (not (contains? dim-names "Latitude")))))))))++(deftest native-sandbox-filters-dimension-columns-test+ (testing "Native query sandbox restricts dimensions by matching column names to field IDs"+ (met/with-gtaps!+ {:gtaps {:venues {:query (mt/native-query+ {:query "SELECT ID, NAME, CATEGORY_ID FROM VENUES"})}}}+ ;; Run the native sandbox source card to populate its result_metadata+ (let [sandbox (t2/select-one :model/Sandbox :table_id (data/id :venues))]+ (mt/user-http-request :crowberto :post 202 (str "card/" (:card_id sandbox) "/query"))+ (mt/with-temp [:model/Card metric {:name "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 [[:count]]}}}]+ (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric)))+ (let [dims (metric-dimensions :rasta (:id metric))+ dim-names (dimension-names dims)]+ (testing "should include columns from native sandbox source card"+ (is (contains? dim-names "Name"))+ (is (contains? dim-names "Category ID")))+ (testing "should NOT include columns excluded from native sandbox"+ (is (not (contains? dim-names "Price")))+ (is (not (contains? dim-names "Latitude"))))))))))++(deftest attribute-sandbox-does-not-restrict-columns-test+ (testing "Attribute-based sandbox (no source card) shows all dimension columns"+ (met/with-gtaps!+ {:gtaps {:venues {:remappings {:cat ["variable" [:field (data/id :venues :category_id) nil]]}}}+ :attributes {"cat" 50}}+ (mt/with-temp [:model/Card metric {:name "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 [[:count]]}}}]+ (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric)))+ (let [dims (metric-dimensions :rasta (:id metric))+ dim-names (dimension-names dims)]+ (testing "all columns should be visible since no column-level sandbox restriction"+ (is (contains? dim-names "Name"))+ (is (contains? dim-names "Price"))+ (is (contains? dim-names "Latitude"))))))))++(deftest sandbox-without-feature-blocks-sandboxed-table-dimensions-test+ (testing "When :sandboxes feature is unavailable but sandboxes are configured, dimensions from sandboxed tables are blocked"+ (met/with-gtaps!+ {:gtaps {:venues {:query (data/$ids venues+ {:database (data/id)+ :type :query+ :query {:source-table $$venues+ :fields [$id $name $category_id]}})}}}+ (mt/with-temp [:model/Card metric {:name "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 [[:count]]}}}]+ ;; Establish dimensions as superuser (with sandboxes feature active, as set by with-gtaps!)+ (let [all-dims (metric-dimensions :crowberto (:id metric))]+ (testing "sanity: superuser sees venues dimensions"+ (is (contains? (dimension-group-names all-dims) "Venues")))+ ;; Now disable the :sandboxes feature and fetch as rasta+ (mt/with-premium-features #{}+ (let [dims (metric-dimensions :rasta (:id metric))+ groups (dimension-group-names dims)]+ (testing "dimensions from the sandboxed Venues table should be blocked"+ (is (not (contains? groups "Venues"))))+ (testing "dimensions from non-sandboxed FK-joined tables are still visible"+ (is (contains? groups "Category"))))))))))diff --git a/src/metabase/measures/api.clj b/src/metabase/measures/api.cljindex f3f26e26431..b3a59e33db2 100644--- a/src/metabase/measures/api.clj+++ b/src/metabase/measures/api.clj@@ -75,7 +75,8 @@(mu/defn- hydrated-measure [id :- ms/PositiveInt](api/read-check (t2/select-one :model/Measure :id id))(metrics/sync-dimensions! :metadata/measure id)- (t2/hydrate (t2/select-one :model/Measure :id id) :creator))+ (-> (t2/hydrate (t2/select-one :model/Measure :id id) :creator)+ metrics/filter-dimensions-for-user))(api.macros/defendpoint :get "/:id" :- ::measure"Fetch `Measure` with ID."diff --git a/src/metabase/metrics/api.clj b/src/metabase/metrics/api.cljindex 7ba65f91f56..1e629fb2c3e 100644--- a/src/metabase/metrics/api.clj+++ b/src/metabase/metrics/api.clj@@ -7,6 +7,7 @@[metabase.lib-metric.core :as lib-metric][metabase.lib-metric.schema :as lib-metric.schema][metabase.metrics.core :as metrics]+ [metabase.metrics.permissions :as metrics.perms][metabase.query-processor.core :as qp][metabase.query-processor.streaming :as qp.streaming][metabase.request.core :as request]@@ -84,7 +85,8 @@(mu/defn- hydrated-metric [id :- ms/PositiveInt](api/read-check (t2/select-one :model/Card :id id :type "metric"))(metrics/sync-dimensions! :metadata/metric id)- (t2/select-one :model/Card :id id :type "metric"))+ (-> (t2/select-one :model/Card :id id :type "metric")+ metrics.perms/filter-dimensions-for-user))(api.macros/defendpoint :get "/:id" :- ::MetricWithDimensions"Fetch a `Metric` with ID.diff --git a/src/metabase/metrics/core.clj b/src/metabase/metrics/core.cljindex 8d98bd709fe..1bf5493b23c 100644--- a/src/metabase/metrics/core.clj+++ b/src/metabase/metrics/core.clj@@ -7,6 +7,7 @@[metabase.lib.core :as lib][metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.metrics.dimension :as metrics.dimension]+ [metabase.metrics.permissions :as metrics.perms][metabase.metrics.transforms :as metrics.transforms][metabase.util.namespaces :as shared.ns]))@@ -17,6 +18,8 @@dimension-valuesdimension-search-valuesdimension-remapped-value]+ [metrics.perms+ filter-dimensions-for-user][metrics.transformsnormalize-dimensionnormalize-target-refdiff --git a/src/metabase/metrics/permissions.clj b/src/metabase/metrics/permissions.cljnew file mode 100644index 00000000000..2b8bba9cddb--- /dev/null+++ b/src/metabase/metrics/permissions.clj@@ -0,0 +1,126 @@+(ns metabase.metrics.permissions+ "Filters dimensions and dimension-mappings by user permissions at the API boundary.+ Dimensions are persisted system-wide by `sync-dimensions!`, but returned to individual+ users filtered by:+ 1. Field visibility_type (hidden/sensitive excluded)+ 2. Table-level view-data permissions+ 3. Column-level sandbox restrictions (EE, via defenterprise)"+ (:require+ [metabase.api.common :as api]+ [metabase.permissions.core :as perms]+ [metabase.premium-features.core :refer [defenterprise]]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++;;; ------------------------------------------------- Batch Lookups -------------------------------------------------++(defn- batch-field-info+ "Batch-fetch field visibility_type and table_id for a set of field IDs.+ Returns {field-id -> {:visibility_type keyword, :table_id int}}."+ [field-ids]+ (when (seq field-ids)+ (into {}+ (map (fn [f] [(:id f) (select-keys f [:visibility_type :table_id])]))+ (t2/select [:model/Field :id :visibility_type :table_id]+ :id [:in field-ids]))))++(defn- batch-table-db-ids+ "Batch-fetch db_id for a set of table IDs.+ Returns {table-id -> db-id}."+ [table-ids]+ (when (seq table-ids)+ (into {}+ (map (fn [t] [(:id t) (:db_id t)]))+ (t2/select [:model/Table :id :db_id]+ :id [:in table-ids]))))++;;; ------------------------------------------------- Permission Predicates -------------------------------------------------++(defn- hidden-field?+ "Returns true if the field's visibility_type should be excluded from metric dimensions."+ [visibility-type]+ (contains? #{:hidden :sensitive :retired} visibility-type))++(defn- user-can-access-table?+ "Returns true if the current user has :unrestricted :perms/view-data for the given table."+ [user-id database-id table-id]+ (perms/user-has-permission-for-table? user-id :perms/view-data :unrestricted database-id table-id))++;;; ------------------------------------------------- Sandbox Extension -------------------------------------------------++(defenterprise sandbox-restricted-fields+ "For sandboxed tables, returns {table-id -> #{allowed-field-ids}}.+ Tables not in the returned map have no column restriction. nil means no sandboxes apply.+ OSS stub returns nil (fail open — :model/Sandbox not available in OSS).+ EE override uses :feature :none to fail closed when MetaStore is down."+ metabase-enterprise.sandbox.api.metric+ [_table-ids]+ nil)++;;; ------------------------------------------------- Core Filter -------------------------------------------------++(defn- target->field-id+ "Extract the integer field ID from a dimension mapping target ref.+ Returns nil if the target is not a field ref or uses a name instead of ID."+ [target]+ (when (and (vector? target)+ (= :field (first target))+ (>= (count target) 3))+ (let [id-or-name (nth target 2)]+ (when (pos-int? id-or-name)+ id-or-name))))++(defn- build-dim->field-id+ "Build a map of {dimension-id -> field-id} from dimensions and their mappings."+ [dimensions dimension-mappings]+ (let [mappings-by-dim-id (into {} (map (juxt :dimension-id identity)) dimension-mappings)]+ (into {}+ (keep (fn [dim]+ (let [field-id (or (some-> dim :sources first :field-id)+ (some-> (get mappings-by-dim-id (:id dim))+ :target+ target->field-id))]+ (when field-id+ [(:id dim) field-id]))))+ dimensions)))++(defn filter-dimensions-for-user+ "Filter dimensions and dimension_mappings on a metric, removing those the+ current user shouldn't see due to:+ 1. Field visibility_type (:hidden or :sensitive)+ 2. Table-level view-data permissions+ 3. Sandbox column restrictions (EE)++ Superusers bypass all checks. Dimensions without resolvable field IDs are+ kept (conservative fallback)."+ [{:keys [dimensions dimension_mappings] :as metric}]+ (if (or api/*is-superuser?*+ (empty? dimensions))+ metric+ (let [dim->field-id (build-dim->field-id dimensions dimension_mappings)+ all-field-ids (set (vals dim->field-id))+ field-info (batch-field-info all-field-ids)+ table-ids (into #{} (keep :table_id) (vals field-info))+ table->db (batch-table-db-ids table-ids)+ sandbox-map (sandbox-restricted-fields table-ids)+ allowed? (fn [dim]+ (let [fid (get dim->field-id (:id dim))]+ (if-not fid+ true ;; can't resolve field -> keep (conservative)+ (let [{:keys [visibility_type table_id]} (get field-info fid)+ db-id (get table->db table_id)]+ (and+ ;; not hidden/sensitive+ (not (hidden-field? visibility_type))+ ;; user has table access+ (or (nil? db-id)+ (user-can-access-table? api/*current-user-id* db-id table_id))+ ;; sandbox allows this field+ (or (nil? sandbox-map)+ (nil? (get sandbox-map table_id))+ (contains? (get sandbox-map table_id) fid)))))))+ kept-ids (into #{} (comp (filter allowed?) (map :id)) dimensions)]+ (assoc metric+ :dimensions (filterv #(contains? kept-ids (:id %)) dimensions)+ :dimension_mappings (filterv #(contains? kept-ids (:dimension-id %)) dimension_mappings)))))diff --git a/test/metabase/metrics/permissions_test.clj b/test/metabase/metrics/permissions_test.cljnew file mode 100644index 00000000000..3b270ab0b25--- /dev/null+++ b/test/metabase/metrics/permissions_test.clj@@ -0,0 +1,184 @@+(ns metabase.metrics.permissions-test+ (:require+ [clojure.test :refer :all]+ [metabase.metrics.permissions :as metrics.perms]+ [metabase.permissions.models.data-permissions :as data-perms]+ [metabase.permissions.models.permissions-group :as perms-group]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++;;; ------------------------------------------------- Helpers -------------------------------------------------++(defn- metric-dimensions+ "Fetch a metric via the API and return just its dimensions."+ [user-kw metric-id]+ (:dimensions (mt/user-http-request user-kw :get 200 (str "metric/" metric-id))))++(defn- dimension-names+ "Extract the set of display-name (or name) values from a seq of dimensions."+ [dims]+ (into #{} (map #(or (:display-name %) (:name %))) dims))++(defn- dimension-group-names+ "Extract the set of group display-names from a seq of dimensions."+ [dims]+ (into #{} (map #(get-in % [:group :display-name])) dims))++;;; ------------------------------------------------- Field Visibility Tests -------------------------------------------------++(deftest hidden-fields-are-filtered-out-test+ (testing "Dimensions based on hidden/sensitive fields are excluded from GET /api/metric/:id"+ (mt/with-temp [:model/Card metric {:name "Orders Count"+ :type :metric+ :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]+ ;; First, fetch to establish dimensions+ (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric)))+ ;; Now hide a field+ (let [tax-field-id (mt/id :orders :tax)]+ (t2/update! :model/Field tax-field-id {:visibility_type :hidden})+ (try+ (let [dims (metric-dimensions :rasta (:id metric))]+ (testing "hidden field should not appear as a dimension"+ (is (not (contains? (dimension-names dims) "Tax")))))+ (finally+ (t2/update! :model/Field tax-field-id {:visibility_type :normal})))))))++(deftest sensitive-fields-are-filtered-out-test+ (testing "Dimensions based on sensitive fields are excluded from GET /api/metric/:id"+ (mt/with-temp [:model/Card metric {:name "Orders Count"+ :type :metric+ :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]+ (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric)))+ (let [tax-field-id (mt/id :orders :tax)]+ (t2/update! :model/Field tax-field-id {:visibility_type :sensitive})+ (try+ (let [dims (metric-dimensions :rasta (:id metric))]+ (testing "sensitive field should not appear as a dimension"+ (is (not (contains? (dimension-names dims) "Tax")))))+ (finally+ (t2/update! :model/Field tax-field-id {:visibility_type :normal})))))))++(deftest normal-fields-are-included-test+ (testing "Dimensions based on normal-visibility fields are included"+ (mt/with-temp [:model/Card metric {:name "Orders Count"+ :type :metric+ :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]+ (let [dims (metric-dimensions :rasta (:id metric))]+ (testing "should have dimensions from the orders table"+ (is (seq dims))+ ;; The orders table has columns like Tax, Total, etc.+ (is (some #{"Tax"} (dimension-names dims))))))))++;;; ------------------------------------------------- Table Permission Tests -------------------------------------------------++(deftest table-permissions-filter-dimensions-test+ (testing "Dimensions from tables the user cannot access are excluded"+ ;; Orders metric has FK-joined dimensions: "Product" group and "User" group+ ;; Block access to People table and verify the "User" group disappears.+ (mt/with-temp [:model/Card metric {:name "Orders Count"+ :type :metric+ :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]+ ;; Establish dimensions as superuser first (sync happens on first read)+ (let [all-dims (metric-dimensions :crowberto (:id metric))+ all-groups (dimension-group-names all-dims)]+ (testing "sanity: superuser sees FK-joined dimensions from connected tables"+ ;; FK-joined groups use singular table display names: "Product", "User"+ (is (contains? all-groups "User") "should see User (People) group")+ (is (contains? all-groups "Product") "should see Product group"))+ ;; Block rasta's access to the People table (keep Orders + Products accessible)+ (mt/with-no-data-perms-for-all-users!+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/view-data :unrestricted)+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/create-queries :query-builder)+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :products) :perms/view-data :unrestricted)+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :products) :perms/create-queries :query-builder)+ ;; People table is BLOCKED+ (let [filtered-dims (metric-dimensions :rasta (:id metric))+ filtered-groups (dimension-group-names filtered-dims)]+ (testing "rasta should NOT see dimensions from the blocked People table"+ (is (not (contains? filtered-groups "User"))))+ (testing "rasta should still see dimensions from Orders and Products"+ (is (contains? filtered-groups "Orders"))+ (is (contains? filtered-groups "Product")))))))))++(deftest superuser-sees-all-dimensions-test+ (testing "Superuser bypasses all permission filtering"+ (mt/with-temp [:model/Card metric {:name "Orders Count"+ :type :metric+ :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]+ (mt/with-no-data-perms-for-all-users!+ ;; Even with all perms revoked for all-users group, crowberto (superuser) sees everything+ (let [dims (metric-dimensions :crowberto (:id metric))+ groups (dimension-group-names dims)]+ (testing "crowberto should see all dimensions including FK-joined tables"+ (is (seq dims))+ (is (contains? groups "Product"))+ (is (contains? groups "User"))))))))++(deftest dimension-mappings-filtered-in-lockstep-test+ (testing "dimension_mappings are filtered in lockstep with dimensions"+ (mt/with-temp [:model/Card metric {:name "Orders Count"+ :type :metric+ :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]+ ;; Establish dimensions+ (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric)))+ (mt/with-no-data-perms-for-all-users!+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/view-data :unrestricted)+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/create-queries :query-builder)+ (let [response (mt/user-http-request :rasta :get 200 (str "metric/" (:id metric)))+ dim-ids (into #{} (map :id) (:dimensions response))+ mapping-dim-ids (into #{} (map :dimension-id) (:dimension_mappings response))]+ (testing "every mapping references an existing dimension"+ (is (every? #(contains? dim-ids %) mapping-dim-ids)))+ (testing "every dimension has a mapping"+ (is (every? #(contains? mapping-dim-ids %) dim-ids))))))))++(deftest dimension-value-endpoint-rejects-filtered-dimension-test+ (testing "Dimension value endpoint returns 400 for a dimension the user can't access"+ (mt/with-temp [:model/Card metric {:name "Orders Count"+ :type :metric+ :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]+ ;; Establish dimensions as superuser+ (let [all-response (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric)))+ ;; Find a dimension from the Product group (FK-joined from Products table)+ product-dim (->> (:dimensions all-response)+ (filter #(= "Product" (get-in % [:group :display-name])))+ first)]+ (when product-dim+ ;; Block access to Products table for rasta+ (mt/with-no-data-perms-for-all-users!+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/view-data :unrestricted)+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/create-queries :query-builder)+ (testing "rasta should get 400 when requesting values for a filtered-out dimension"+ (mt/user-http-request :rasta :get 400+ (str "metric/" (:id metric)+ "/dimension/" (:id product-dim) "/values")))))))))++(deftest no-dimensions-passthrough-test+ (testing "Metric with no dimensions returns cleanly (no NPE)"+ (mt/with-temp [:model/Card metric {:name "Empty Metric"+ :type :metric+ :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})}]+ ;; Don't trigger sync — dimensions should be nil/empty+ (let [response (mt/user-http-request :rasta :get 200 (str "metric/" (:id metric)))]+ (is (contains? response :dimensions))))))++(deftest unresolvable-dimension-kept-test+ (testing "Dimensions without a resolvable field ID are conservatively kept"+ (let [fake-metric {:dimensions [{:id "resolvable" :display-name "Tax"+ :sources [{:field-id (mt/id :orders :tax)}]}+ {:id "unresolvable" :display-name "Mystery"+ :sources []}]+ :dimension_mappings [{:dimension-id "resolvable"+ :target [:field {} (mt/id :orders :tax)]}+ {:dimension-id "unresolvable"+ :target [:some-other-ref {}]}]}+ result (mt/with-test-user :rasta+ (metrics.perms/filter-dimensions-for-user fake-metric))]+ (testing "unresolvable dimension is preserved"+ (is (= #{"Tax" "Mystery"} (dimension-names (:dimensions result)))))+ (testing "both mappings are preserved"+ (is (= #{"resolvable" "unresolvable"}+ (into #{} (map :dimension-id) (:dimension_mappings result))))))))