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
Make the library index's authorization contract explicit (#78897)
Chris Truter113f912ad269
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex 6c1f7a52e9b..92614612de5 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -300,7 +300,10 @@metabase.query-processor.util/normalize-token {:namespaces ["metabase.*"]}}}:discouraged-var- {clojure.core/print {:message "Use metabase.util.log instead of clojure.core/print"}+ {metabase-enterprise.entity-retrieval.core/search-unfiltered {:message "Permission bypass risk: library-index hits are unfiltered — resolve each entity and drop what the current user can't read"}+ metabase.entity-retrieval.core/search-unfiltered {:message "Permission bypass risk: library-index hits are unfiltered — resolve each entity and drop what the current user can't read"}+ metabase.entity-retrieval.mirror/search-unfiltered {:message "Permission bypass risk: library-index hits are unfiltered — resolve each entity and drop what the current user can't read"}+ clojure.core/print {:message "Use metabase.util.log instead of clojure.core/print"}clojure.core/println {:message "Use metabase.util.log instead of clojure.core/println"}clojure.core/printf {:message "Use metabase.util.log instead of clojure.core/printf"}clojure.core/prn {:message "Use metabase.util.log instead of clojure.core/prn"}diff --git a/.clj-kondo/ratchets.edn b/.clj-kondo/ratchets.ednindex b20b8362c9e..96d3623f30e 100644--- a/.clj-kondo/ratchets.edn+++ b/.clj-kondo/ratchets.edn@@ -13,7 +13,7 @@:deprecated-var 81:discouraged-java-method 3:discouraged-namespace 80- :discouraged-var 100+ :discouraged-var 106:equals-true 1:main-without-gen-class 1:metabase/defsetting-namespace 7diff --git a/enterprise/backend/src/metabase_enterprise/entity_retrieval/core.clj b/enterprise/backend/src/metabase_enterprise/entity_retrieval/core.cljindex de24b7ffa28..c4e14f6a3ab 100644--- a/enterprise/backend/src/metabase_enterprise/entity_retrieval/core.clj+++ b/enterprise/backend/src/metabase_enterprise/entity_retrieval/core.clj@@ -373,12 +373,15 @@(format "WHEN doc_type = '%s' THEN %s" (name k) w)))](format "(%s) - (CASE %s ELSE 0.0 END)" distance-expr cases)))-(defenterprise search+(defenterprise search-unfiltered"Find the library-entity documents best matching `user-search-prompt`, up to `limit`, ranked by ablended score (cosine similarity plus a slight doc_type bump).Each result is shaped `{:entity {:model :id} :doc_type :doc_text :score}`, best score first; the callerdedupes the (many-per-entity) docs down to distinct entities.- Returns [] when the pgvector store is unconfigured."+ Returns [] when the pgvector store is unconfigured.++ Hits are not permission-filtered — see [[metabase.entity-retrieval.mirror/search-unfiltered]] for what a+ caller owes the current user.":feature :library-retrieval[user-search-prompt limit](if-not (available?)diff --git a/enterprise/backend/test/metabase_enterprise/entity_retrieval/appdb_mode_test.clj b/enterprise/backend/test/metabase_enterprise/entity_retrieval/appdb_mode_test.cljindex 13fd354f896..b098bef3d6d 100644--- a/enterprise/backend/test/metabase_enterprise/entity_retrieval/appdb_mode_test.clj+++ b/enterprise/backend/test/metabase_enterprise/entity_retrieval/appdb_mode_test.clj@@ -134,7 +134,9 @@(is (= public-before (tables-in-schema app-db "public"))))(testing "retrieval round-trips through the app-db pool"(is (= [{:model "table" :id table-id}]- (->> (entity-retrieval.core/search "puppy" 5)+ ;; Index plumbing, no user in the loop — filtering is tested at the tool.+ #_{:clj-kondo/ignore [:discouraged-var]}+ (->> (entity-retrieval.core/search-unfiltered "puppy" 5)(map :entity)distinctvec))))diff --git a/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj b/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.cljindex d6a56faeb91..6966c4046d1 100644--- a/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj+++ b/enterprise/backend/test/metabase_enterprise/entity_retrieval/core_test.clj@@ -22,6 +22,15 @@(defn- approx [target] #(< (abs (- (double %) (double target))) 1e-9))+(defn- search-unfiltered*+ "Raw index hits, for the availability, ranking, and vector-compatibility assertions below.+ These are index-plumbing tests with no user in the loop; the filtering that production callers owe is+ tested with the Metabot tool."+ [query limit]+ ;; No user in the loop: these assertions read scores and doc text that never leave the test process.+ #_{:clj-kondo/ignore [:discouraged-var]}+ (mirror/search-unfiltered query limit))+(deftest score-shape-matches-regular-search-test(let [score (var-get #'entity-retrieval.core/score)](testing "weighted-scorer breakdown: similarity factor + doc_type bump + total_score"@@ -44,7 +53,7 @@;; write-path nudge no-ops rather than throwing.(mt/with-premium-features #{:library :library-retrieval}(with-redefs [semantic.db.datasource/db-url nil]- (is (= [] (mirror/search "anything" 10)))+ (is (= [] (search-unfiltered* "anything" 10)))(is (nil? (mirror/request-entity-sync! "table" 1)))))))(deftest targeted-drain-reconciles-each-dirty-entity-test@@ -156,10 +165,10 @@(with-redefs [semantic.db.datasource/db-url nil](mt/with-dynamic-fn-redefs [semantic.db.datasource/pgvector-mode (constantly :app-db)](mt/with-premium-features #{:library :library-retrieval}- (with-redefs [entity-retrieval.core/app-db-schema-usable? (constantly false)]+ (mt/with-dynamic-fn-redefs [entity-retrieval.core/app-db-schema-usable? (constantly false)](is (false? (entity-retrieval.core/available?))"a role that can use semantic_search but cannot create library_retrieval is not ready"))- (with-redefs [entity-retrieval.core/app-db-schema-usable? (constantly true)]+ (mt/with-dynamic-fn-redefs [entity-retrieval.core/app-db-schema-usable? (constantly true)](is (true? (entity-retrieval.core/available?))))))))(testing "a dedicated store needs no app-db schema check"(with-redefs [semantic.db.datasource/db-url "jdbc:postgresql://stub"@@ -316,7 +325,7 @@(testing "the nearer table ranks first; each hit carries the entity ref + matched doc"(is (=? [{:entity {:model "table" :id near-id} :doc_type "name" :doc_text "near"}{:entity {:model "table" :id far-id}}]- (mirror/search q 10))))+ (search-unfiltered* q 10))))(finally(jdbc/execute! ds [(str "DROP TABLE IF EXISTS "(index-table/vectors-table) ", "@@ -413,7 +422,8 @@(reconcile/reconcile! ds (constantly semantic.tu/mock-embedding-model));; raw NN would tie both at distance 0; the 0.02 vs 0.01 doc_type bump puts alpha's name first.(is (= [[alpha "name"] [beta "synonym"]]- (mapv (juxt (comp :id :entity) :doc_type) (take 2 (mirror/search q 10)))))+ (mapv (juxt (comp :id :entity) :doc_type)+ (take 2 (search-unfiltered* q 10)))))(finally(jdbc/execute! ds [(str "DROP TABLE IF EXISTS "(index-table/vectors-table) ", "@@ -434,14 +444,20 @@(mt/with-temp [:model/Collection {lib-id :id} {:type "library" :location "/"}:model/Collection {data-id :id} {:type "library-data" :location (str "/" lib-id "/")}:model/Database {db-id :id} {}- :model/Table {_t :id} {:db_id db-id :collection_id data-id :is_published true+ :model/Table {table-id :id} {:db_id db-id :collection_id data-id :is_published true:active true :name "orders" :display_name "orders"}](try(semantic.tu/with-mock-embeddings {"orders" [1.0 0.0 0.0 0.0]}(reconcile/reconcile! ds (constantly semantic.tu/mock-embedding-model)))- ;; a dim-1 query vector against the dim-4 index column -> pgvector SQLState 22000 -> degrade to []- (semantic.tu/with-mock-embeddings {"q" [1.0]}- (is (= [] (entity-retrieval.core/search "q" 10))))+ ;; Every entry point here is a defenterprise dispatcher that answers [] in OSS, so pair the+ ;; degrade assertion with a control: an unrun query and a degraded one both look like [].+ #_{:clj-kondo/ignore [:discouraged-var]}+ (semantic.tu/with-mock-embeddings {"orders" [1.0 0.0 0.0 0.0] "q" [1.0]}+ (is (=? [{:model "table" :id table-id}]+ (distinct (map :entity (entity-retrieval.core/search-unfiltered "orders" 10))))+ "the query really runs, so the [] below is the degrade path and not a fallback")+ ;; a dim-1 query vector against the dim-4 index column -> pgvector SQLState 22000+ (is (= [] (entity-retrieval.core/search-unfiltered "q" 10))))(finally(jdbc/execute! ds [(str "DROP TABLE IF EXISTS \"" (index-table/vectors-table)"\", \"" (index-table/meta-table) "\"")])))))))))))diff --git a/src/metabase/entity_retrieval/core.clj b/src/metabase/entity_retrieval/core.cljindex 155c44f70b5..e99b51101d3 100644--- a/src/metabase/entity_retrieval/core.clj+++ b/src/metabase/entity_retrieval/core.clj@@ -3,8 +3,12 @@The library entity index is a pgvector index of every library entity's name/description plus its OSI`ai_context` synonyms/examples (see [[metabase.osi.models.osi-ai-context]]).- [[search]] matches a natural-language request against it by vector similarity (enterprise; returns []- in OSS). [[ai-context-instructions]] reads curator instructions live from the appdb."+ [[search-unfiltered]] matches a natural-language request against it by vector similarity (enterprise;+ returns [] in OSS). [[ai-context-instructions]] reads curator instructions live from the appdb.++ The index is user-agnostic, so [[search-unfiltered]] hits are not permission-filtered. A caller that+ returns anything derived from them must first resolve each entity against the appdb and keep only the ones+ the current user can read."(:require[clojure.string :as str][metabase.entity-retrieval.mirror]@@ -13,12 +17,14 @@(comment metabase.entity-retrieval.mirror/keep-me)+;; Re-exporting the var is not raw access: this namespace only bridges OSS/EE, and never reads a result.+#_{:clj-kondo/ignore [:discouraged-var]}(p/import-vars[metabase.entity-retrieval.mirrorentity-retrieval-available?force-reconcile!library-entity-keys- search])+ search-unfiltered])(def card-entity-types"The real entity_type strings the CRUD and tool APIs speak that all denote a Card: `question`/`metric`/diff --git a/src/metabase/entity_retrieval/mirror.clj b/src/metabase/entity_retrieval/mirror.cljindex 6664b9d3f11..1e8a83b27ad 100644--- a/src/metabase/entity_retrieval/mirror.clj+++ b/src/metabase/entity_retrieval/mirror.clj@@ -33,10 +33,14 @@[]nil)-(defenterprise search+(defenterprise search-unfiltered"Similarity-search the library entity index for the documents nearest `user-search-prompt`.Returns up to `limit` matches shaped `{:entity {:model :id} :doc_type :doc_text :score}`,- best score first; [] in OSS or when no pgvector store is configured."+ best score first; [] in OSS or when no pgvector store is configured.++ The index is user-agnostic, so a hit's names, descriptions, synonyms, and examples may belong to an entity+ the current user cannot read. Anything user-facing must first resolve each entity against the appdb, keep+ only the readable ones, and drop hits that no longer resolve."metabase-enterprise.entity-retrieval.core[_user-search-prompt _limit][])diff --git a/src/metabase/metabot/tools/entity_retrieval.clj b/src/metabase/metabot/tools/entity_retrieval.cljindex 835e7fec4ec..5df6e838bb8 100644--- a/src/metabase/metabot/tools/entity_retrieval.clj+++ b/src/metabase/metabot/tools/entity_retrieval.clj@@ -85,13 +85,16 @@[#{} []])second))+;; The one production read of the raw index — hence the lint exemption. Every field of every hit either is+;; dropped here or survives the hydration below, which keeps only entities the current user can read.+#_{:clj-kondo/ignore [:discouraged-var]}(defn- build-matches"Fetch, dedupe to distinct entities, hydrate each match's entity ref into a full search record, andreturn the top `n` the current user can read.Each match: `{:doc_type :matched_text :usage_instructions :score :similarity :weak? :entity hydrated-hit}`."[user-search-prompt n]- (let [raw (entity-retrieval/search- user-search-prompt (min over-fetch-cap (* over-fetch-factor n)))+ (let [fetch-n (min over-fetch-cap (* over-fetch-factor n))+ raw (entity-retrieval/search-unfiltered user-search-prompt fetch-n)deduped (dedupe-by-entity raw)refs (distinct (map :entity deduped));; Hydration permission-filters (entity-refs->search-results drops entities the user can't read),diff --git a/test/metabase/metabot/tools/entity_retrieval_test.clj b/test/metabase/metabot/tools/entity_retrieval_test.cljindex 43c05126e81..1fd70c42004 100644--- a/test/metabase/metabot/tools/entity_retrieval_test.clj+++ b/test/metabase/metabot/tools/entity_retrieval_test.clj@@ -9,6 +9,15 @@(set! *warn-on-reflection* true)+;; Stubbing the raw index is the only way to hand the tool a hit for an entity the user can't read.+#_{:clj-kondo/ignore [:discouraged-var]}+(defmacro ^:private with-unfiltered-search+ "Run `body` with the index search stubbed to `search-fn`, so a test can hand the tool synthetic hits — the+ only way to check what it refuses to pass on."+ [search-fn & body]+ `(mt/with-dynamic-fn-redefs [cs.core/search-unfiltered ~search-fn]+ ~@body))+(deftest tool-shape-oss-fallback-test(testing "without the library-retrieval feature the tool returns the standard empty result shape";; Pin the feature off so the defenterprise call takes its OSS fallback regardless of any ambient@@ -39,13 +48,46 @@:instructions "":score {:total_score (- 1.0 (/ id 10.0)):scores [{:name :similarity :score 0.8}]}}))]- (mt/with-dynamic-fn-redefs [cs.core/search (fn [_ _] raw)- ;; entity 1 (the top hit) is unreadable → dropped during hydration- tools.search/entity-refs->search-results- (fn [refs] (for [{:keys [model id]} refs :when (not= 1 id)]- {:type model :id id :name (str "e" id)}))]- (testing "asking for 2 returns the 2 readable entities (2 and 3), not just the 1 below the old top-2 cut"- (is (= [2 3] (mapv (comp :id :entity) (build-matches "q" 2)))))))))+ (with-unfiltered-search (fn [_ _] raw)+ (mt/with-dynamic-fn-redefs [;; entity 1 (the top hit) is unreadable → dropped during hydration+ tools.search/entity-refs->search-results+ (fn [refs] (for [{:keys [model id]} refs :when (not= 1 id)]+ {:type model :id id :name (str "e" id)}))+ ;; stub the appdb lookups: this test is about candidate order, not+ ;; instructions or library membership+ cs.core/ai-context-instructions (constantly {})+ cs.core/library-entity-keys (constantly nil)]+ (testing "asking for 2 returns the 2 readable entities (2 and 3), not just the 1 below the old top-2 cut"+ (is (= [2 3] (mapv (comp :id :entity) (build-matches "q" 2))))))))))++(deftest tool-never-exposes-unreadable-index-documents-test+ (testing "neither output channel carries index text for an entity the current user can't read"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Card {secret-id :id}+ {:name "Secret Card" :type :model :collection_id coll-id+ :database_id (mt/id) :table_id (mt/id :orders)+ :dataset_query {:database (mt/id) :type :query+ :query {:source-table (mt/id :orders)}}}]+ (let [sentinel "UNREADABLE_INDEX_SENTINEL"+ raw [{:entity {:model "model" :id secret-id}+ :doc_type "description"+ :doc_text sentinel+ :score {:total_score 0.9+ :scores [{:name :similarity :score 0.9}]}}]+ search! #(entity-retrieval/retrieve-library-entities-tool+ {:user_search_prompt "secret"})]+ (with-unfiltered-search (fn [_ _] raw)+ (mt/with-dynamic-fn-redefs+ [cs.core/library-entity-keys (constantly #{["model" secret-id]})]+ (testing "a user who can read the card does get the match, so the check below isn't vacuous"+ (mt/with-test-user :crowberto+ (is (str/includes? (pr-str (search!)) sentinel))))+ (testing "a user without collection access receives neither the entity nor its matched document"+ (mt/with-test-user :rasta+ (let [result (search!)]+ (is (= [] (get-in result [:structured-output :data])))+ (is (not (str/includes? (pr-str result) sentinel)))))))))))))(deftest match->xml-locale-independent-test(testing "score/similarity render with a '.' decimal separator even under a comma-decimal default locale"