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
Filter collection-item tables with uncorrelated subqueries (#83443)
John Swansone6dd0e1140c7
diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj b/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.cljindex 5c5977505d6..f416ea99b01 100644--- a/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj+++ b/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj@@ -38,22 +38,6 @@(when (:is_published table)(mi/current-user-has-full-permissions? (perms/perms-objects-set-for-parent-collection (:collection_id table) :read))))-(defenterprise published-table-visible-clause- "Returns a HoneySQL clause matching published tables that are readable via collection permissions."- :feature :library- [table-id-column {:keys [user-id is-superuser?]}]- [:in table-id-column- ^:allow-subquery- {:select [:id]- :from [(warehouse-schema-overlay/table-query)]- :where [:and- [:= :is_published true]- (collection/visible-collection-filter-clause- :collection_id- {}- {:current-user-id user-id- :is-superuser? is-superuser?})]}])-(defenterprise published-table-perm-grant-rows"Returns a HoneySQL SELECT producing (id, perm_type, perm_value) rows for tables that arepublished into a collection the user can read. The grant supplies `:perms/create-queriesdiff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.cljindex e65f554c25b..e9b084d4a0f 100644--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj@@ -136,3 +136,61 @@:archived false}](filter #(= table-id (:id %)) (filter #(= "table" (:model %)) items)))"User with data permissions should see published tables in root"))))))))++(deftest collection-items-metadata-table-permissions-test+ (testing "The EXISTS probe behind /items/metadata and include-available-models applies the non-admin table filter"+ (mt/with-premium-features #{:library}+ (mt/with-no-data-perms-for-all-users!+ (mt/with-temp [:model/Collection collection {:type "library-data"}+ :model/Table table {:collection_id (u/the-id collection)+ :is_published true}+ :model/Table _ {:collection_id (u/the-id collection)+ :is_published false}+ :model/PermissionsGroup {group-id :id} {}]+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)+ (perms/grant-collection-read-permissions! (perms/all-users-group) collection)+ (let [metadata-url (str "collection/" (u/the-id collection) "/items/metadata")+ items-url (str "collection/" (u/the-id collection) "/items")+ fetch (fn []+ {:metadata (mt/user-http-request :rasta :get 200 metadata-url)+ :items (mt/user-http-request :rasta :get 200 items-url+ :include-available-models true)})]+ (testing "with collection read but view-data blocked, the table is not counted"+ (data-perms/set-database-permission! group-id (mt/id) :perms/view-data :blocked)+ (data-perms/set-database-permission! group-id (mt/id) :perms/create-queries :no)+ (let [{:keys [metadata items]} (fetch)]+ (is (= {:available_models [] :total_items 0} metadata))+ (is (= [] (:available_models items)))+ (is (= [] (:data items)))))+ (testing "with collection read and view-data, the published-via-collection grant makes the table count"+ (data-perms/set-table-permission! group-id table :perms/view-data :unrestricted)+ (let [{:keys [metadata items]} (fetch)]+ (is (= {:available_models ["table"] :total_items 1} metadata))+ (is (= ["table"] (:available_models items)))+ (is (= [(u/the-id table)] (map :id (:data items))))))+ (testing "with direct query permissions as well, the table still counts exactly once"+ (data-perms/set-table-permission! group-id table :perms/create-queries :query-builder)+ (let [{:keys [metadata items]} (fetch)]+ (is (= {:available_models ["table"] :total_items 1} metadata))+ (is (= ["table"] (:available_models items)))))+ (testing "the model filter does not change what is counted"+ (is (= {:available_models ["table"] :total_items 1}+ (mt/user-http-request :rasta :get 200 metadata-url :models "table")))+ (is (= {:available_models [] :total_items 0}+ (mt/user-http-request :rasta :get 200 metadata-url :models "card")))))))+ (testing "GET /api/collection/root/items/metadata applies the same filter to published tables in the root"+ (mt/with-no-data-perms-for-all-users!+ (mt/with-temp [:model/Table table {:collection_id nil+ :is_published true}+ :model/PermissionsGroup {group-id :id} {}]+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)+ (let [fetch (fn []+ (mt/user-http-request :rasta :get 200 "collection/root/items/metadata" :models "table"))]+ (testing "with view-data blocked, no table is counted"+ (data-perms/set-database-permission! group-id (mt/id) :perms/view-data :blocked)+ (data-perms/set-database-permission! group-id (mt/id) :perms/create-queries :no)+ (is (= {:available_models [] :total_items 0} (fetch))))+ (testing "with view-data on the table, it is counted"+ (data-perms/set-table-permission! group-id table :perms/view-data :unrestricted)+ (is (= ["table"] (:available_models (fetch))))+ (is (pos? (:total_items (fetch))))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/published_tables_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/published_tables_test.cljindex 0325707e868..f631cd2f470 100644--- a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/published_tables_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/published_tables_test.clj@@ -61,28 +61,6 @@(mt/with-current-user user-id(is (false? (boolean (published-tables/can-access-via-collection? table)))))))))-(deftest published-table-visible-clause-filters-by-collection-perms-test- (testing "Returns clause that only includes published tables in readable collections"- (mt/with-premium-features #{:library}- (mt/with-temp [:model/Collection {allowed-coll-id :id} {:type "library-data"}- :model/Collection {blocked-coll-id :id} {:type "library-data"}- :model/PermissionsGroup {group-id :id} {}- :model/User {user-id :id} {}- :model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}- :model/Table {allowed-table-id :id} {:is_published true :collection_id allowed-coll-id}- :model/Table {blocked-table-id :id} {:is_published true :collection_id blocked-coll-id}- :model/Table _ {:is_published false :collection_id allowed-coll-id}]- (mt/with-no-data-perms-for-all-users!- (perms/grant-collection-read-permissions! group-id allowed-coll-id)- (perms/revoke-collection-permissions! group-id blocked-coll-id)- (perms/revoke-collection-permissions! (perms/all-users-group) blocked-coll-id)- (let [clause (published-tables/published-table-visible-clause- :id- {:user-id user-id- :is-superuser? false})]- (is (= #{allowed-table-id}- (t2/select-pks-set :model/Table {:where [:and clause [:in :id [allowed-table-id blocked-table-id]]]})))))))))-(deftest published-table-perm-grant-rows-returns-nil-without-create-queries-test(testing "Returns nil when permission-mapping doesn't include :perms/create-queries"(mt/with-premium-features #{:library}diff --git a/src/metabase/collections/children.clj b/src/metabase/collections/children.cljindex b8ae4db9d48..8129b065b31 100644--- a/src/metabase/collections/children.clj+++ b/src/metabase/collections/children.clj@@ -748,39 +748,33 @@(defmethod collection-children-query :table[_ collection {:keys [archived? pinned-state]}]- (let [user-info {:user-id api/*current-user-id*- :is-superuser? api/*is-superuser?*}- published-clause (perms/published-table-visible-clause :t.id user-info)- queryable-clause (cond-> [:or- [:in :t.id (perms/visible-table-filter-select- :id- user-info- {:perms/view-data :unrestricted- :perms/create-queries :query-builder})]]- published-clause (conj [:and- [:in :t.id (perms/visible-table-filter-select- :id- user-info- {:perms/view-data :unrestricted})]- published-clause]))]- {:select [:t.id- [:t.id :table_id]- [:t.display_name :name]- :t.description- :t.collection_id- [:t.db_id :database_id]- [[:!= :t.archived_at nil] :archived]- [(h2x/literal "table") :model]]- :from [(warehouse-schema-overlay/table-query {:alias :t})]- :where [:and- [:= :t.is_published true]- (poison-when-pinned-clause pinned-state)- (collection/visible-collection-filter-clause :t.collection_id {:cte-name :visible_collection_ids})- queryable-clause- [:= :t.collection_id (:id collection)]- (if archived?- [:!= :t.archived_at nil]- [:= :t.archived_at nil])]}))+ {:select [:t.id+ [:t.id :table_id]+ [:t.display_name :name]+ :t.description+ :t.collection_id+ [:t.db_id :database_id]+ [[:!= :t.archived_at nil] :archived]+ [(h2x/literal "table") :model]]+ :from [(warehouse-schema-overlay/table-query {:alias :t})]+ :where [:and+ [:= :t.is_published true]+ (poison-when-pinned-clause pinned-state)+ (collection/visible-collection-filter-clause :t.collection_id {:cte-name :visible_collection_ids})+ ;; The subquery form, not the CTE one: this query becomes a UNION ALL branch or an EXISTS probe, where+ ;; a CTE is not valid, and hoisting the CTE to the top level does not work either: H2 2.1.214 returns no+ ;; rows for a CTE with bound parameters referenced from inside a derived table (see the docstring).+ (perms/visible-table-filter-subquery-clause+ :t.id+ {:user-id api/*current-user-id*+ :is-superuser? api/*is-superuser?*}+ {:perms/view-data :unrestricted+ :perms/create-queries :query-builder}+ {:include-published-via-collection? true})+ [:= :t.collection_id (:id collection)]+ (if archived?+ [:!= :t.archived_at nil]+ [:= :t.archived_at nil])]})(defn- annotate-collections[parent-coll colls {:keys [show-dashboard-questions?]}]diff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.cljindex a5b46a0534e..2c45dd08947 100644--- a/src/metabase/permissions/core.clj+++ b/src/metabase/permissions/core.clj@@ -84,6 +84,7 @@visible-database-filter-selectvisible-table-filter-selectvisible-table-filter-with-cte+ visible-table-filter-subquery-clauseselect-tables-and-groups-granting-perm][metabase.permissions.models.permissionsnamespace-clause@@ -154,8 +155,7 @@can-access-via-collection?user-published-table-permissionuser-has-any-published-table-permission?- user-has-published-table-permission-for-database?- published-table-visible-clause])+ user-has-published-table-permission-for-database?])(p/import-vars [metabase.permissions.settings use-tenants])diff --git a/src/metabase/permissions/models/data_permissions/sql.clj b/src/metabase/permissions/models/data_permissions/sql.cljindex c35d1de1401..09b53b731b2 100644--- a/src/metabase/permissions/models/data_permissions/sql.clj+++ b/src/metabase/permissions/models/data_permissions/sql.clj@@ -200,13 +200,70 @@[agg-fn conditional-case])(perm-type-to-int-inline perm-type required-level)]))+(mu/defn- permitted-tables-query-parts :- [:maybe [:map+ [:branches [:sequential :map]]+ [:having :any]]]+ "The pieces of the permitted-table-ids query shared by [[visible-table-filter-with-cte]] and+ [[visible-table-filter-subquery-clause]]: the UNION ALL `:branches` collecting every permission grant that applies+ to a table, and the `:having` condition that keeps the tables whose grants satisfy `permission-mapping`. nil when+ the user sees every table: a superuser, or a data analyst checking manage-table-metadata."+ [{:keys [user-id is-superuser? is-data-analyst?] :as user-info} :- UserInfo+ permission-mapping :- PermissionMapping+ {:keys [active-only? include-published-via-collection?]} :- [:maybe VisibleTableFilterWithCteOptions]]+ (when-not (or is-superuser?+ (and is-data-analyst?+ (contains? permission-mapping :perms/manage-table-metadata)))+ (let [perm-types (keys permission-mapping)+ perm-type-filter (into [:or]+ (map (fn [pt] [:= :dp.perm_type (h2x/literal pt)])+ perm-types))+ having-conditions (into [:and]+ (map (fn [[perm-type perm-level]]+ (let [[level most-or-least] (if (sequential? perm-level)+ perm-level+ [perm-level :least])]+ (permission-type-having-clause perm-type level most-or-least)))+ permission-mapping))+ user-groups-clause (user-in-group-clause user-id)+ published-grant-rows (when include-published-via-collection?+ (published-tables/published-table-perm-grant-rows+ user-info perm-types (boolean active-only?)))+ active-clause (when active-only? [:= :mt.active true])]+ {:branches (cond-> [;; Table-level permissions (direct grant to table)+ ^:allow-subquery+ {:select [:mt.id :dp.perm_type :dp.perm_value]+ :from [[:data_permissions :dp]]+ :join [(table-source) [:= :mt.id :dp.table_id]]+ :where (into [:and+ [:not= :dp.table_id nil]+ user-groups-clause+ perm-type-filter]+ (when active-clause [active-clause]))}+ ;; Database-level permissions (applies to all tables in db)+ ^:allow-subquery+ {:select [:mt.id :dp.perm_type :dp.perm_value]+ :from [[:data_permissions :dp]]+ :join [(table-source) [:= :mt.db_id :dp.db_id]]+ :where (into [:and+ [:= :dp.table_id nil]+ user-groups-clause+ perm-type-filter]+ (when active-clause [active-clause]))}]+ published-grant-rows (conj published-grant-rows))+ :having having-conditions})))++(def ^:private every-table-clause+ "The filter for a user who sees every table."+ [:= [:inline 1] [:inline 1]])+(mu/defn visible-table-filter-with-cte"Returns a map with :with (CTE definitions) and :clause (WHERE clause fragment) for filteringtables visible to the user. Uses a CTE to compute permitted table IDs once rather than usingcorrelated subqueries, which provides better performance for large numbers of tables.The returned map can be merged into a query by adding :with to the query's :with vector- and using :clause in the WHERE clause.+ and using :clause in the WHERE clause. See [[visible-table-filter-subquery-clause]] when the+ filter has to live inside a derived table or a UNION ALL branch.Uses UNION ALL to separate table-level and database-level permission lookups, avoidinginefficient BitmapOr scans that occur with OR joins.@@ -217,63 +274,45 @@published tables in collections the user can read as a source of `:perms/create-queries:query-builder` grants by adding a third UNION ALL branch to the table_permissions CTE.View-data is intentionally not synthesized; it must still come from real data_permissions."- [column-or-exp :- ColumnOrExp- {:keys [user-id is-superuser? is-data-analyst?] :as user-info} :- UserInfo- permission-mapping :- PermissionMapping- & [{:keys [active-only? include-published-via-collection?]- :or {active-only? false include-published-via-collection? false}}] :- [:* VisibleTableFilterWithCteOptions]]- ;; Superusers see all tables. Data analysts see all tables when checking manage-table-metadata.- (if (or is-superuser?- (and is-data-analyst?- (contains? permission-mapping :perms/manage-table-metadata)))- {:clause [:= [:inline 1] [:inline 1]]}- (let [perm-types (keys permission-mapping)- perm-type-filter (into [:or]- (map (fn [pt] [:= :dp.perm_type (h2x/literal pt)])- perm-types))- having-conditions (into [:and]- (map (fn [[perm-type perm-level]]- (let [[level most-or-least] (if (sequential? perm-level)- perm-level- [perm-level :least])]- (permission-type-having-clause perm-type level most-or-least)))- permission-mapping))- user-groups-clause (user-in-group-clause user-id)- published-grant-rows (when include-published-via-collection?- (published-tables/published-table-perm-grant-rows- user-info perm-types active-only?))- active-clause (when active-only? [:= :mt.active true])- permission-branches (cond-> [;; Table-level permissions (direct grant to table)- ^:allow-subquery- {:select [:mt.id :dp.perm_type :dp.perm_value]- :from [[:data_permissions :dp]]- :join [(table-source) [:= :mt.id :dp.table_id]]- :where (into [:and- [:not= :dp.table_id nil]- user-groups-clause- perm-type-filter]- (when active-clause [active-clause]))}- ;; Database-level permissions (applies to all tables in db)- ^:allow-subquery- {:select [:mt.id :dp.perm_type :dp.perm_value]- :from [[:data_permissions :dp]]- :join [(table-source) [:= :mt.db_id :dp.db_id]]- :where (into [:and- [:= :dp.table_id nil]- user-groups-clause- perm-type-filter]- (when active-clause [active-clause]))}]- published-grant-rows (conj published-grant-rows))]- {:with [;; First CTE: collect all permission grants that apply to each table- [:table_permissions ^:allow-subquery {:union-all permission-branches}]- ;; Second CTE: aggregate and filter by permission requirements- [:permitted_tables- ^:allow-subquery- {:select [:dp.id]- :from [[:table_permissions :dp]]- :group-by [:dp.id]- :having having-conditions}]]- :clause [:in column-or-exp ^:allow-subquery {:select [:id] :from [:permitted_tables]}]})))+ [column-or-exp :- ColumnOrExp+ user-info :- UserInfo+ permission-mapping :- PermissionMapping+ & [opts] :- [:* VisibleTableFilterWithCteOptions]]+ (if-let [{:keys [branches having]} (permitted-tables-query-parts user-info permission-mapping opts)]+ {:with [;; First CTE: collect all permission grants that apply to each table+ [:table_permissions ^:allow-subquery {:union-all branches}]+ ;; Second CTE: aggregate and filter by permission requirements+ [:permitted_tables+ ^:allow-subquery+ {:select [:dp.id]+ :from [[:table_permissions :dp]]+ :group-by [:dp.id]+ :having having}]]+ :clause [:in column-or-exp ^:allow-subquery {:select [:id] :from [:permitted_tables]}]}+ ;; Superusers see all tables. Data analysts see all tables when checking manage-table-metadata.+ {:clause every-table-clause}))++(mu/defn visible-table-filter-subquery-clause+ "The filter of [[visible-table-filter-with-cte]] as one WHERE clause, with the permitted-table-ids query inlined+ as an uncorrelated subquery instead of CTEs. Use this where a CTE is not valid, such as a UNION ALL branch or an+ EXISTS probe. The subquery is uncorrelated, so the app DB still evaluates it once per statement.++ Hoisting the CTEs to the top level of the statement does not work on H2 2.1.214, the pinned app DB version: a+ non-recursive CTE that contains bound parameters (here, the perm_value strings in the HAVING) returns no rows+ when it is referenced from inside a derived table. H2 fixed this in 2.3.230, but that version cannot open a+ 2.1.214 database file, so upgrading is not a quick fix.++ Takes the same options as [[visible-table-filter-with-cte]]."+ [column-or-exp :- ColumnOrExp+ user-info :- UserInfo+ permission-mapping :- PermissionMapping+ & [opts] :- [:* VisibleTableFilterWithCteOptions]]+ (if-let [{:keys [branches having]} (permitted-tables-query-parts user-info permission-mapping opts)]+ [:in column-or-exp ^:allow-subquery {:select [:dp.id]+ :from [[^:allow-subquery {:union-all branches} :dp]]+ :group-by [:dp.id]+ :having having}]+ every-table-clause))(mu/defn select-tables-and-groups-granting-perm"Selects table.id and the group.id of all permissions groups that give the provided user the provided permission level or adiff --git a/src/metabase/permissions/published_tables.clj b/src/metabase/permissions/published_tables.cljindex a9e20646827..bf70810edbf 100644--- a/src/metabase/permissions/published_tables.clj+++ b/src/metabase/permissions/published_tables.clj@@ -38,13 +38,6 @@[_table]false)-(defenterprise published-table-visible-clause- "Returns a HoneySQL clause for published tables visible via collection permissions.- OSS implementation returns nil."- metabase-enterprise.data-studio.permissions.published-tables- [_table-id-column _user-info]- nil)-(defenterprise published-table-perm-grant-rows"Returns a HoneySQL SELECT producing (id, perm_type, perm_value) rows representing the permissiongrants that published+visible-collection tables provide. Used as a UNION ALL branch in thediff --git a/test/metabase/permissions/models/data_permissions/sql_test.clj b/test/metabase/permissions/models/data_permissions/sql_test.cljindex 0e5162247bb..3d9d009934b 100644--- a/test/metabase/permissions/models/data_permissions/sql_test.clj+++ b/test/metabase/permissions/models/data_permissions/sql_test.clj@@ -203,6 +203,60 @@(is (some #(= (:id %) (:id active-table)) results))(is (not (some #(= (:id %) (:id inactive-table)) results)))))))))+(deftest visible-table-filter-subquery-clause-test+ (testing "visible-table-filter-subquery-clause selects the same tables as visible-table-filter-with-cte"+ (mt/with-temp [:model/Database db {}+ :model/Table granted-table {:db_id (:id db) :active true}+ :model/Table inactive-table {:db_id (:id db) :active false}+ :model/Table ungranted-table {:db_id (:id db) :active true}+ :model/PermissionsGroup group {}+ :model/User user {}+ :model/PermissionsGroupMembership _ {:user_id (:id user) :group_id (:id group)}]+ ;; drop the default grants every group, All Users included, gets on a new database: only `group` grants anything+ (t2/delete! :model/DataPermissions :db_id (:id db))+ (perms/set-database-permission! (:id group) (:id db) :perms/view-data :unrestricted)+ (perms/set-database-permission! (:id group) (:id db) :perms/create-queries :no)+ (perms/set-table-permission! (:id group) granted-table :perms/create-queries :query-builder)+ (perms/set-table-permission! (:id group) inactive-table :perms/create-queries :query-builder)+ (let [user-info {:user-id (:id user) :is-superuser? false}+ permission-mapping {:perms/view-data :unrestricted+ :perms/create-queries :query-builder}+ db-tables (fn [query]+ (t2/select-pks-set :model/Table+ (update query :where (fn [w] [:and [:= :db_id (:id db)] w]))))+ cte-tables (fn [& opts]+ (let [{:keys [with clause]} (apply sql/visible-table-filter-with-cte+ :id user-info permission-mapping opts)]+ (db-tables {:with with :where clause})))+ subquery-tables (fn [& opts]+ (db-tables {:where (apply sql/visible-table-filter-subquery-clause+ :id user-info permission-mapping opts)}))]+ (testing "with the default options"+ (is (= #{(:id granted-table) (:id inactive-table)}+ (cte-tables)+ (subquery-tables))))+ (testing "with active-only?"+ (is (= #{(:id granted-table)}+ (cte-tables {:active-only? true})+ (subquery-tables {:active-only? true}))))+ (testing "from inside a derived table, where a CTE cannot go"+ (is (= #{(:id granted-table)}+ (t2/select-pks-set :model/Table+ {:select [:x.id]+ :from [[^:allow-subquery+ {:select [:id]+ :from [:metabase_table]+ :where [:and+ [:= :db_id (:id db)]+ [:= :active true]+ (sql/visible-table-filter-subquery-clause+ :id user-info permission-mapping)]}+ :x]]}))))+ (testing "a superuser gets a clause that keeps every table"+ (is (= #{(:id granted-table) (:id inactive-table) (:id ungranted-table)}+ (db-tables {:where (sql/visible-table-filter-subquery-clause+ :id (assoc user-info :is-superuser? true) permission-mapping)}))))))))+(deftest visible-table-filter-select-include-inactive-test(testing "visible-table-filter-select respects active-only? option"(mt/with-temp [:model/Database db {}