Skip to content

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

Guarantee correctness for the search permissions fast path (#73037)

Chris Truter23269606dfc5
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 531b535754d..0c17f844756 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1034,6 +1034,7 @@
legacy-mbql
lib
models
+ permissions
query-processor
search
sync
@@ -3392,7 +3393,7 @@
task
tracing
util}
- :model-imports #{:model/Card :model/Collection :model/Dashboard}}
+ :model-imports #{:model/Collection}}
enterprise/serialization
{:team "Graphy"
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
index 71235ab3c02..8a99eb38fd3 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
@@ -14,6 +14,7 @@
[metabase-enterprise.semantic-search.settings :as semantic-settings]
[metabase.analytics-interface.core :as analytics]
[metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
[metabase.search.config :as search.config]
[metabase.search.core :as search]
[metabase.tracing.core :as tracing]
@@ -767,42 +768,47 @@
(let [decoded (decode-pgobject pgo)]
(cond-> decoded (string? decoded) json/decode+kw)))))
-;; Search-models whose `mi/can-read?` is a pure function of `:collection_id`, which is
-;; already denormalized on the index row. Values are the Toucan model whose `can-read?`
-;; defmethod is invoked on a stub instance carrying only `:collection_id`.
-;;
-;; - "card" / "metric" / "dataset" → :model/Card
-;; - "dashboard" → :model/Dashboard (as of 20260420 this _could_ be
-;; :model/Card for additional albeit modest perf gains
-;; but choosing to not silently ride Card's semantics)
-;; - "indexed-entity" → :model/Card by design: the index row's
-;; `collection_id` is the parent Card's (denormalized
-;; via the spec's Collection join), so routing through
-;; Card short-circuits the original ModelIndex → Card
-;; resolution in `filter-can-read-indexed-entity`.
+(defn- compute-collection-id-only-search-models
+ "Compute search-models whose read perms are determined fully by their collection id."
+ []
+ ;; `search/specifications` must run before reading the registry: its `t2/resolve-model` calls load the
+ ;; model namespaces that populate it. Otherwise cold start caches an empty set for the JVM lifetime.
+ (let [specs (search/specifications)
+ registered-t2-models (perms/collection-id-only-read-models)
+ registered-search-models (set (keys (perms/collection-based-visibility-search-models)))]
+ ;; Two sources:
+ ;; (1) string-form registrations, whose spec's `:model` is a different t2-model (e.g. ModelIndex)
+ ;; and wouldn't be picked up by the filter below;
+ ;; (2) every spec whose `:model` was registered via the keyword form — `mi/can-read?` dispatches on
+ ;; the t2-model, so sibling specs like "dataset"/"metric" that share `:model/Card` are covered
+ ;; by one registration.
+ (into registered-search-models
+ (comp (filter (fn [[_ spec]] (contains? registered-t2-models (:model spec))))
+ (map key))
+ specs)))
+
(def ^:private collection-id-only-search-models
- {"card" :model/Card
- "metric" :model/Card
- "dataset" :model/Card
- "dashboard" :model/Dashboard
- "indexed-entity" :model/Card})
+ "Search-models whose read perms are determined fully by their collection id.
+ Wrapped in `delay` so the registry can populate before first read."
+ (delay (compute-collection-id-only-search-models)))
(defn- filter-read-permitted
- "Returns only those documents in `docs` whose corresponding t2 instances pass an mi/can-read? check for the bound api user."
+ "Returns the subset of `docs` whose t2 instances pass `mi/can-read?` for the current user."
[docs]
(let [timer (u/start-timer)
doc->t2-model (fn [doc] (:model (search/spec (:model doc))))
- {fast-docs true slow-docs false} (group-by #(contains? collection-id-only-search-models (:model %)) docs)
- ;; Fast path: the permission check depends only on `:collection_id`, which is already on the
- ;; index row. Dedupe by `[stub-model, collection_id]` so `can-read?` runs at most once per
- ;; (model, collection) pair instead of once per document.
- readable? (memoize
- (fn [stub-model coll-id]
- (mi/can-read? (t2/instance stub-model {:collection_id coll-id}))))
- fast-filtered (filterv (fn [doc]
- (readable? (get collection-id-only-search-models (:model doc))
- (:collection_id doc)))
- fast-docs)
+ fast-set @collection-id-only-search-models
+ {fast-docs true slow-docs false} (group-by #(contains? fast-set (:model %)) docs)
+ ;; Fast path: for models registered via `perms/define-collection-based-visibility!`, `mi/can-read?` is
+ ;; definitionally `(perms/can-read-via-parent-collection? (:collection_id instance))`, so we skip the
+ ;; t2/select and check perms straight from the denormalized `:collection_id` on the index row.
+ ;; Calling the shared helper means fast and slow paths run the same code for these models.
+ ;; Memoizing dedupes the perm check across docs that share a collection.
+ ;;
+ ;; Trade-off: the indexed `:collection_id` is eventually-consistent, so a moved/deleted row may appear
+ ;; in results until the next reindex. Click-through still enforces live perms.
+ coll-readable? (memoize perms/can-read-via-parent-collection?)
+ fast-filtered (filterv #(coll-readable? (:collection_id %)) fast-docs)
slow-t2-instances (vec
(for [[t2-model docs] (group-by doc->t2-model slow-docs)
t2-instance (t2/select t2-model :id [:in (map :id docs)])]
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj
index f2be8423cc8..455caeebce6 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj
@@ -8,11 +8,13 @@
[metabase-enterprise.semantic-search.env :as semantic.env]
[metabase-enterprise.semantic-search.index :as semantic.index]
[metabase-enterprise.semantic-search.settings :as semantic.settings]
+ [metabase-enterprise.semantic-search.spec-trace-test-util :as spec-trace]
[metabase-enterprise.semantic-search.test-util :as semantic.tu]
[metabase.analytics-interface.core :as analytics]
[metabase.api.common :as api]
[metabase.collections.models.collection :as collection]
- [metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
+ [metabase.search.core :as search]
[metabase.test :as mt]
[metabase.util :as u])
(:import
@@ -508,80 +510,125 @@
(#'semantic.index/batch-resolve-personal-owner-ids
[user1-personal-coll-id user2-sub-coll-id shared-coll-id nil]))))))))
-(deftest filter-read-permitted-indexed-entity-test
+(deftest filter-read-permitted-fast-path-test
(mt/with-premium-features #{:semantic-search}
- (testing "filter-read-permitted routes indexed-entity docs through the collection_id-only fast path"
+ (testing "filter-read-permitted routes collection-id-only models through the fast path"
(mt/with-temp [:model/Collection {readable-coll-id :id} {}
:model/Collection {unreadable-coll-id :id} {}]
- (let [indexed-entity-docs [{:id "1:123"
- :model "indexed-entity"
- :collection_id readable-coll-id}
- {:id "2:456"
- :model "indexed-entity"
- :collection_id unreadable-coll-id}
- {:id "3:789"
- :model "indexed-entity"
- :collection_id nil}]]
- (testing "keeps all entities when user has root permissions"
- (binding [api/*current-user-permissions-set* (atom #{"/"})]
- (let [result (#'semantic.index/filter-read-permitted indexed-entity-docs)]
- (is (= 3 (count result))))))
- (testing "drops all entities when user has no permissions"
- (binding [api/*current-user-permissions-set* (atom #{})]
- (let [result (#'semantic.index/filter-read-permitted indexed-entity-docs)]
- (is (= 0 (count result))))))
- (testing "keeps only entities in readable collections"
- (binding [api/*current-user-permissions-set* (atom #{(format "/collection/%d/read/" readable-coll-id)})]
- (let [result (#'semantic.index/filter-read-permitted indexed-entity-docs)]
- (is (= 1 (count result)))
- (is (= "1:123" (:id (first result)))))))
- (testing "memoizes permission check per collection_id across docs"
- (let [calls (atom 0)
- real-can-read? mi/can-read?]
- (with-redefs [mi/can-read? (fn [& args]
- (swap! calls inc)
- (apply real-can-read? args))]
- (binding [api/*current-user-permissions-set* (atom #{"/"})]
- (#'semantic.index/filter-read-permitted
- (repeat 50 {:id "1:1" :model "indexed-entity" :collection_id readable-coll-id}))
- (is (= 1 @calls) "expected one can-read? call for the single distinct collection_id")))))
- (testing "handles empty input"
- (is (= [] (#'semantic.index/filter-read-permitted [])))))))))
-
-(deftest filter-read-permitted-dispatch-test
- (mt/with-premium-features #{:semantic-search}
- (testing "fast path dispatches through the per-search-model t2 model"
- (mt/with-temp [:model/Collection {coll-id :id} {}]
- (binding [api/*current-user-permissions-set* (atom #{"/"})]
- (testing "card and dashboard in the same collection do NOT share a memo bucket"
- ;; Card dispatches through :model/Card, Dashboard through :model/Dashboard. Their
- ;; `can-read?` answers happen to agree today (both route through
- ;; `can-read-audit-helper` which ignores the model keyword for non-Collection models),
- ;; but the dispatch MUST still hit each model's own defmethod so future divergence
- ;; cannot silently ride on Card's semantics.
- (let [calls (atom 0)
- real-can-read? mi/can-read?]
- (with-redefs [mi/can-read? (fn [& args]
- (swap! calls inc)
- (apply real-can-read? args))]
- (#'semantic.index/filter-read-permitted
- [{:id 1 :model "card" :collection_id coll-id}
- {:id 2 :model "dashboard" :collection_id coll-id}])
- (is (= 2 @calls)
- "card and dashboard must dispatch separately even for the same collection_id"))))
- (testing "card and indexed-entity share the :model/Card memo bucket"
- ;; indexed-entity is deliberately routed through :model/Card — its index row's
- ;; `collection_id` is the parent Card's, denormalized at ingest time.
- (let [calls (atom 0)
- real-can-read? mi/can-read?]
- (with-redefs [mi/can-read? (fn [& args]
- (swap! calls inc)
- (apply real-can-read? args))]
+ (testing "indexed-entity docs are filtered by denormalized :collection_id"
+ (let [docs [{:id "1:123" :model "indexed-entity" :collection_id readable-coll-id}
+ {:id "2:456" :model "indexed-entity" :collection_id unreadable-coll-id}
+ {:id "3:789" :model "indexed-entity" :collection_id nil}]]
+ (testing "keeps all entities when user has root permissions"
+ (binding [api/*current-user-permissions-set* (atom #{"/"})]
+ (is (= 3 (count (#'semantic.index/filter-read-permitted docs))))))
+ (testing "drops all entities when user has no permissions"
+ (binding [api/*current-user-permissions-set* (atom #{})]
+ (is (= 0 (count (#'semantic.index/filter-read-permitted docs))))))
+ (testing "keeps only entities in readable collections"
+ (binding [api/*current-user-permissions-set* (atom #{(format "/collection/%d/read/" readable-coll-id)})]
+ (let [result (#'semantic.index/filter-read-permitted docs)]
+ (is (= 1 (count result)))
+ (is (= "1:123" (:id (first result)))))))))
+ (testing "card/metric/dataset/dashboard docs use the same fast path"
+ (doseq [model ["card" "metric" "dataset" "dashboard"]]
+ (testing (str "model=" model)
+ (let [docs [{:id 1 :model model :collection_id readable-coll-id}
+ {:id 2 :model model :collection_id unreadable-coll-id}
+ {:id 3 :model model :collection_id nil}]]
+ (binding [api/*current-user-permissions-set* (atom #{(format "/collection/%d/read/" readable-coll-id)})]
+ (let [result (#'semantic.index/filter-read-permitted docs)]
+ (is (= [1] (map :id result))
+ "only the doc whose denormalized collection_id is readable survives")))))))
+ (testing "memoizes permission check per collection_id across docs"
+ (let [calls (atom 0)
+ real-helper perms/can-read-via-parent-collection?]
+ (with-redefs [perms/can-read-via-parent-collection? (fn [& args]
+ (swap! calls inc)
+ (apply real-helper args))]
+ (binding [api/*current-user-permissions-set* (atom #{"/"})]
(#'semantic.index/filter-read-permitted
- [{:id 1 :model "card" :collection_id coll-id}
- {:id "1:99" :model "indexed-entity" :collection_id coll-id}])
- (is (= 1 @calls)
- "card and indexed-entity both dispatch through :model/Card and memoize together")))))))))
+ (repeat 50 {:id "1:1" :model "indexed-entity" :collection_id readable-coll-id}))
+ (is (= 1 @calls) "expected one can-read-via-parent-collection? call for the single distinct collection_id")))))
+ (testing "handles empty input"
+ (is (= [] (#'semantic.index/filter-read-permitted []))))))))
+
+(deftest collection-id-only-search-models-derived-correctly-test
+ (testing "derived set includes every collection-id-only search-model plus indexed-entity"
+ ;; Update the expected set when `define-collection-based-visibility!` is added to or removed from a model.
+ (is (= #{"card" "metric" "dataset" "dashboard" "indexed-entity"}
+ @@#'semantic.index/collection-id-only-search-models))))
+
+(deftest collection-based-visibility-search-model-claims-verified-test
+ (testing "every search-model registered with :denormalized-from traces to that model from :collection-id"
+ ;; Guards the `:denormalized-from` claim at `define-collection-based-visibility!` call sites against
+ ;; drift. We walk the join equality graph from `:collection-id` and require the claim to be a
+ ;; structural source — not merely any model mentioned in `:joins`. Without this, a stale claim can
+ ;; still pass if the model stays joined for an unrelated field.
+ (let [specs (search/specifications)]
+ (doseq [[search-model denormalized-from] (perms/collection-based-visibility-search-models)]
+ (testing (str search-model " traces :collection-id to " denormalized-from)
+ (let [spec (get specs search-model)
+ reached (spec-trace/trace-collection-id-source-models spec)]
+ (is (some? spec)
+ (str "no search spec registered for " (pr-str search-model)))
+ (is (contains? reached denormalized-from)
+ (str (pr-str search-model) " claims :denormalized-from " (pr-str denormalized-from)
+ " but tracing :collection-id through its join equalities only reaches "
+ reached))))))))
+
+(deftest keyword-form-derived-search-models-trace-to-own-model-test
+ (testing "every keyword-form-derived search-model denormalizes :collection_id from its own t2-model"
+ ;; The string form of `define-collection-based-visibility!` carries an explicit `:denormalized-from`
+ ;; claim verified above. The keyword form has no such claim: sibling specs like "dataset"/"metric"
+ ;; are swept into the fast path purely because their `:model` is a registered t2-model. The fast path
+ ;; checks `can-read-via-parent-collection?` against the index row's `:collection_id`, so this is only
+ ;; correct if the spec's `:collection-id` is its own collection. Assert that structurally — tracing
+ ;; `:collection-id` through join equalities must reach the spec's own registered t2-model — so a future
+ ;; sibling sourcing `:collection-id` from a join (a different collection) fails here instead of
+ ;; silently gaining incorrect read semantics.
+ (let [specs (search/specifications)
+ registered-t2-models (perms/collection-id-only-read-models)]
+ ;; Guard against a vacuous pass: if the registry is empty the `:when` filter below matches nothing
+ ;; and the only assertion never runs. A future refactor that breaks registry population should fail
+ ;; here rather than silently no-op.
+ (is (seq registered-t2-models)
+ "registry must be populated by search/specifications")
+ (doseq [[search-model spec] specs
+ :let [t2-model (:model spec)]
+ :when (contains? registered-t2-models t2-model)]
+ (testing (str search-model " traces :collection-id to its own model " t2-model)
+ (let [reached (spec-trace/trace-collection-id-source-models spec)]
+ (is (contains? reached t2-model)
+ (str (pr-str search-model) " is derived into the fast path via its registered t2-model "
+ (pr-str t2-model) " but tracing :collection-id through its join equalities only reaches "
+ reached " — its denormalized :collection_id is not its own collection"))))))))
+
+(deftest collection-id-only-search-models-cold-start-regression-test
+ (testing "derivation populates correctly even if registry is empty at first access"
+ ;; The derivation must call `search/specifications` before reading either registry — `t2/resolve-model`
+ ;; inside `specifications` loads the model namespaces that populate them.
+ ;; If the order flips, cold start caches an empty set for the JVM lifetime. Both the t2-model registry
+ ;; (card/metric/dataset/dashboard) and the search-model registry (indexed-entity) must be covered.
+ (let [real-specs (var-get #'search/specifications)
+ real-t2-registry perms/collection-id-only-read-models
+ real-search-registry perms/collection-based-visibility-search-models
+ specs-loaded? (atom false)]
+ (with-redefs [search/specifications (fn []
+ (reset! specs-loaded? true)
+ (real-specs))
+ perms/collection-id-only-read-models (fn []
+ (if @specs-loaded?
+ (real-t2-registry)
+ #{}))
+ perms/collection-based-visibility-search-models (fn []
+ (if @specs-loaded?
+ (real-search-registry)
+ {}))]
+ (let [result (#'semantic.index/compute-collection-id-only-search-models)]
+ (is (contains? result "card"))
+ (is (contains? result "dashboard"))
+ (is (contains? result "indexed-entity")))))))
(deftest to-boolean-test
(testing "to-boolean function correctly converts various input types to booleans"
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/spec_trace_test_util.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/spec_trace_test_util.clj
new file mode 100644
index 00000000000..afe77927b5d
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/spec_trace_test_util.clj
@@ -0,0 +1,65 @@
+(ns metabase-enterprise.semantic-search.spec-trace-test-util
+ "Helpers for walking `metabase.search.spec` shapes in tests — used to verify structural claims
+ like `:denormalized-from` against the actual join-equality graph of a spec."
+ (:require
+ [clojure.string :as str]
+ [metabase.search.spec :as search.spec]))
+
+(defn- join-equality-pairs
+ "Return `[col-a col-b]` for every `[:= col-a col-b]` subform of `condition` where both sides are
+ column-reference keywords. Walks through compound conditions like `[:and ...]`."
+ [condition]
+ (->> (tree-seq sequential? seq condition)
+ (filter (fn [node]
+ (and (vector? node)
+ (= := (first node))
+ (= 3 (count node))
+ (keyword? (nth node 1))
+ (keyword? (nth node 2)))))
+ (map (fn [[_ a b]] [a b]))))
+
+(defn- column-alias
+ "Extract the `:alias` from a dotted column-reference keyword like `:alias.col`. Returns nil if the
+ keyword is not in `alias.col` form."
+ [col]
+ (when (keyword? col)
+ (let [idx (str/index-of (name col) \.)]
+ (when idx
+ (keyword (subs (name col) 0 idx))))))
+
+(defn- attr-seed-columns
+ "Qualified `:alias.col` columns that `:attrs` entry `attr-key`/`attr-val` references, to seed a trace."
+ [attr-key attr-val]
+ ;; Delegate to the indexer's own extractor so the seed grammar (`true` shorthand, nested
+ ;; vector/`{:fields ...}` exprs, SQL-function/control-keyword filtering) can't drift from what the index
+ ;; reads. `find-fields-attr` yields `[alias col]` pairs (`:this` = base model); re-qualify to the
+ ;; `:alias.col` keywords used in `:joins`.
+ (into #{}
+ (map (fn [[alias col]] (keyword (str (name alias) "." (name col)))))
+ (persistent! (#'search.spec/find-fields-attr (transient []) attr-key attr-val))))
+
+(defn trace-collection-id-source-models
+ "Return t2-model keywords reachable from the spec's `:collection-id` attribute via join equalities.
+ `:this` resolves to the spec's own base model; other aliases resolve via `:joins`. A claim of
+ `:denormalized-from X` is structurally sound iff `X` is in the returned set."
+ [spec]
+ (let [seed-cols (attr-seed-columns :collection-id (get-in spec [:attrs :collection-id]))
+ joins (:joins spec)
+ alias->model (-> (into {} (map (fn [[alias [model _]]] [alias model])) joins)
+ (assoc :this (:model spec)))
+ edges (mapcat (fn [[_ [_ jcond]]] (join-equality-pairs jcond)) joins)
+ eq-map (reduce (fn [m [a b]]
+ (-> m
+ (update a (fnil conj #{}) b)
+ (update b (fnil conj #{}) a)))
+ {}
+ edges)
+ reachable (loop [visited #{}
+ queue (vec seed-cols)]
+ (if-let [col (first queue)]
+ (if (visited col)
+ (recur visited (rest queue))
+ (recur (conj visited col)
+ (into (vec (rest queue)) (eq-map col))))
+ visited))]
+ (into #{} (keep (comp alias->model column-alias)) reachable)))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/spec_trace_test_util_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/spec_trace_test_util_test.clj
new file mode 100644
index 00000000000..95ba984a554
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/spec_trace_test_util_test.clj
@@ -0,0 +1,48 @@
+(ns metabase-enterprise.semantic-search.spec-trace-test-util-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.semantic-search.spec-trace-test-util :as spec-trace]))
+
+;; Seed extraction (shorthand `true`, vector/`:case`/`:fields` expressions, control-keyword filtering) is
+;; `search.spec/find-fields-attr`'s behavior and is tested there. These tests cover this util's own logic:
+;; the join-equality graph walk, and that the two attr forms real specs use (`true` and a `:alias.col`
+;; keyword) seed it correctly.
+
+(deftest trace-reaches-every-model-on-the-collection-id-path-test
+ ;; indexed-entity shape: `:collection-id` → `:collection.id` joins to `:model.collection_id`, so both
+ ;; Collection and Card are structurally valid `:denormalized-from` claims.
+ (is (= #{:model/Collection :model/Card}
+ (spec-trace/trace-collection-id-source-models
+ {:model :model/ModelIndexValue
+ :attrs {:collection-id :collection.id}
+ :joins {:model_index [:model/ModelIndex [:= :model_index.id :this.model_index_id]]
+ :model [:model/Card [:= :model.id :model_index.model_id]]
+ :collection [:model/Collection [:= :collection.id :model.collection_id]]}}))))
+
+(deftest trace-excludes-joins-not-on-the-collection-id-path-test
+ ;; `:table` is joined for display only; models reached through joins that don't connect to the
+ ;; `:collection-id` seed must not appear.
+ (is (= #{:model/Collection :model/Base}
+ (spec-trace/trace-collection-id-source-models
+ {:model :model/Base
+ :attrs {:collection-id :collection.id}
+ :joins {:collection [:model/Collection [:= :collection.id :this.collection_id]]
+ :table [:model/Table [:= :table.id :this.table_id]]}}))))
+
+(deftest trace-walks-equalities-inside-compound-and-conditions-test
+ (is (= #{:model/Collection :model/Base}
+ (spec-trace/trace-collection-id-source-models
+ {:model :model/Base
+ :attrs {:collection-id :collection.id}
+ :joins {:collection [:model/Collection
+ [:and [:= :this.is_published true]
+ [:= :collection.id :this.collection_id]]]}}))))
+
+(deftest trace-seeds-from-true-shorthand-test
+ ;; card/dashboard shape: `:collection-id true` means `:this.collection_id`. The seed must expand the
+ ;; shorthand or the walk starts from `true` and reaches nothing.
+ (is (= #{:model/Base :model/Collection}
+ (spec-trace/trace-collection-id-source-models
+ {:model :model/Base
+ :attrs {:collection-id true}
+ :joins {:collection [:model/Collection [:= :collection.id :this.collection_id]]}}))))
diff --git a/src/metabase/dashboards/models/dashboard.clj b/src/metabase/dashboards/models/dashboard.clj
index 1f046f01fae..598779b5f13 100644
--- a/src/metabase/dashboards/models/dashboard.clj
+++ b/src/metabase/dashboards/models/dashboard.clj
@@ -58,11 +58,7 @@
([_ pk]
(mi/can-write? (t2/select-one :model/Dashboard :id pk))))
-(defmethod mi/can-read? :model/Dashboard
- ([instance]
- (perms/can-read-audit-helper :model/Dashboard instance))
- ([_ pk]
- (mi/can-read? (t2/select-one :model/Dashboard :id pk))))
+(perms/define-collection-based-visibility! :model/Dashboard)
(defmethod mi/non-timestamped-fields :model/Dashboard [_]
#{:last_viewed_at})
diff --git a/src/metabase/indexed_entities/models/model_index.clj b/src/metabase/indexed_entities/models/model_index.clj
index 239154b416a..eabacbbc1ed 100644
--- a/src/metabase/indexed_entities/models/model_index.clj
+++ b/src/metabase/indexed_entities/models/model_index.clj
@@ -8,6 +8,7 @@
[metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
[metabase.query-processor.core :as qp]
[metabase.search.core :as search]
[metabase.sync.schedules :as sync.schedules]
@@ -206,5 +207,7 @@
:model [:model/Card [:= :model.id :model_index.model_id]]
:collection [:model/Collection [:= :collection.id :model.collection_id]]}})
+(perms/define-collection-based-visibility! "indexed-entity" :denormalized-from :model/Card)
+
;; TODO resolve the toucan2 issue preventing us from using this hook
(underive :model/ModelIndexValue :hook/search-index)
diff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.clj
index 1b770465944..b83644e9906 100644
--- a/src/metabase/permissions/core.clj
+++ b/src/metabase/permissions/core.clj
@@ -83,7 +83,12 @@
[metabase.permissions.models.permissions
namespace-clause
can-read-audit-helper
+ can-read-via-parent-collection?
+ collection-based-visibility-search-models
+ collection-id-only-read-method
+ collection-id-only-read-models
current-user-has-application-permissions?
+ define-collection-based-visibility!
grant-application-permissions!
grant-collection-read-permissions!
grant-collection-readwrite-permissions!
diff --git a/src/metabase/permissions/models/permissions.clj b/src/metabase/permissions/models/permissions.clj
index 0013edfc631..d361414ac33 100644
--- a/src/metabase/permissions/models/permissions.clj
+++ b/src/metabase/permissions/models/permissions.clj
@@ -420,6 +420,20 @@
(when (and include-tenant-namespaces? (nil? namespace-val) (setting/get :use-tenants))
[:= namespace-keyword "tenant-specific"])])
+(defn can-read-via-parent-collection?
+ "Read permission for rows whose read policy is a pure function of `:collection_id` and current user perms.
+ Used by models that opt into the collection-id-only contract via [[define-collection-based-visibility!]],
+ and by semantic search's fast path; sharing this helper keeps the two paths structurally in sync.
+ Takes `coll-id` (not an instance) so the logic cannot grow a dependency on other instance fields."
+ [coll-id]
+ (and (or (premium-features/enable-audit-app?)
+ (not (and (some? coll-id) (audit/is-collection-id-audit? coll-id))))
+ (mi/current-user-has-full-permissions?
+ #{(permissions.path/collection-read-path
+ (or coll-id
+ {:metabase.collections.models.collection.root/is-root? true
+ :namespace nil}))})))
+
;;; TODO -- this is a predicate function that returns truthy or falsey, it should end in a `?` -- Cam
(mu/defn can-read-audit-helper
"Audit instances should only be readable if audit app is enabled."
@@ -434,6 +448,76 @@
:model/Collection (mi/current-user-has-full-permissions? :read instance)
(mi/current-user-has-full-permissions? (perms-objects-set-for-parent-collection instance :read)))))
+;;; ---- Collection-based visibility registration ----
+
+(defonce ^:private collection-based-visibility-registry
+ ;; Registrations from `define-collection-based-visibility!`.
+ ;; `:t2-methods` maps t2-model-kw → the installed `mi/can-read?` fn (identity-check test uses the value).
+ ;; `:search-models` maps search-model-string → claimed parent t2-model the `:collection_id` is denormalized
+ ;; from at index time. The claim is verified against the spec's joins by a contract test; see
+ ;; `metabase-enterprise.semantic-search.index-test`.
+ (atom {:t2-methods {} :search-models {}}))
+
+(defn collection-id-only-read-models
+ "Set of t2 model keywords whose `mi/can-read?` was installed via [[define-collection-based-visibility!]]."
+ []
+ (set (keys (:t2-methods @collection-based-visibility-registry))))
+
+(defn collection-id-only-read-method
+ "The `mi/can-read?` fn [[define-collection-based-visibility!]] installed for `t2-model`, or nil.
+ Exposed so identity-check tests can detect later overrides."
+ [t2-model]
+ (get-in @collection-based-visibility-registry [:t2-methods t2-model]))
+
+(defn collection-based-visibility-search-models
+ "Map of search-model-string → the claimed parent t2-model the `:collection_id` is denormalized from.
+ Registrations come from the string form of [[define-collection-based-visibility!]]."
+ []
+ (:search-models @collection-based-visibility-registry))
+
+(defn register-collection-id-only-read-method!
+ "Implementation detail of [[define-collection-based-visibility!]]. Do not call directly."
+ [t2-model method]
+ (swap! collection-based-visibility-registry assoc-in [:t2-methods t2-model] method))
+
+(defn register-collection-based-visibility-search-model!
+ "Implementation detail of [[define-collection-based-visibility!]]. Do not call directly."
+ [search-model denormalized-from]
+ (swap! collection-based-visibility-registry assoc-in [:search-models search-model] denormalized-from))
+
+(defmacro define-collection-based-visibility!
+ "Register read perms as determined fully by `:collection_id`.
+
+ Normal form — `target` is a t2-model keyword: installs `mi/can-read?` as a delegate to
+ [[can-read-via-parent-collection?]] and registers the model.
+ If a model later needs richer read perms, remove the macro call and write a plain `defmethod`.
+ The identity-check test in `metabase.permissions.models.permissions-test` will flag silent overrides.
+
+ Alternate form — `target` is a search-model string whose index-row `:collection_id` is denormalized
+ from a parent model at index time (e.g. `\"indexed-entity\"` from its parent Card).
+ No `mi/can-read?` is installed; the registration only flags the search-model for the semantic-search
+ fast path. `:denormalized-from` is required and names the parent t2-model for documentation."
+ [target & {:keys [denormalized-from]}]
+ (cond
+ (keyword? target)
+ `(do
+ (defmethod mi/can-read? ~target
+ ([instance#] (can-read-via-parent-collection? (:collection_id instance#)))
+ ([_# pk#] (mi/can-read? (t2/select-one ~target :id pk#))))
+ (register-collection-id-only-read-method! ~target (get-method mi/can-read? ~target)))
+
+ (string? target)
+ ;; Throw unconditionally rather than `assert` — assertions are elided when `*assert*` is false (AOT
+ ;; release builds), and a nil `:denormalized-from` would silently break fast-path derivation.
+ (if denormalized-from
+ `(register-collection-based-visibility-search-model! ~target ~denormalized-from)
+ (throw (IllegalArgumentException.
+ "string form of define-collection-based-visibility! requires :denormalized-from")))
+
+ :else
+ (throw (IllegalArgumentException.
+ "define-collection-based-visibility! target must be a t2-model keyword or search-model string"))))
+
; Audit permissions helper fns end
(defn revoke-application-permissions!
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index d4a9b2b9ec2..9fd9656e098 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -143,11 +143,7 @@
([_ pk]
(mi/can-write? (t2/select-one :model/Card :id pk))))
-(defmethod mi/can-read? :model/Card
- ([instance]
- (perms/can-read-audit-helper :model/Card instance))
- ([_ pk]
- (mi/can-read? (t2/select-one :model/Card :id pk))))
+(perms/define-collection-based-visibility! :model/Card)
(defn model?
"Returns true if `card` is a model."
diff --git a/src/metabase/search/core.clj b/src/metabase/search/core.clj
index 2cee1542e75..3d08756d77b 100644
--- a/src/metabase/search/core.clj
+++ b/src/metabase/search/core.clj
@@ -37,6 +37,7 @@
searchable-value-trim-sql]
[search.spec
spec
+ specifications
define-spec]
[search.util
collapse-id
diff --git a/src/metabase/search/impl.clj b/src/metabase/search/impl.clj
index 857e71da848..15e0cec657e 100644
--- a/src/metabase/search/impl.clj
+++ b/src/metabase/search/impl.clj
@@ -435,7 +435,11 @@
(:model-ancestors? search-ctx) (add-dataset-collection-hierarchy)
true (add-collection-effective-location)
true (map (partial add-can-write search-ctx))
- true (map serialize))]
+ true (map serialize)
+ ;; Realize within the enclosing tracing span so hydration and
+ ;; serialization time is attributed here rather than deferred to
+ ;; JSON encoding after the span closes.
+ true vec)]
(cond-> {:data paginated-results
:limit (:limit-int search-ctx)
:models (:models search-ctx)
diff --git a/test/metabase/permissions/models/permissions_test.clj b/test/metabase/permissions/models/permissions_test.clj
index 6a61eb8955f..bb1dd273e3f 100644
--- a/test/metabase/permissions/models/permissions_test.clj
+++ b/test/metabase/permissions/models/permissions_test.clj
@@ -1,6 +1,7 @@
(ns metabase.permissions.models.permissions-test
(:require
[clojure.test :refer :all]
+ [metabase.api.common :as api]
[metabase.audit-app.impl :as audit.impl]
[metabase.collections.models.collection :as collection]
[metabase.models.interface :as mi]
@@ -286,3 +287,30 @@
(is (true? (mi/can-create? :model/Dashboard {:collection_id (:id coll)}))))
(testing "admin can create dashboard in root collection"
(is (true? (mi/can-create? :model/Dashboard {}))))))))
+
+(deftest ^:parallel can-read-via-parent-collection?-test
+ (testing "read perm is true iff the current user has read on the parent collection"
+ (binding [api/*current-user-permissions-set* (atom #{"/"})]
+ (is (true? (boolean (perms/can-read-via-parent-collection? 42))))
+ (is (true? (boolean (perms/can-read-via-parent-collection? nil)))))
+ (binding [api/*current-user-permissions-set* (atom #{})]
+ (is (false? (boolean (perms/can-read-via-parent-collection? 42))))
+ (is (false? (boolean (perms/can-read-via-parent-collection? nil)))))
+ (binding [api/*current-user-permissions-set* (atom #{"/collection/42/read/"})]
+ (is (true? (boolean (perms/can-read-via-parent-collection? 42))))
+ (is (false? (boolean (perms/can-read-via-parent-collection? 99)))))))
+
+(deftest collection-id-only-read-methods-not-overridden-test
+ (testing "no one has redefmethod'd mi/can-read? for a model registered as collection-id-only"
+ ;; Load the model namespaces so their `define-collection-based-visibility!` calls populate the registry.
+ (require 'metabase.queries.models.card
+ 'metabase.dashboards.models.dashboard)
+ (let [registered (perms/collection-id-only-read-models)]
+ (is (seq registered))
+ (doseq [t2-model registered]
+ (is (identical? (perms/collection-id-only-read-method t2-model)
+ (get-method mi/can-read? t2-model))
+ (str t2-model ": `mi/can-read?` was overridden after "
+ "`define-collection-based-visibility!` installed it. "
+ "If this model needs richer read perms, remove the macro call so downstream consumers "
+ "(e.g., semantic search's fast path) don't assume the collection-id-only contract."))))))