Skip to content

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

Sandboxing middleware => Lib (#63321)

Cam Sauleecf97f0775c
diff --git a/deps.edn b/deps.edn
index 4025ebd94cd..da55711562d 100644
--- a/deps.edn
+++ b/deps.edn
@@ -846,7 +846,7 @@
metabase.driver.sql.query-processor-test
metabase-enterprise.advanced-permissions.models.permissions.block-permissions-test
metabase-enterprise.advanced-permissions.query-processor.middleware.permissions-test
- metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test]}}
+ metabase-enterprise.sandbox.query-processor.middleware.sandboxing-test]}}
;; test the notification system
;; clj -X:dev:ee:ee-dev:test:test/notification
@@ -866,7 +866,7 @@
metabase.driver.sql.query-processor-test
metabase-enterprise.advanced-permissions.models.permissions.block-permissions-test
metabase-enterprise.advanced-permissions.query-processor.middleware.permissions-test
- metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test]}}
+ metabase-enterprise.sandbox.query-processor.middleware.sandboxing-test]}}
;; test search-related stuff.
;;
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj
index 266ff9fe518..d34407fdff0 100644
--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj
+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj
@@ -163,7 +163,7 @@
:group_id group-id)
(and
(premium-features/enable-sandboxes?)
- (t2/exists? :model/GroupTableAccessPolicy
+ (t2/exists? :model/Sandbox
:group_id group-id)))
:blocked
:unrestricted))
@@ -185,9 +185,9 @@
(and
(premium-features/enable-sandboxes?)
(t2/exists?
- :model/GroupTableAccessPolicy
+ :model/Sandbox
{:select [:s.id]
- :from [[(t2/table-name :model/GroupTableAccessPolicy) :s]]
+ :from [[(t2/table-name :model/Sandbox) :s]]
:join [[(t2/table-name :model/Table) :t] [:= :t.id :s.table_id]]
:where [:and
[:= :s.group_id group-id]
@@ -213,7 +213,7 @@
:db_id db-id)
(and
(premium-features/enable-sandboxes?)
- (t2/exists? :model/GroupTableAccessPolicy
+ (t2/exists? :model/Sandbox
:group_id all-users-group-id
{:from [[:sandboxes :s]]
:join [[:metabase_table :t] [:= :s.table_id :t.id]]
diff --git a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj b/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
index 833b5723ae4..4d44023bbca 100644
--- a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
+++ b/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
@@ -25,7 +25,7 @@
{:name :sandboxes
:available (and (premium-features/enable-official-collections?)
(t2/exists? :model/Database :engine [:in (descendants driver/hierarchy :sql)]))
- :enabled (t2/exists? :model/GroupTableAccessPolicy)}
+ :enabled (t2/exists? :model/Sandbox)}
{:name :email-allow-list
:available (premium-features/enable-email-allow-list?)
:enabled (boolean (some? (advanced-config.settings/subscription-allowed-domains)))}
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj
index 7a3df228128..2680c8c0eb7 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj
@@ -1,7 +1,7 @@
(ns metabase-enterprise.sandbox.api.gtap
"`/api/mt/gtap` endpoints, for CRUD operations and the like on GTAPs (Group Table Access Policies)."
(:require
- [metabase-enterprise.sandbox.models.group-table-access-policy :as gtap]
+ [metabase-enterprise.sandbox.models.sandbox :as gtap]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.open-api :as open-api]
@@ -19,14 +19,14 @@
[:group_id {:optional true} [:maybe ms/PositiveInt]]
[:table_id {:optional true} [:maybe ms/PositiveInt]]]]
(if (and group_id table_id)
- (t2/select-one :model/GroupTableAccessPolicy :group_id group_id :table_id table_id)
- (t2/select :model/GroupTableAccessPolicy {:order-by [[:id :asc]]})))
+ (t2/select-one :model/Sandbox :group_id group_id :table_id table_id)
+ (t2/select :model/Sandbox {:order-by [[:id :asc]]})))
(api.macros/defendpoint :get "/:id"
"Fetch GTAP by `id`"
[{:keys [id]} :- [:map
[:id ms/PositiveInt]]]
- (api/check-404 (t2/select-one :model/GroupTableAccessPolicy :id id)))
+ (api/check-404 (t2/select-one :model/Sandbox :id id)))
;; TODO - not sure what other endpoints we might need, e.g. for fetching the list above but for a given group or Table
@@ -46,7 +46,7 @@
[:group_id ms/PositiveInt]
[:attribute_remappings {:optional true} AttributeRemappings]]]
(first (t2/insert-returning-instances!
- :model/GroupTableAccessPolicy
+ :model/Sandbox
(select-keys body [:table_id :card_id :group_id :attribute_remappings]))))
(api.macros/defendpoint :put "/:id"
@@ -59,14 +59,14 @@
body :- [:map
[:card_id {:optional true} [:maybe ms/PositiveInt]]
[:attribute_remappings {:optional true} AttributeRemappings]]]
- (api/check-404 (t2/select-one :model/GroupTableAccessPolicy :id id))
+ (api/check-404 (t2/select-one :model/Sandbox :id id))
;; Only update `card_id` and/or `attribute_remappings` if the values are present in the body of the request.
;; This allows existing values to be "cleared" by being set to nil
(when (some #(contains? body %) [:card_id :attribute_remappings])
- (t2/update! :model/GroupTableAccessPolicy id
+ (t2/update! :model/Sandbox id
(u/select-keys-when body
:present #{:card_id :attribute_remappings})))
- (t2/select-one :model/GroupTableAccessPolicy :id id))
+ (t2/select-one :model/Sandbox :id id))
(api.macros/defendpoint :post "/validate"
"Validate a sandbox which may not have yet been saved. This runs the same validation that is performed when the
@@ -92,8 +92,8 @@
"Delete a GTAP entry."
[{:keys [id]} :- [:map
[:id ms/PositiveInt]]]
- (api/check-404 (t2/select-one :model/GroupTableAccessPolicy :id id))
- (t2/delete! :model/GroupTableAccessPolicy :id id)
+ (api/check-404 (t2/select-one :model/Sandbox :id id))
+ (t2/delete! :model/Sandbox :id id)
api/generic-204-no-content)
(defn- +check-sandboxes-enabled
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj
index 27b7cd77c5e..c99fd1a63f3 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj
@@ -44,7 +44,7 @@
(when user-id
(let [user-group-ids (user/group-ids user-id)
sandboxes-with-group-ids (t2/hydrate
- (t2/select :model/GroupTableAccessPolicy
+ (t2/select :model/Sandbox
{:select [[:pgm.group_id :group_id]
[:s.*]]
:from [[:permissions_group_membership :pgm]]
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj
index ad048e49295..8fd2bd982f8 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj
@@ -1,8 +1,7 @@
(ns metabase-enterprise.sandbox.models.params.field-values
(:require
[metabase-enterprise.sandbox.api.table :as table]
- [metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions
- :as row-level-restrictions]
+ [metabase-enterprise.sandbox.query-processor.middleware.sandboxing :as sandboxing]
[metabase.api.common :as api]
[metabase.lib.util.match :as lib.util.match]
[metabase.premium-features.core :refer [defenterprise]]
@@ -19,20 +18,20 @@
;; back to fetching it manually with `field/table`
(table/only-sandboxed-perms? (or table (field/table field))))
-(defn- table-id->gtap
+(defn- table-id->sandbox
"Find the GTAP for current user that apply to table `table-id`."
[table-id]
(let [group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id api/*current-user-id*)
- gtaps (t2/select :model/GroupTableAccessPolicy
+ sandboxes (t2/select :model/Sandbox
:group_id [:in group-ids]
:table_id table-id)]
- (when gtaps
- (row-level-restrictions/assert-one-gtap-per-table gtaps)
+ (when sandboxes
+ (sandboxing/assert-one-sandbox-per-table sandboxes)
;; there shold be only one gtap per table and we only need one table here
;; see docs in [[metabase.permissions.models.permissions]] for more info
- (t2/hydrate (first gtaps) :card))))
+ (t2/hydrate (first sandboxes) :card))))
-(defn- field->gtap-attributes-for-current-user
+(defn- field->sandbox-attributes-for-current-user
"Returns the gtap attributes for current user that applied to `field`.
The gtap-attributes is a list with 2 elements:
@@ -52,14 +51,14 @@
;; (field-id->gtap-attributes-for-current-user (t2/select-one Field :id 3))
;; -> [1, {\"State\" \"CA\"}]"
- [{:keys [table_id] :as _field}]
- (when-let [gtap (table-id->gtap table_id)]
- (let [login-attributes (api/current-user-attributes)
- attribute_remappings (:attribute_remappings gtap)
- field-ids (t2/select-fn-set :id :model/Field :table_id table_id)]
- [(:card_id gtap)
- (-> gtap :card :updated_at)
- (if (= :native (get-in gtap [:card :query_type]))
+ [{table-id :table_id, :as _field}]
+ (when-let [sandbox (table-id->sandbox table-id)]
+ (let [login-attributes (api/current-user-attributes)
+ attribute_remappings (:attribute_remappings sandbox)
+ field-ids (t2/select-fn-set :id :model/Field :table_id table-id)]
+ [(:card_id sandbox)
+ (-> sandbox :card :updated_at)
+ (if (= :native (get-in sandbox [:card :query_type]))
;; For sandbox that uses native query, we can't narrow down to the exact attribute
;; that affect the current table. So we just hash the whole login-attributes of users.
;; This makes hashing a bit less efficient but it ensures that user get a new hash
@@ -80,4 +79,4 @@
:feature :sandboxes
[field]
(when (field-is-sandboxed? field)
- {:sandbox-attributes (field->gtap-attributes-for-current-user field)}))
+ {:sandbox-attributes (field->sandbox-attributes-for-current-user field)}))
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj
index d5ed62068ff..7b3c356706e 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj
@@ -23,7 +23,7 @@
:where conditions}))))]
(do
(log/debugf "Deleting %d matching GTAPs: %s" (count gtap-ids) (pr-str gtap-ids))
- (t2/delete! :model/GroupTableAccessPolicy :id [:in gtap-ids]))
+ (t2/delete! :model/Sandbox :id [:in gtap-ids]))
(log/debug "No matching GTAPs need to be deleted."))
(catch Throwable e
(throw (ex-info (tru "Error deleting Sandboxes: {0}" (ex-message e))
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/group_table_access_policy.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
similarity index 81%
rename from enterprise/backend/src/metabase_enterprise/sandbox/models/group_table_access_policy.clj
rename to enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
index b5fc1411275..823374e043d 100644
--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/group_table_access_policy.clj
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj
@@ -1,14 +1,17 @@
-(ns metabase-enterprise.sandbox.models.group-table-access-policy
+(ns metabase-enterprise.sandbox.models.sandbox
"Model definition for sandboxes, aka Group Table Access Policies (old name). A sandbox is used to control access to a
certain Table for a certain PermissionsGroup. Whenever a member of that group attempts to query the Table in question,
a Saved Question specified by the GTAP is instead used as the source of the query.
- See documentation in [[metabase.permissions.models.permissions]] for more information about the Metabase permissions system."
+ See documentation in [[metabase.permissions.models.permissions]] for more information about the Metabase permissions
+ system."
(:require
[medley.core :as m]
[metabase.audit-app.core :as audit]
- [metabase.classloader.core :as classloader]
[metabase.legacy-mbql.normalize :as mbql.normalize]
+ [metabase.legacy-mbql.schema :as mbql.s]
+ [metabase.lib.schema.id :as lib.schema.id]
+ [metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
[metabase.premium-features.core :refer [defenterprise]]
@@ -17,16 +20,15 @@
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.malli :as mu]
- [metabase.util.malli.schema :as ms]
[metabase.warehouses.models.database :as database]
[methodical.core :as methodical]
[toucan2.core :as t2]))
(set! *warn-on-reflection* true)
-(methodical/defmethod t2/table-name :model/GroupTableAccessPolicy [_model] :sandboxes)
+(methodical/defmethod t2/table-name :model/Sandbox [_model] :sandboxes)
-(doto :model/GroupTableAccessPolicy
+(doto :model/Sandbox
(derive :metabase/model)
;;; only admins can work with sandboxes
(derive ::mi/read-policy.superuser)
@@ -37,7 +39,7 @@
mbql.normalize/normalize
attribute-remappings))
-(t2/deftransforms :model/GroupTableAccessPolicy
+(t2/deftransforms :model/Sandbox
{:attribute_remappings {:in (comp mi/json-in normalize-attribute-remapping-targets)
:out (comp normalize-attribute-remapping-targets mi/json-out-without-keywordization)}})
@@ -51,24 +53,29 @@
:query {:source-table table-id}}))]
[(:name col) col])))
-(defn check-column-types-match
+(mu/defn check-column-types-match
"Assert that the base type of `col`, returned by a GTAP source query, matches the base type of `table-col`, a column
from the original Table being sandboxed."
- {:arglists '([col table-col])}
- [col {table-col-base-type :base_type}]
+ [col :- [:or
+ ::lib.schema.metadata/column
+ ::mbql.s/legacy-column-metadata]
+ table-col :- [:maybe [:or
+ ::lib.schema.metadata/column
+ ::mbql.s/legacy-column-metadata]]]
;; These errors might get triggered by API endpoints or by the QP (this code is used in the
- ;; `row-level-restrictions` middleware). So include `:type` and `:status-code` information in the ExceptionInfo
+ ;; `sandboxing` middleware). So include `:type` and `:status-code` information in the ExceptionInfo
;; data so it can be passed along if applicable.
- (when table-col-base-type
- (when-not (isa? (keyword (:base_type col)) table-col-base-type)
- (let [msg (tru "Sandbox Questions can''t return columns that have different types than the Table they are sandboxing.")]
- (throw (ex-info msg
- {:type qp.error-type/bad-configuration
- :status-code 400
- :message msg
- :new-col col
- :expected table-col-base-type
- :actual (:base_type col)}))))))
+ (when-let [table-col-base-type ((some-fn :base-type :base_type) table-col)]
+ (let [col-base-type ((some-fn :base-type :base_type) col)]
+ (when-not (isa? col-base-type table-col-base-type)
+ (let [msg (tru "Sandbox Questions can''t return columns that have different types than the Table they are sandboxing.")]
+ (throw (ex-info msg
+ {:type qp.error-type/bad-configuration
+ :status-code 400
+ :message msg
+ :new-col col
+ :expected table-col-base-type
+ :actual (:base_type col)})))))))
(defn- merge-sandbox-into-graph
"Merges a single sandboxing policy into the permissions graph. Adjusts permissions at the database or schema level,
@@ -114,7 +121,7 @@
"Augments a provided permissions graph with active sandboxing policies."
:feature :sandboxes
[graph & {:keys [group-ids group-id db-id audit?]}]
- (let [sandboxes (t2/select :model/GroupTableAccessPolicy
+ (let [sandboxes (t2/select :model/Sandbox
{:select [:s.group_id :s.table_id :t.db_id :t.schema]
:from [[:sandboxes :s]]
:join [[:metabase_table :t] [:= :s.table_id :t.id]]
@@ -137,15 +144,14 @@
;; not all sandboxes have Cards
(when card-id
;; not all Cards have saved result metadata
- (when-let [result-metadata (t2/select-one-fn :result_metadata :model/Card :id card-id)]
+ (when-let [result-metadata (not-empty (t2/select-one-fn :result_metadata :model/Card :id card-id))]
(check-columns-match-table table-id result-metadata))))
- ([table-id :- ms/PositiveInt result-metadata-columns]
- ;; prevent circular refs
- (classloader/require 'metabase.query-processor)
+ ([table-id :- ::lib.schema.id/table result-metadata-columns]
(let [table-cols (table-field-names->cols table-id)]
- (doseq [col result-metadata-columns
- :let [table-col (get table-cols (:name col))]]
+ (doseq [col result-metadata-columns
+ :let [table-col (get table-cols (:name col))]
+ :when table-col]
(check-column-types-match col table-col)))))
(defenterprise pre-update-check-sandbox-constraints
@@ -154,7 +160,7 @@
:feature :sandboxes
[{new-result-metadata :result_metadata, card-id :id} changes]
(when (contains? changes :result_metadata)
- (when-let [gtaps-using-this-card (not-empty (t2/select [:model/GroupTableAccessPolicy :id :table_id] :card_id card-id))]
+ (when-let [gtaps-using-this-card (not-empty (t2/select [:model/Sandbox :id :table_id] :card_id card-id))]
(let [original-result-metadata (t2/select-one-fn :result_metadata :model/Card :id card-id)]
(when-not (= original-result-metadata new-result-metadata)
(doseq [{table-id :table_id} gtaps-using-this-card]
@@ -180,13 +186,13 @@
;; This allows existing values to be "cleared" by being set to nil
(do
(when (some #(contains? sandbox %) [:card_id :attribute_remappings])
- (t2/update! :model/GroupTableAccessPolicy
+ (t2/update! :model/Sandbox
id
(u/select-keys-when sandbox :present #{:card_id :attribute_remappings})))
- (t2/select-one :model/GroupTableAccessPolicy :id id))
- (first (t2/insert-returning-instances! :model/GroupTableAccessPolicy sandbox))))))
+ (t2/select-one :model/Sandbox :id id))
+ (first (t2/insert-returning-instances! :model/Sandbox sandbox))))))
-(t2/define-before-insert :model/GroupTableAccessPolicy
+(t2/define-before-insert :model/Sandbox
[{:keys [table_id group_id], :as gtap}]
(let [db-id (database/table-id->database-id table_id)]
;; Remove native query access to the DB when saving a sandbox
@@ -195,7 +201,7 @@
(u/prog1 gtap
(check-columns-match-table gtap)))
-(t2/define-before-update :model/GroupTableAccessPolicy
+(t2/define-before-update :model/Sandbox
[{:keys [id], :as updates}]
(u/prog1 updates
(let [original (t2/original updates)
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions.clj b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions.clj
deleted file mode 100644
index 9b0fa18de55..00000000000
--- a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions.clj
+++ /dev/null
@@ -1,349 +0,0 @@
-(ns metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions
- "Apply segmented a.k.a. sandboxing anti-permissions to the query, i.e. replace sandboxed Tables with the
- appropriate [[metabase-enterprise.sandbox.models.group-table-access-policy]]s (GTAPs). See dox
- for [[metabase.permissions.models.permissions]] for a high-level overview of the Metabase permissions system."
- (:require
- [clojure.core.memoize :as memoize]
- [medley.core :as m]
- [metabase-enterprise.sandbox.api.util :as sandbox.api.util]
- [metabase-enterprise.sandbox.models.group-table-access-policy :as gtap]
- [metabase.api.common :as api :refer [*current-user* *current-user-id*]]
- [metabase.app-db.core :as mdb]
- [metabase.legacy-mbql.schema :as mbql.s]
- [metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]
- ;; TODO: Why use the lib.metadata.protocols functions directly, instead of the lib.metadata wrappers?
- ;; This should probably be enforced at the modules level.
- [metabase.lib.metadata.protocols :as lib.metadata.protocols]
- [metabase.lib.schema.common :as lib.schema.common]
- [metabase.lib.schema.id :as lib.schema.id]
- [metabase.lib.util.match :as lib.util.match]
- [metabase.premium-features.core :refer [defenterprise]]
- [metabase.query-processor.error-type :as qp.error-type]
- ^{:clj-kondo/ignore [:deprecated-namespace]}
- [metabase.query-processor.middleware.fetch-source-query-legacy :as fetch-source-query-legacy]
- [metabase.query-processor.pipeline :as qp.pipeline]
- [metabase.query-processor.store :as qp.store]
- [metabase.request.core :as request]
- [metabase.util :as u]
- [metabase.util.i18n :refer [trs tru]]
- [metabase.util.log :as log]
- [metabase.util.malli :as mu]
- ^{:clj-kondo/ignore [:discouraged-namespace]}
- [toucan2.core :as t2]))
-
-(set! *warn-on-reflection* true)
-
-;;; +----------------------------------------------------------------------------------------------------------------+
-;;; | query->gtap |
-;;; +----------------------------------------------------------------------------------------------------------------+
-
-(defn- all-table-ids [m]
- (into #{} cat (lib.util.match/match m
- (_ :guard (every-pred map? :source-table (complement ::gtap?)))
- (let [recursive-ids (all-table-ids (dissoc &match :source-table))]
- (cons (:source-table &match) recursive-ids)))))
-
-(defn- query->all-table-ids [query]
- (let [ids (all-table-ids query)]
- (when (seq ids)
- (lib.metadata/bulk-metadata-or-throw (qp.store/metadata-provider) :metadata/table ids)
- (set ids))))
-
-(defn assert-one-gtap-per-table
- "Make sure all referenced Tables have at most one GTAP."
- [gtaps]
- (doseq [[table-id gtaps] (group-by :table_id gtaps)
- :when (> (count gtaps) 1)]
- (throw (ex-info (tru "Found more than one group table access policy for user ''{0}''"
- (:email @*current-user*))
- {:type qp.error-type/client
- :table-id table-id
- :gtaps gtaps
- :user *current-user-id*
- :group-ids (map :group_id gtaps)}))))
-
-(defn- tables->sandboxes [table-ids]
- (qp.store/cached [*current-user-id* table-ids]
- (let [enforced-sandboxes (sandbox.api.util/enforced-sandboxes-for-tables table-ids)]
- (when (seq enforced-sandboxes)
- (assert-one-gtap-per-table enforced-sandboxes)
- enforced-sandboxes))))
-
-(defn- query->table-id->gtap [query]
- {:pre [(some? *current-user-id*)]}
- (let [table-ids (query->all-table-ids query)
- gtaps (some-> table-ids tables->sandboxes)]
- (when (seq gtaps)
- (m/index-by :table_id gtaps))))
-
-;;; +----------------------------------------------------------------------------------------------------------------+
-;;; | Applying a GTAP |
-;;; +----------------------------------------------------------------------------------------------------------------+
-
-(mu/defn- target-field->base-type :- [:maybe ::lib.schema.common/base-type]
- "If the `:target` of a parameter contains a `:field` clause, return the base type corresponding to the Field it
- references. Otherwise returns `nil`."
- [[_ target-field-clause]]
- (when-let [field-id (lib.util.match/match-one target-field-clause [:field (field-id :guard integer?) _] field-id)]
- (:base-type (lib.metadata.protocols/field (qp.store/metadata-provider) field-id))))
-
-(defn- attr-value->param-value
- "Take an `attr-value` with a desired `target-type` and coerce to that type if need be. If not type is given or it's
- already correct, return the original `attr-value`"
- [target-type attr-value]
- (let [attr-string? (string? attr-value)]
- (cond
- ;; If the attr-value is a string and the target type is integer, parse it as a long
- (and attr-string? (isa? target-type :type/Integer))
- (parse-long attr-value)
- ;; If the attr-value is a string and the target type is float, parse it as a double
- (and attr-string? (isa? target-type :type/Float))
- (parse-double attr-value)
- ;; No need to parse it if the type isn't numeric or if it's already a number
- :else
- attr-value)))
-
-(defn- attr-remapping->parameter [login-attributes [attr-name target]]
- (let [attr-value (get login-attributes attr-name)
- field-base-type (target-field->base-type target)]
- (when (not attr-value)
- (throw (ex-info (tru "Query requires user attribute `{0}`" (name attr-name))
- {:type qp.error-type/missing-required-parameter})))
- {:type :category
- :target target
- :value (attr-value->param-value field-base-type attr-value)}))
-
-(defn- gtap->parameters [{attribute-remappings :attribute_remappings}]
- (mapv (partial attr-remapping->parameter (api/current-user-attributes))
- attribute-remappings))
-
-(mu/defn- preprocess-source-query :- mbql.s/SourceQuery
- [source-query :- mbql.s/SourceQuery]
- (try
- (let [query {:database (u/the-id (lib.metadata/database (qp.store/metadata-provider)))
- :type :query
- :query source-query}
- preprocessed (-> (lib/without-cleaning
- (fn []
- (request/as-admin
- ((requiring-resolve 'metabase.query-processor.preprocess/preprocess) query))))
- lib/->legacy-MBQL)]
- (select-keys (:query preprocessed) [:source-query :source-metadata]))
- (catch Throwable e
- (throw (ex-info (tru "Error preprocessing source query when applying GTAP: {0}" (ex-message e))
- {:source-query source-query}
- e)))))
-
-(mu/defn- card-gtap->source :- ::mbql.s/SourceQuery
- [{card-id :card_id :as gtap}]
- (update-in (fetch-source-query-legacy/card-id->source-query-and-metadata card-id)
- [:source-query :parameters]
- concat
- (gtap->parameters gtap)))
-
-(mu/defn- table-gtap->source :- ::mbql.s/SourceQuery
- [{table-id :table_id, :as gtap}]
- {:source-query {:source-table table-id, :parameters (gtap->parameters gtap)}})
-
-(mu/defn- mbql-query-metadata :- [:+ :map]
- [inner-query]
- (request/as-admin
- ((requiring-resolve 'metabase.query-processor.preprocess/query->expected-cols)
- {:database (u/the-id (lib.metadata/database (qp.store/metadata-provider)))
- :type :query
- :query inner-query})))
-
-;; cache the original metadata for a little bit so we don't have to preprocess a query every time we apply sandboxing
-(def ^:private ^{:arglists '([table-id])} original-table-metadata
- (memoize/ttl
- ^{::memoize/args-fn (fn [[table-id]]
- [(mdb/unique-identifier) table-id])}
- (fn [table-id]
- (mbql-query-metadata {:source-table table-id}))
- :ttl/threshold (u/minutes->ms 1)))
-
-(mu/defn- reconcile-metadata :- [:+ :map]
- "Combine the metadata in `source-query-metadata` with the `table-metadata` from the Table being sandboxed."
- [source-query-metadata :- [:+ :map] table-metadata]
- (let [col-name->table-metadata (m/index-by :name table-metadata)]
- (vec
- (for [col source-query-metadata
- :let [table-col (get col-name->table-metadata (:name col))]
- :when table-col]
- (do
- (gtap/check-column-types-match col table-col)
- table-col)))))
-
-(mu/defn- native-query-metadata :- [:+ :map]
- [source-query :- [:map [:source-query :any]]]
- (let [result
- ;; Rebind *result* in case the outer query is being streamed back to the client. The streaming code binds this
- ;; to a custom handler, and we don't want to accidentally terminate the stream here!
- (binding [qp.pipeline/*result* qp.pipeline/default-result-handler]
- (request/as-admin
- ((requiring-resolve 'metabase.query-processor/process-query)
- {:database (u/the-id (lib.metadata/database (qp.store/metadata-provider)))
- :type :query
- :query {:source-query source-query
- :limit 0}})))]
- (or (-> result :data :results_metadata :columns not-empty)
- (throw (ex-info (tru "Error running query to determine metadata")
- {:source-query source-query
- :result result})))))
-
-(mu/defn- source-query-form-ensure-metadata :- [:and [:map-of :keyword :any]
- [:map
- [:source-query :any]
- [:source-metadata [:+ :map]]]]
- "Add `:source-metadata` to a `source-query` if needed. If the source metadata had to be resolved (because Card with
- `card-id`) didn't already have it, save it so we don't have to resolve it again next time around."
- [{:keys [source-metadata], :as source-query} :- [:and [:map-of :keyword :any] [:map [:source-query :any]]]
- table-id :- ::lib.schema.id/table
- card-id :- [:maybe ::lib.schema.id/card]]
- (let [table-metadata (original-table-metadata table-id)
- ;; make sure source query has `:source-metadata`; add it if needed
- [metadata save?] (cond
- ;; if it already has `:source-metadata`, we're good to go.
- (seq source-metadata)
- [source-metadata false]
-
- ;; if it doesn't have source metadata, but it's an MBQL query, we can preprocess the query to
- ;; get the expected metadata.
- (not (get-in source-query [:source-query :native]))
- [(mbql-query-metadata source-query) true]
-
- ;; otherwise if it's a native query we'll have to run the query really quickly to get the
- ;; expected metadata.
- :else
- [(native-query-metadata source-query) true])
- metadata (reconcile-metadata metadata table-metadata)]
- (assert (seq metadata))
- ;; save the result metadata so we don't have to do it again next time if applicable
- (when (and card-id save?)
- (log/tracef "Saving results metadata for GTAP Card %s" card-id)
- (t2/update! :model/Card card-id {:result_metadata metadata}))
- ;; make sure the fetched Fields are present the QP store
- (when-let [field-ids (not-empty (filter some? (map :id metadata)))]
- (lib.metadata/bulk-metadata-or-throw (qp.store/metadata-provider) :metadata/column field-ids))
- (assoc source-query :source-metadata metadata)))
-
-(mu/defn- gtap->source :- [:map
- [:source-query :any]
- [:source-metadata {:optional true} [:sequential ::mbql.s/legacy-column-metadata]]]
- "Get the source query associated with a `gtap`."
- [{card-id :card_id, table-id :table_id, :as gtap} :- :map]
- (-> ((if card-id
- card-gtap->source
- table-gtap->source) gtap)
- preprocess-source-query
- (source-query-form-ensure-metadata table-id card-id)))
-
-;;; +----------------------------------------------------------------------------------------------------------------+
-;;; | Middleware |
-;;; +----------------------------------------------------------------------------------------------------------------+
-
-;;; ------------------------------------------ apply-row-level-permissions -------------------------------------------
-
-(defn- apply-gtap
- "Apply a GTAP to map m (e.g. a Join or inner query), replacing its `:source-table`/`:source-query` with the GTAP
- `:source-query`."
- [{:keys [source-table] :as m} gtap]
- ;; Only infer source query metadata for JOINS that use `:fields :all`. That's the only situation in which we
- ;; absolutely *need* to infer source query metadata (we need to know the columns returned by the source query so we
- ;; can generate the join against ALL fields). It's better not to infer the source metadata if we don't NEED to,
- ;; because we might be inferring the wrong thing. See comments above -- in practice a GTAP should have the same
- ;; columns as the Table it replaces, but this constraint is not enforced anywhere. If we infer metadata and the GTAP
- ;; turns out *not* to match exactly, the query could break. So only infer it in cases where the query would
- ;; definitely break otherwise.
- (u/prog1 (-> (merge
- (dissoc m :source-table :source-query)
- (gtap->source gtap))
- (assoc-in [:source-query :query-permissions/gtapped-table] source-table))
- (log/tracef "Applied GTAP: replaced\n%swith\n%s"
- (u/pprint-to-str 'yellow m)
- (u/pprint-to-str 'green <>))))
-
-(defn- apply-gtaps
- "Replace `:source-table` entries that refer to Tables for which we have applicable GTAPs with `:source-query` entries
- from their GTAPs."
- [m table-id->gtap]
- ;; replace maps that have `:source-table` key and a matching entry in `table-id->gtap`, but do not have `::gtap?` key
- (lib.util.match/replace m
- (_ :guard (every-pred map? (complement ::gtap?) :source-table #(get table-id->gtap (:source-table %))))
- (let [updated (apply-gtap &match (get table-id->gtap (:source-table &match)))
- ;; now recursively apply gtaps anywhere else they might exist at this level, e.g. `:joins`
- recursively-updated (merge
- (select-keys updated [:source-table :source-query])
- (apply-gtaps (dissoc updated :source-table :source-query) table-id->gtap))]
- ;; add a `::gtap?` key next to every `:source-table` key so when we do a second pass after adding JOINs they
- ;; don't get processed again
- (lib.util.match/replace recursively-updated
- (_ :guard (every-pred map? :source-table))
- (assoc &match ::gtap? true)))))
-
-(mu/defn- expected-cols :- [:sequential ::mbql.s/legacy-column-metadata]
- [query :- ::mbql.s/Query]
- (request/as-admin
- ((requiring-resolve 'metabase.query-processor.preprocess/query->expected-cols) query)))
-
-(defn- gtapped-query
- "Apply GTAPs to `query` and return the updated version of `query`."
- [original-query table-id->gtap]
- (let [sandboxed-query (apply-gtaps original-query table-id->gtap)]
- (if (= sandboxed-query original-query)
- original-query
- (assoc sandboxed-query ::original-metadata (expected-cols original-query)))))
-
-(def ^:private default-recursion-limit 20)
-(def ^:private ^:dynamic *recursion-limit* default-recursion-limit)
-
-(defenterprise apply-sandboxing
- "Pre-processing middleware. Replaces source tables a User was querying against with source queries that (presumably)
- restrict the rows returned, based on presence of sandboxes."
- :feature :sandboxes
- [query]
- (if-not api/*is-superuser?*
- (or (when-let [table-id->gtap (when *current-user-id*
- (query->table-id->gtap query))]
- (let [gtapped-query (gtapped-query query table-id->gtap)]
- (if (not= query gtapped-query)
- ;; Applying GTAPs to the query may have introduced references to tables that are also sandboxed,
- ;; so we need to recursively appby the middleware until new queries are not returned.
- (if (= *recursion-limit* 0)
- (throw (ex-info (trs "Reached recursion limit of {0} in \"apply-sandboxing\" middleware"
- default-recursion-limit)
- query))
- (binding [*recursion-limit* (dec *recursion-limit*)]
- (apply-sandboxing gtapped-query)))
- gtapped-query)))
- query)
- query))
-
-;;;; Post-processing
-
-(mu/defn- merge-metadata :- [:map
- [:cols [:sequential ::mbql.s/legacy-column-metadata]]]
- "Merge column metadata from the non-sandboxed version of the query into the sandboxed results `metadata`. This way the
- final results metadata coming back matches what we'd get if the query was not running in a sandbox."
- [original-metadata :- [:sequential ::mbql.s/legacy-column-metadata]
- metadata :- [:map
- [:cols [:sequential ::mbql.s/legacy-column-metadata]]]]
- (letfn [(merge-cols [cols]
- (let [col-name->expected-col (m/index-by :name original-metadata)]
- (for [col cols]
- (merge
- col
- (get col-name->expected-col (:name col))))))]
- (update metadata :cols merge-cols)))
-
-(defenterprise merge-sandboxing-metadata
- "Post-processing middleware. Merges in column metadata from the original, unsandboxed version of the query."
- :feature :sandboxes
- [{::keys [original-metadata] :as query} rff]
- (fn merge-sandboxing-metadata-rff* [metadata]
- (let [metadata (assoc metadata :is_sandboxed (some? (lib.util.match/match-one query (m :guard (every-pred map? :query-permissions/gtapped-table)))))
- metadata (if original-metadata
- (merge-metadata original-metadata metadata)
- metadata)]
- (rff metadata))))
diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj
new file mode 100644
index 00000000000..7a45c6290c0
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj
@@ -0,0 +1,386 @@
+(ns metabase-enterprise.sandbox.query-processor.middleware.sandboxing
+ "Apply segmented a.k.a. sandboxing anti-permissions to the query, i.e. replace sandboxed Tables with the
+ appropriate [[metabase-enterprise.sandbox.models.sandbox]]s (Sandboxes). See dox
+ for [[metabase.permissions.models.permissions]] for a high-level overview of the Metabase permissions system."
+ (:require
+ [better-cond.core :as b]
+ [medley.core :as m]
+ [metabase-enterprise.sandbox.api.util :as sandbox.api.util]
+ [metabase-enterprise.sandbox.models.sandbox :as sandbox]
+ [metabase.api.common :as api :refer [*current-user* *current-user-id*]]
+ [metabase.legacy-mbql.schema :as mbql.s]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.metadata.result-metadata :as lib.metadata.result-metadata]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.schema.common :as lib.schema.common]
+ [metabase.lib.schema.id :as lib.schema.id]
+ [metabase.lib.schema.metadata :as lib.schema.metadata]
+ [metabase.lib.schema.parameter :as lib.schema.parameter]
+ [metabase.lib.util :as lib.util]
+ [metabase.lib.util.match :as lib.util.match]
+ [metabase.lib.walk :as lib.walk]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [metabase.query-processor.error-type :as qp.error-type]
+ [metabase.query-processor.pipeline :as qp.pipeline]
+ [metabase.query-processor.util.persisted-cache :as qp.persisted]
+ [metabase.request.core :as request]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
+ ^{:clj-kondo/ignore [:discouraged-namespace]}
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;;; TODO (Cam 9/9/25) -- we should probably kebab-case these when they come in
+;;; from [[metabase-enterprise.sandbox.api.util/enforced-sandboxes-for-tables]] for consistency with all of the rest
+;;; of the QP code. Or maybe add this to the Metadata Provider (or a special "Enterprise" Metadata Provider)?
+(mr/def ::sandbox
+ [:map
+ [:table_id ::lib.schema.id/table]
+ [:card_id {:optional true} [:maybe ::lib.schema.id/card]]
+ [:attribute_remappings {:optional true} [:maybe
+ [:map-of
+ #_attribute-name ::lib.schema.common/non-blank-string
+ #_target ::lib.schema.parameter/target]]]])
+
+(mu/defn- query->all-table-ids :- [:maybe [:set ::lib.schema.id/table]]
+ [query]
+ (u/prog1 (lib/all-source-table-ids query)
+ (when (seq <>)
+ (lib.metadata/bulk-metadata-or-throw query :metadata/table <>))))
+
+(mu/defn assert-one-sandbox-per-table
+ "Make sure all referenced Tables have at most one Sandbox."
+ [sandboxes :- [:sequential ::sandbox]]
+ (doseq [[table-id sandboxes] (group-by :table_id sandboxes)
+ :when (> (count sandboxes) 1)]
+ (throw (ex-info (tru "Found more than one group table access policy for user ''{0}''"
+ (:email @*current-user*))
+ {:type qp.error-type/client
+ :table-id table-id
+ :sandboxes sandboxes
+ :user *current-user-id*
+ :group-ids (map :group_id sandboxes)}))))
+
+(mu/defn- tables->sandboxes :- [:maybe [:sequential ::sandbox]]
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable
+ table-ids :- [:maybe [:set ::lib.schema.id/table]]]
+ (when (seq table-ids)
+ (let [thunk (fn []
+ (let [sandboxes (sandbox.api.util/enforced-sandboxes-for-tables table-ids)]
+ (when (seq sandboxes)
+ (assert-one-sandbox-per-table sandboxes)
+ sandboxes)))
+ ks [::tables->sandboxes *current-user-id* table-ids]]
+ (lib.metadata/general-cached-value metadata-providerable ks thunk))))
+
+(mu/defn- query->table-id->sandbox :- [:maybe [:map-of ::lib.schema.id/table ::sandbox]]
+ [query :- ::lib.schema/query]
+ {:pre [(some? *current-user-id*)]}
+ (let [table-ids (query->all-table-ids query)
+ sandboxes (some->> table-ids (tables->sandboxes query))]
+ (when (seq sandboxes)
+ (m/index-by :table_id sandboxes))))
+
+(mu/defn- target-field->base-type :- [:maybe ::lib.schema.common/base-type]
+ "If the `:target` of a parameter contains a `:field` clause, return the base type corresponding to the Field it
+ references. Otherwise returns `nil`."
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable
+ target-field-clause :- ::lib.schema.parameter/target]
+ ;; parameter targets still use legacy field refs for whatever wacko reason
+ (when-let [field-id (lib.util.match/match-one target-field-clause [:field (field-id :guard pos-int?) _opts] field-id)]
+ (:base-type (lib.metadata/field metadata-providerable field-id))))
+
+(defn- attr-value->param-value
+ "Take an `attr-value` with a desired `target-type` and coerce to that type if need be. If not type is given or it's
+ already correct, return the original `attr-value`"
+ [target-type attr-value]
+ (let [attr-string? (string? attr-value)]
+ (cond
+ ;; If the attr-value is a string and the target type is integer, parse it as a long
+ (and attr-string? (isa? target-type :type/Integer))
+ (parse-long attr-value)
+ ;; If the attr-value is a string and the target type is float, parse it as a double
+ (and attr-string? (isa? target-type :type/Float))
+ (parse-double attr-value)
+ ;; No need to parse it if the type isn't numeric or if it's already a number
+ :else
+ attr-value)))
+
+(defn- attr-remapping->parameter [metadata-providerable login-attributes [attr-name target]]
+ (let [attr-value (get login-attributes attr-name)
+ field-base-type (target-field->base-type metadata-providerable target)]
+ (when (not attr-value)
+ (throw (ex-info (tru "Query requires user attribute `{0}`" (name attr-name))
+ {:type qp.error-type/missing-required-parameter})))
+ {:type :category
+ :target target
+ :value (attr-value->param-value field-base-type attr-value)}))
+
+(mu/defn- sandbox->parameters :- [:maybe [:sequential ::lib.schema.parameter/parameter]]
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable
+ {attribute-remappings :attribute_remappings} :- ::sandbox]
+ (mapv (partial attr-remapping->parameter metadata-providerable (api/current-user-attributes))
+ attribute-remappings))
+
+(mu/defn- preprocess-query :- ::lib.schema/query
+ [query :- ::lib.schema/query]
+ (try
+ (lib/without-cleaning
+ (fn []
+ (let [preprocess (requiring-resolve 'metabase.query-processor.preprocess/preprocess)]
+ (request/as-admin
+ ;; preprocessing normally loses metadata attached to the last stage, since legacy MBQL syntax does not
+ ;; support it and preprocessing roundtrips to legacy and back a few times... to make sure it's preserved,
+ ;; append an extra dummy stage before preprocessing and then toss it when we're done.
+ (-> query
+ lib/append-stage
+ preprocess
+ (update :stages pop))))))
+ (catch Throwable e
+ (throw (ex-info (tru "Error preprocessing query when applying Sandbox: {0}" (ex-message e))
+ {:query query}
+ e)))))
+
+(mu/defn card-id->underlying-query :- ::lib.schema/query
+ "Return the source query info for Card with `card-id`. Pass true as the optional second arg `log?` to enable
+ logging. (The circularity check calls this and will print more than desired)"
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable
+ card-id :- ::lib.schema.id/card]
+ (let [;; todo: we need to cache this. We are running this in preprocess, compile, and then again
+ card (or (lib.metadata/card metadata-providerable card-id)
+ (throw (ex-info (tru "Card {0} does not exist." card-id)
+ {:card-id card-id})))
+ persisted-info (:lib/persisted-info card)
+ persisted? (qp.persisted/can-substitute? card persisted-info)
+ query (lib/card->underlying-query metadata-providerable card)]
+ ;; log the query at this point, it's useful for some purposes
+ (log/debugf "Fetched query from Card %s:\n%s" card-id (u/cprint-to-str (select-keys query [:stages :parameters])))
+ (cond-> query
+ ;; This will be applied, if still appropriate, by the peristence middleware
+ persisted?
+ (assoc :persisted-info/native
+ (qp.persisted/persisted-info-native-query
+ (u/the-id (lib.metadata/database metadata-providerable))
+ persisted-info)))))
+
+(mu/defn- card-sandbox->query :- ::lib.schema/query
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable
+ {card-id :card_id :as sandbox} :- ::sandbox]
+ (update (card-id->underlying-query metadata-providerable card-id)
+ :parameters
+ concat
+ (sandbox->parameters metadata-providerable sandbox)))
+
+(mu/defn- table-sandbox->query :- ::lib.schema/query
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable
+ {table-id :table_id, :as sandbox} :- ::sandbox]
+ (-> (lib/query metadata-providerable (lib.metadata/table metadata-providerable table-id))
+ (assoc :parameters (sandbox->parameters metadata-providerable sandbox))))
+
+(mu/defn- native-query-metadata :- [:maybe [:sequential {:min 1} ::mbql.s/legacy-column-metadata]]
+ [query :- ::lib.schema/query]
+ (let [result
+ ;; Rebind *result* in case the outer query is being streamed back to the client. The streaming code binds this
+ ;; to a custom handler, and we don't want to accidentally terminate the stream here!
+ (binding [qp.pipeline/*result* qp.pipeline/default-result-handler]
+ (request/as-admin
+ ((requiring-resolve 'metabase.query-processor/process-query)
+ query)))]
+ (when-not (= (:status result) :completed)
+ (throw (ex-info "Error running query to determine metadata"
+ {:query query, :result result})))
+ (-> result :data :results_metadata :columns not-empty)))
+
+(mu/defn- ensure-native-queries-have-metadata :- ::lib.schema/query
+ "Add `:source-metadata` to a `source-query` if needed. If the source metadata had to be resolved (because Card with
+ `card-id`) didn't already have it, save it so we don't have to resolve it again next time around."
+ [query :- ::lib.schema/query
+ card-id :- [:maybe ::lib.schema.id/card]]
+ (or (when (= (count (:stages query)) 1)
+ (let [first-stage (lib.util/query-stage query 0)]
+ (when (and (lib.util/native-stage? first-stage)
+ (not (:lib/stage-metadata first-stage)))
+ (when-let [cols (not-empty (native-query-metadata query))]
+ (when card-id
+ (log/infof "Saving results metadata for Sandbox Card %d" card-id)
+ ;; TODO (Cam 9/9/25) -- we should switch to saving Lib-style metadata in the app DB instead of legacy
+ ;; style in the near future
+ (t2/update! :model/Card card-id {:result_metadata cols}))
+ (assoc-in query [:stages 0 :lib/stage-metadata] (->> cols
+ lib.util/->stage-metadata
+ (lib/normalize ::lib.schema.metadata/stage)))))))
+ query))
+
+(mu/defn- sandbox->query :- ::lib.schema/query
+ "Get the query associated with a `sandbox`."
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable
+ {card-id :card_id, :as sandbox} :- ::sandbox]
+ (-> ((if card-id
+ card-sandbox->query
+ table-sandbox->query) metadata-providerable sandbox)
+ (ensure-native-queries-have-metadata card-id)
+ (assoc-in [:middleware :disable-remaps?] true)
+ preprocess-query))
+
+(defn- project-only-columns-from-original-table
+ "A sandbox query is only allowed to return columns returned by the original table. If the sandbox query returns
+ anything else, log a warning telling people this is officially unsupported, then add a new stage to the query with
+ `:fields` to only select the allowed columns.
+
+ We probably should have had this error from day 1 but now there are sandboxes in the wild that do this so I guess we
+ just have to work around them going forward."
+ [metadata-providerable sandbox-query original-table-id]
+ (let [sandbox-cols (lib/returned-columns sandbox-query)
+ table-cols (lib.metadata/fields metadata-providerable original-table-id)
+ fixed-cols (remove (fn [{:keys [table-id], :as sandbox-col}]
+ (b/cond
+ (and table-id
+ (not= table-id original-table-id))
+ (do
+ (log/errorf (str "Sandboxes can only include columns from the original Table (%d),"
+ " query included %s from Table %d. This is unsupported and may not"
+ " work in the future.")
+ original-table-id
+ (pr-str (:name sandbox-col))
+ table-id)
+ true)
+
+ :let [matching-table-col (m/find-first #(= (:name %)
+ (:name sandbox-col))
+ table-cols)]
+ (not matching-table-col)
+ (do
+ (log/errorf (str "Sandboxes can only include columns from the original Table,"
+ " but query included %s. This is unsupported and may not work in"
+ " the future.")
+ (pr-str (:name sandbox-col)))
+ true)
+
+ :else
+ (do
+ ;; this will throw an exception if types don't match up
+ (sandbox/check-column-types-match sandbox-col matching-table-col)
+ false)))
+ sandbox-cols)]
+ (if (= fixed-cols sandbox-cols)
+ sandbox-query
+ (do
+ (log/warn "Adding additional stage to query to work around bad sandbox with extra columns")
+ (-> sandbox-query
+ lib/append-stage
+ (lib/with-fields (map lib/update-keys-for-col-from-previous-stage fixed-cols)))))))
+
+(defn- merge-original-table-metadata [native-cols original-table-cols]
+ (into []
+ (keep (fn [table-col]
+ (when-let [native-col (m/find-first #(= (:name %) (:name table-col))
+ native-cols)]
+ (merge native-col table-col))))
+ original-table-cols))
+
+(mu/defn- apply-sandbox-to-stage :- [:sequential {:min 2} ::lib.schema/stage]
+ "Apply a Sandbox to a `stage`, returning a vector of replacement stages."
+ [query :- ::lib.schema/query
+ {:keys [source-table] :as stage} :- ::lib.schema/stage
+ sandbox :- ::sandbox]
+ (let [sandbox-query (sandbox->query query sandbox)
+ sandbox-query (project-only-columns-from-original-table query sandbox-query source-table)
+ new-source-stages (mapv (fn [stage]
+ (assoc stage :query-permissions/sandboxed-table source-table))
+ (:stages sandbox-query))
+ ;; merge stage metadata in the last source stage if needed
+ new-source-stages (m/update-existing-in new-source-stages
+ [(dec (count new-source-stages)) :lib/stage-metadata :columns]
+ (fn [cols]
+ (merge-original-table-metadata
+ cols
+ (lib/returned-columns query (lib.metadata/table query source-table)))))
+ replacement-stages (conj new-source-stages
+ (dissoc stage :source-table))]
+ (log/tracef "Applied Sandbox: replaced stage\n\n%s\n\nwith stages\n\n%s"
+ (u/cprint-to-str stage)
+ (u/cprint-to-str replacement-stages))
+ replacement-stages))
+
+(mu/defn- apply-sandboxes :- ::lib.schema/query
+ "Replace `:source-table` entries that refer to Tables for which we have applicable Sandboxes with `:source-query`
+ entries from their Sandboxes."
+ [query :- ::lib.schema/query
+ table-id->sandbox :- [:map-of ::lib.schema.id/table ::sandbox]]
+ ;; replace stages that have `:source-table` key and a matching entry in `table-id->sandbox`, but do not have
+ ;; `::sandbox?` key
+ (lib.walk/walk-stages
+ query
+ (fn [query _path stage]
+ (when (and (= (:lib/type stage) :mbql.stage/mbql)
+ (:source-table stage)
+ (not (::sandbox? stage)))
+ (when-let [sandbox (get table-id->sandbox (:source-table stage))]
+ ;; add a `::sandbox?` key to each replacement stage that has `:source-table?` so when we do a second pass after
+ ;; adding JOINs they don't get processed again
+ (mapv (fn [stage]
+ (cond-> stage
+ (:source-table stage) (assoc ::sandbox? true)))
+ (apply-sandbox-to-stage query stage sandbox)))))))
+
+(mu/defn- expected-cols :- [:sequential ::mbql.s/legacy-column-metadata]
+ [query :- ::lib.schema/query]
+ (mapv lib/lib-metadata-column->legacy-metadata-column
+ (lib.metadata.result-metadata/returned-columns query)))
+
+(defn- sandboxed-query
+ "Apply Sandboxes to `query` and return the updated version of `query`."
+ [original-query table-id->sandbox]
+ (let [sandboxed-query (apply-sandboxes original-query table-id->sandbox)]
+ (if (= sandboxed-query original-query)
+ original-query
+ (assoc sandboxed-query ::original-metadata (expected-cols original-query)))))
+
+(mu/defn- apply-sandboxing* :- ::lib.schema/query
+ [query :- ::lib.schema/query]
+ (or (when (not api/*is-superuser?*)
+ (when-let [table-id->sandbox (when *current-user-id*
+ (query->table-id->sandbox query))]
+ (sandboxed-query query table-id->sandbox)))
+ query))
+
+(defenterprise apply-sandboxing
+ "Pre-processing middleware. Replaces source tables a User was querying against with source queries that (presumably)
+ restrict the rows returned, based on presence of sandboxes."
+ :feature :sandboxes
+ [query]
+ (apply-sandboxing* query))
+
+;;;; Post-processing
+
+(mu/defn- merge-metadata :- [:map
+ [:cols [:sequential ::mbql.s/legacy-column-metadata]]]
+ "Merge column metadata from the non-sandboxed version of the query into the sandboxed results `metadata`. This way the
+ final results metadata coming back matches what we'd get if the query was not running in a sandbox."
+ [original-metadata :- [:sequential ::mbql.s/legacy-column-metadata]
+ metadata :- [:map
+ [:cols [:sequential ::mbql.s/legacy-column-metadata]]]]
+ (letfn [(merge-cols [cols]
+ (let [col-name->expected-col (m/index-by :name original-metadata)]
+ (for [col cols]
+ (merge
+ col
+ (get col-name->expected-col (:name col))))))]
+ (update metadata :cols merge-cols)))
+
+(defenterprise merge-sandboxing-metadata
+ "Post-processing middleware. Merges in column metadata from the original, unsandboxed version of the query."
+ :feature :sandboxes
+ [{::keys [original-metadata] :as query} rff]
+ (fn merge-sandboxing-metadata-rff* [metadata]
+ (let [metadata (assoc metadata :is_sandboxed (some? (lib.util.match/match-one query
+ (m :guard (every-pred map? :query-permissions/sandboxed-table)))))
+ metadata (if original-metadata
+ (merge-metadata original-metadata metadata)
+ metadata)]
+ (rff metadata))))
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index 7015554755c..4c1d4a411fe 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -57,11 +57,10 @@
"CommentReaction"
"ConnectionImpersonation"
"ContentTranslation"
- "DatabaseRouter"
"DashboardBookmark"
"DataPermissions"
+ "DatabaseRouter"
"DocumentBookmark"
- "GroupTableAccessPolicy"
"HTTPAction"
"ImplicitAction"
"LoginHistory"
@@ -70,9 +69,9 @@
"ModerationReview"
"Notification"
"NotificationCard"
- "NotificationSubscription"
"NotificationHandler"
"NotificationRecipient"
+ "NotificationSubscription"
"Permissions"
"PermissionsGroup"
"PermissionsGroupMembership"
@@ -90,6 +89,7 @@
"QueryTable"
"RecentViews"
"Revision"
+ "Sandbox"
"SearchIndexMetadata"
"Secret"
"Session"
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
index 3d16e9cbcdc..e93b43da22e 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
@@ -88,8 +88,8 @@
(testing "A new database defaults to `:blocked` if the group has a sandbox for any table"
(mt/with-temp [:model/Table {table-id :id} {:db_id db-id}
- :model/GroupTableAccessPolicy _ {:group_id group-id
- :table_id table-id}
+ :model/Sandbox _ {:group_id group-id
+ :table_id table-id}
:model/Database {db-id-2 :id} {}]
(is (= :blocked (perm-value db-id-2)))))))))
@@ -115,8 +115,8 @@
(testing "A new table defaults to `:blocked` if the group has a sandbox for any existing table"
(data-perms/set-table-permission! group-id table-id-1 :perms/view-data :unrestricted)
- (mt/with-temp [:model/GroupTableAccessPolicy _ {:group_id group-id
- :table_id table-id-1}
+ (mt/with-temp [:model/Sandbox _ {:group_id group-id
+ :table_id table-id-1}
:model/Table {table-id-3 :id} {:db_id db-id :schema "PUBLIC"}]
(is (nil? (perm-value nil)))
(is (= :unrestricted (perm-value table-id-1)))
@@ -145,10 +145,10 @@
(data-perms/set-database-permission! all-users-group-id db-id :perms/view-data :unrestricted)
(mt/with-temp [:model/Card {card-id :id} {}
:model/Table {table-id :id} {:db_id db-id}
- :model/GroupTableAccessPolicy _ {:table_id table-id
- :group_id all-users-group-id
- :card_id card-id
- :attribute_remappings {"foo" 1}}]
+ :model/Sandbox _ {:table_id table-id
+ :group_id all-users-group-id
+ :card_id card-id
+ :attribute_remappings {"foo" 1}}]
(is (= :blocked (advanced-permissions.common/new-group-view-data-permission-level db-id)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/permissions/block_permissions_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/permissions/block_permissions_test.clj
index 0af90dff74f..285bfcd35dc 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/permissions/block_permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/models/permissions/block_permissions_test.clj
@@ -108,11 +108,11 @@
(mt/with-premium-features #{:sandboxes :advanced-permissions}
(mt/with-model-cleanup [:model/Permissions]
(mt/with-temp [:model/PermissionsGroup {group-id :id} {}
- :model/GroupTableAccessPolicy _ {:table_id (mt/id :venues)
- :group_id group-id}]
+ :model/Sandbox _ {:table_id (mt/id :venues)
+ :group_id group-id}]
(grant-block-perms! group-id)
(is (nil? (test-db-perms group-id)))
- (is (not (t2/exists? :model/GroupTableAccessPolicy :group_id group-id))))))))
+ (is (not (t2/exists? :model/Sandbox :group_id group-id))))))))
(deftest update-graph-data-perms-should-delete-block-perms-test
(testing "granting data permissions for a table should not delete existing block permissions"
@@ -387,7 +387,6 @@
;; rasta has access to the database:
(is (= [[1]]
(mt/rows (mt/user-http-request :rasta :post 202 (format "card/%d/query" card-id)))))
-
;; block a single table on the db:
(let [tables-in-db (map :id (:tables (t2/hydrate (t2/select-one :model/Database db-id) :tables)))
table-id (rand-nth tables-in-db)]
@@ -401,10 +400,10 @@
(mt/with-premium-features #{:advanced-permissions :sandboxes}
(mt/with-no-data-perms-for-all-users!
(mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/native-query {:query "SELECT ID FROM CHECKINS"})}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id (perms/all-users-group))
- :table_id (mt/id :checkins)
- :card_id card-id
- :attribute_remappings {}}
+ :model/Sandbox _ {:group_id (u/the-id (perms/all-users-group))
+ :table_id (mt/id :checkins)
+ :card_id card-id
+ :attribute_remappings {}}
:model/Card {query-card-id :id} {:dataset_query (mt/mbql-query checkins
{:aggregation [[:count]]
:joins [{:source-table $$venues
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/query_processor/middleware/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/query_processor/middleware/permissions_test.clj
index 553e1e7ab21..37e05a4e8c1 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/query_processor/middleware/permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/query_processor/middleware/permissions_test.clj
@@ -3,7 +3,7 @@
[clojure.data.csv :as csv]
[clojure.test :refer :all]
[metabase-enterprise.advanced-permissions.query-processor.middleware.permissions :as ee.qp.perms]
- [metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions :as row-level-restrictions]
+ [metabase-enterprise.sandbox.query-processor.middleware.sandboxing :as sandboxing]
[metabase.legacy-mbql.normalize :as mbql.normalize]
[metabase.lib.test-metadata :as meta]
[metabase.lib.util.match :as lib.util.match]
@@ -37,7 +37,7 @@
(defn- apply-row-level-permissions [query]
(-> (qp.store/with-metadata-provider (mt/id)
- (#'row-level-restrictions/apply-sandboxing (mbql.normalize/normalize query)))
+ (#'sandboxing/apply-sandboxing (mbql.normalize/normalize query)))
remove-metadata))
(defmacro ^:private with-download-perms!
@@ -161,10 +161,10 @@
(testing "Applying a basic sandbox does not affect the download permissions for a table"
(mt/with-current-user (mt/user->id :rasta)
(mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/mbql-query checkins {:filter [:> $date "2014-01-01"]})}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id (perms/all-users-group))
- :table_id (mt/id :checkins)
- :card_id card-id
- :attribute_remappings {}}]
+ :model/Sandbox _ {:group_id (u/the-id (perms/all-users-group))
+ :table_id (mt/id :checkins)
+ :card_id card-id
+ :attribute_remappings {}}]
(with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :users) :full
(mt/id :categories) :none
(mt/id :venues) :limited
@@ -182,10 +182,10 @@
(testing "Applying a advanced sandbox does not affect the download permissions for a table"
(mt/with-current-user (mt/user->id :rasta)
(mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/native-query {:query "SELECT ID FROM CHECKINS"})}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id (perms/all-users-group))
- :table_id (mt/id :checkins)
- :card_id card-id
- :attribute_remappings {}}]
+ :model/Sandbox _ {:group_id (u/the-id (perms/all-users-group))
+ :table_id (mt/id :checkins)
+ :card_id card-id
+ :attribute_remappings {}}]
(with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :users) :full
(mt/id :categories) :none
(mt/id :venues) :limited
@@ -439,10 +439,10 @@
(mt/with-full-data-perms-for-all-users!
(with-redefs [ee.qp.perms/max-rows-in-limited-downloads 3]
(mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/native-query {:query "SELECT ID FROM CHECKINS"})}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id (perms/all-users-group))
- :table_id (mt/id :checkins)
- :card_id card-id
- :attribute_remappings {}}]
+ :model/Sandbox _ {:group_id (u/the-id (perms/all-users-group))
+ :table_id (mt/id :checkins)
+ :card_id card-id
+ :attribute_remappings {}}]
(with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :categories) :none
(mt/id :checkins) :full}}}
(streaming-test/do-test!
diff --git a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
index e7b73955afe..a082414bcde 100644
--- a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
@@ -94,7 +94,7 @@
:model/UserParameterValue
:model/UserKeyValue
:model/ViewLog
- :model/GroupTableAccessPolicy
+ :model/Sandbox
:model/ConnectionImpersonation
:model/CloudMigration
:model/Comment
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/card_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/card_test.clj
index 0639098029e..0e656169ede 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/card_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/card_test.clj
@@ -18,8 +18,8 @@
:model/Table table {:db_id (u/the-id db)}
:model/Field _field {:table_id (u/the-id table) :name "field"}
:model/PermissionsGroup group {}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id group)
- :table_id (u/the-id table)}]
+ :model/Sandbox _ {:group_id (u/the-id group)
+ :table_id (u/the-id table)}]
(perms/add-user-to-group! (mt/user->id :rasta) group)
(mt/with-db db
(mt/with-no-data-perms-for-all-users!
@@ -40,8 +40,8 @@
:model/PermissionsGroup group {}
:model/Card card {:name "Some Name"
:collection_id (u/the-id collection)}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id group)
- :table_id (u/the-id table)}]
+ :model/Sandbox _ {:group_id (u/the-id group)
+ :table_id (u/the-id table)}]
(perms/add-user-to-group! (mt/user->id :rasta) group)
(mt/with-db db
(mt/with-no-data-perms-for-all-users!
@@ -64,8 +64,8 @@
:model/PermissionsGroup group {}
:model/Card card {:name "Some Name"
:collection_id (u/the-id collection)}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id group)
- :table_id (u/the-id table)}]
+ :model/Sandbox _ {:group_id (u/the-id group)
+ :table_id (u/the-id table)}]
(perms/add-user-to-group! (mt/user->id :rasta) group)
(mt/with-db db
(mt/with-no-data-perms-for-all-users!
@@ -86,8 +86,8 @@
:model/Table other-table {:db_id (u/the-id db)}
:model/Field _field {:table_id (u/the-id table) :name "field"}
:model/PermissionsGroup group {}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id group)
- :table_id (u/the-id table)}]
+ :model/Sandbox _ {:group_id (u/the-id group)
+ :table_id (u/the-id table)}]
(perms/add-user-to-group! (mt/user->id :rasta) group)
(mt/with-db db
(mt/with-no-data-perms-for-all-users!
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
index 49e3df36576..99194864a8d 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
@@ -26,11 +26,11 @@
:attribute_remappings {:foo 1}})
(defmacro ^:private with-gtap-cleanup!
- "Invokes `body` ensuring any `GroupTableAccessPolicy` created will be removed afterward. Leaving behind a GTAP can
+ "Invokes `body` ensuring any `Sandbox` created will be removed afterward. Leaving behind a GTAP can
case referential integrity failures for any related `Card` that would be cleaned up as part of a `with-temp*` call"
[& body]
`(mt/with-premium-features #{:sandboxes}
- (mt/with-model-cleanup [:model/GroupTableAccessPolicy]
+ (mt/with-model-cleanup [:model/Sandbox]
~@body)))
(defn- gtap-post
@@ -60,12 +60,12 @@
:model/PermissionsGroup {group-id-1 :id} {}
:model/PermissionsGroup {group-id-2 :id} {}
:model/Card {card-id :id} {}
- :model/GroupTableAccessPolicy {gtap-id-1 :id} {:table_id table-id-1
- :group_id group-id-1
- :card_id card-id}
- :model/GroupTableAccessPolicy {gtap-id-2 :id} {:table_id table-id-2
- :group_id group-id-2
- :card_id card-id}]
+ :model/Sandbox {gtap-id-1 :id} {:table_id table-id-1
+ :group_id group-id-1
+ :card_id card-id}
+ :model/Sandbox {gtap-id-2 :id} {:table_id table-id-2
+ :group_id group-id-2
+ :card_id card-id}]
(testing "Test that we can fetch the list of all GTAPs"
(is (partial=
[{:id gtap-id-1 :table_id table-id-1 :group_id group-id-1}
@@ -192,40 +192,40 @@
:model/Card {card-id :id} {}]
(mt/with-premium-features #{:sandboxes}
(testing "Test that we can update only the attribute remappings for a GTAP"
- (mt/with-temp [:model/GroupTableAccessPolicy {gtap-id :id} {:table_id table-id
- :group_id group-id
- :card_id card-id
- :attribute_remappings {"foo" 1}}]
+ (mt/with-temp [:model/Sandbox {gtap-id :id} {:table_id table-id
+ :group_id group-id
+ :card_id card-id
+ :attribute_remappings {"foo" 1}}]
(is (= (assoc default-gtap-results :attribute_remappings {:bar 2})
(mt/boolean-ids-and-timestamps
(mt/user-http-request :crowberto :put 200 (format "mt/gtap/%s" gtap-id)
{:attribute_remappings {:bar 2}}))))))
(testing "Test that we can add a card_id via PUT"
- (mt/with-temp [:model/GroupTableAccessPolicy {gtap-id :id} {:table_id table-id
- :group_id group-id
- :card_id nil
- :attribute_remappings {"foo" 1}}]
+ (mt/with-temp [:model/Sandbox {gtap-id :id} {:table_id table-id
+ :group_id group-id
+ :card_id nil
+ :attribute_remappings {"foo" 1}}]
(is (= default-gtap-results
(mt/boolean-ids-and-timestamps
(mt/user-http-request :crowberto :put 200 (format "mt/gtap/%s" gtap-id)
{:card_id card-id}))))))
(testing "Test that we can remove a card_id via PUT"
- (mt/with-temp [:model/GroupTableAccessPolicy {gtap-id :id} {:table_id table-id
- :group_id group-id
- :card_id card-id
- :attribute_remappings {"foo" 1}}]
+ (mt/with-temp [:model/Sandbox {gtap-id :id} {:table_id table-id
+ :group_id group-id
+ :card_id card-id
+ :attribute_remappings {"foo" 1}}]
(is (= (assoc default-gtap-results :card_id false)
(mt/boolean-ids-and-timestamps
(mt/user-http-request :crowberto :put 200 (format "mt/gtap/%s" gtap-id)
{:card_id nil}))))))
(testing "Test that we can remove a card_id and change attribute remappings via PUT"
- (mt/with-temp [:model/GroupTableAccessPolicy {gtap-id :id} {:table_id table-id
- :group_id group-id
- :card_id card-id
- :attribute_remappings {"foo" 1}}]
+ (mt/with-temp [:model/Sandbox {gtap-id :id} {:table_id table-id
+ :group_id group-id
+ :card_id card-id
+ :attribute_remappings {"foo" 1}}]
(is (= (assoc default-gtap-results :card_id false, :attribute_remappings {:bar 2})
(mt/boolean-ids-and-timestamps
(mt/user-http-request :crowberto :put 200 (format "mt/gtap/%s" gtap-id)
@@ -255,10 +255,10 @@
:card_id card-id-1
:attribute_remappings {:foo 1}}]
(:sandboxes result)))
- (is (t2/exists? :model/GroupTableAccessPolicy :table_id table-id-1 :group_id group-id))))
+ (is (t2/exists? :model/Sandbox :table_id table-id-1 :group_id group-id))))
(testing "Test that we can update a sandbox using the permission graph API"
- (let [sandbox-id (t2/select-one-fn :id :model/GroupTableAccessPolicy
+ (let [sandbox-id (t2/select-one-fn :id :model/Sandbox
:table_id table-id-1
:group_id group-id)
graph (-> (data-perms.graph/api-graph)
@@ -270,12 +270,12 @@
(:sandboxes result)))
(is (partial= {:card_id card-id-2
:attribute_remappings {"foo" 2}}
- (t2/select-one :model/GroupTableAccessPolicy
+ (t2/select-one :model/Sandbox
:table_id table-id-1
:group_id group-id)))))
(testing "Test that we can create and update multiple sandboxes at once using the permission graph API"
- (let [sandbox-id (t2/select-one-fn :id :model/GroupTableAccessPolicy
+ (let [sandbox-id (t2/select-one-fn :id :model/Sandbox
:table_id table-id-1
:group_id group-id)
graph (-> (data-perms.graph/api-graph)
@@ -294,13 +294,13 @@
;; Updated sandbox
(is (partial= {:card_id card-id-1
:attribute_remappings {"foo" 3}}
- (t2/select-one :model/GroupTableAccessPolicy
+ (t2/select-one :model/Sandbox
:table_id table-id-1
:group_id group-id)))
;; Created sandbox
(is (partial= {:card_id card-id-2
:attribute_remappings {"foo" 10}}
- (t2/select-one :model/GroupTableAccessPolicy
+ (t2/select-one :model/Sandbox
:table_id table-id-2
:group_id group-id))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj
index 43a86bf580b..9f0fcb29f3e 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj
@@ -50,17 +50,17 @@
[:table_id [:= (mt/id :venues)]]
[:card_id nil?]
[:attribute_remappings nil?]]]
- (t2/select :model/GroupTableAccessPolicy :group_id (u/the-id &group))))))
+ (t2/select :model/Sandbox :group_id (u/the-id &group))))))
(let [graph (mt/user-http-request :crowberto :get 200 "permissions/graph")
graph' (assoc-in graph (db-graph-keypath &group) (updated-db-perms))
response (mt/user-http-request :crowberto :put 200 "permissions/graph" graph')]
(mt/with-temp [:model/Database db-2 {}
:model/Table db-2-table {:db_id (u/the-id db-2)}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id &group)
- :table_id (u/the-id db-2-table)}
+ :model/Sandbox _ {:group_id (u/the-id &group)
+ :table_id (u/the-id db-2-table)}
:model/PermissionsGroup other-group {}
- :model/GroupTableAccessPolicy _ {:group_id (u/the-id other-group)
- :table_id (mt/id :venues)}]
+ :model/Sandbox _ {:group_id (u/the-id other-group)
+ :table_id (mt/id :venues)}]
(testing "perms graph should be updated"
(testing "in API request response"
(is (= (expected-perms)
@@ -71,7 +71,7 @@
(db-graph-keypath &group))))))
(testing "GTAP should be deleted from application DB"
(is (= []
- (t2/select :model/GroupTableAccessPolicy
+ (t2/select :model/Sandbox
:group_id (u/the-id &group)
:table_id (mt/id :venues)))))
(testing "GTAP for same group, other database should not be affected"
@@ -82,7 +82,7 @@
[:table_id [:= (u/the-id db-2-table)]]
[:card_id nil?]
[:attribute_remappings nil?]]]
- (t2/select :model/GroupTableAccessPolicy
+ (t2/select :model/Sandbox
:group_id (u/the-id &group)
:table_id (u/the-id db-2-table)))))
(testing "GTAP for same table, other group should not be affected"
@@ -93,20 +93,20 @@
[:table_id [:= (mt/id :venues)]]
[:card_id nil?]
[:attribute_remappings nil?]]]
- (t2/select :model/GroupTableAccessPolicy :group_id (u/the-id other-group)))))))))))))
+ (t2/select :model/Sandbox :group_id (u/the-id other-group)))))))))))))
(deftest grant-sandbox-perms-dont-delete-gtaps-test
(testing "PUT /api/permissions/graph"
(testing "granting sandboxed permissions for a group should *not* delete an associated GTAP (#16190)"
(mt/with-temp-copy-of-db
- (mt/with-temp [:model/GroupTableAccessPolicy _ {:group_id (u/the-id (perms-group/all-users))
- :table_id (mt/id :venues)}]
+ (mt/with-temp [:model/Sandbox _ {:group_id (u/the-id (perms-group/all-users))
+ :table_id (mt/id :venues)}]
(let [graph (mt/user-http-request :crowberto :get 200 "permissions/graph")
graph' (assoc-in graph (db-graph-keypath (perms-group/all-users))
{"PUBLIC" {(mt/id :venues) "sandboxed"}})]
(mt/user-http-request :crowberto :put 200 "permissions/graph" graph')
(testing "GTAP should not have been deleted"
- (is (t2/exists? :model/GroupTableAccessPolicy :group_id (u/the-id (perms-group/all-users)), :table_id (mt/id :venues))))))))))
+ (is (t2/exists? :model/Sandbox :group_id (u/the-id (perms-group/all-users)), :table_id (mt/id :venues))))))))))
(defn- fake-persist-card! [card]
(let [persisted-info (persisted-info/turn-on-model! (mt/user->id :rasta) card)]
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/util_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/util_test.clj
index f7082140064..9769def43b5 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/util_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/util_test.clj
@@ -16,7 +16,7 @@
(doall @data-perms/*sandboxes-for-user*)
;; make the cache wrong
- (t2/delete! :model/GroupTableAccessPolicy :group_id (:id &group))
+ (t2/delete! :model/Sandbox :group_id (:id &group))
;; subsequent calls should still use the cache, and not hit the DB at all
(t2/with-call-count [call-count]
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
index b8a172b4c3f..85eb27c50f2 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/models/params/field_values_test.clj
@@ -23,7 +23,7 @@
:human_readable_values (map #(str "id_" %) (range 10))})
(let [categories-id (mt/id :categories :id)
f (t2/select-one :model/Field :id (mt/id :categories :id))
- card-id (-> f :table_id (#'ee-params.field-values/table-id->gtap) :card :id)
+ card-id (-> f :table_id (#'ee-params.field-values/table-id->sandbox) :card :id)
fv (params.field-values/get-or-create-field-values! f)]
(is (= [(range 4 6)]
(t2/select-fn-vec :values :model/FieldValues
@@ -109,10 +109,10 @@
:user_id user-id-1}
:model/PermissionsGroupMembership _ {:group_id group-id
:user_id user-id-2}
- :model/GroupTableAccessPolicy _ {:card_id card-id
- :group_id group-id
- :table_id (mt/id :categories)
- :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}]
+ :model/Sandbox _ {:card_id card-id
+ :group_id group-id
+ :table_id (mt/id :categories)
+ :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}]
(testing "with same attributes, the hash should be the same field"
(is (= (hash-input-for-user-id-with-attributes user-id-1 {"State" "CA"} field)
@@ -140,10 +140,10 @@
:model/User {user-id :id} {}
:model/PermissionsGroupMembership _ {:group_id group-id
:user_id user-id}
- :model/GroupTableAccessPolicy _ {:card_id card-id
- :group_id group-id
- :table_id (mt/id :categories)
- :attribute_remappings {"State" [:variable [:template-tag "STATE"]]}}]
+ :model/Sandbox _ {:card_id card-id
+ :group_id group-id
+ :table_id (mt/id :categories)
+ :attribute_remappings {"State" [:variable [:template-tag "STATE"]]}}]
(testing "same users but if the login_attributes change, they should have different hash (#24966)"
(is (not= (hash-input-for-user-id-with-attributes user-id {"State" "CA"} field)
(hash-input-for-user-id-with-attributes user-id {"State" "NY"} field))))))
@@ -157,19 +157,19 @@
:model/PermissionsGroup {group-id-1 :id} {}
:model/PermissionsGroupMembership _ {:group_id group-id-1
:user_id user-id-1}
- :model/GroupTableAccessPolicy _ {:card_id card-id
- :group_id group-id-1
- :table_id (mt/id :categories)
- :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}
+ :model/Sandbox _ {:card_id card-id
+ :group_id group-id-1
+ :table_id (mt/id :categories)
+ :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}
;; user 2 in group 2 with gtap using the same card
:model/User {user-id-2 :id} {}
:model/PermissionsGroup {group-id-2 :id} {}
:model/PermissionsGroupMembership _ {:group_id group-id-2
:user_id user-id-2}
- :model/GroupTableAccessPolicy _ {:card_id card-id
- :group_id group-id-2
- :table_id (mt/id :categories)
- :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}]
+ :model/Sandbox _ {:card_id card-id
+ :group_id group-id-2
+ :table_id (mt/id :categories)
+ :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}]
(testing "with the same attributes, the hash should be the same"
(is (= (hash-input-for-user-id-with-attributes user-id-1 {"State" "CA"} field)
(hash-input-for-user-id-with-attributes user-id-2 {"State" "CA"} field))))
@@ -185,20 +185,20 @@
:model/PermissionsGroup {group-id-1 :id} {}
:model/PermissionsGroupMembership _ {:group_id group-id-1
:user_id user-id-1}
- :model/GroupTableAccessPolicy _ {:card_id card-id-1
- :group_id group-id-1
- :table_id (mt/id :categories)
- :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}
+ :model/Sandbox _ {:card_id card-id-1
+ :group_id group-id-1
+ :table_id (mt/id :categories)
+ :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}
;; user 2 in group 2 with gtap using card 2
:model/Card {card-id-2 :id} {}
:model/User {user-id-2 :id} {}
:model/PermissionsGroup {group-id-2 :id} {}
:model/PermissionsGroupMembership _ {:group_id group-id-2
:user_id user-id-2}
- :model/GroupTableAccessPolicy _ {:card_id card-id-2
- :group_id group-id-2
- :table_id (mt/id :categories)
- :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}]
+ :model/Sandbox _ {:card_id card-id-2
+ :group_id group-id-2
+ :table_id (mt/id :categories)
+ :attribute_remappings {"State" [:dimension [:field (mt/id :categories :name) nil]]}}]
(testing "the hash are different even though they have the same attribute"
(is (not= (hash-input-for-user-id-with-attributes user-id-1 {"State" "CA"} field)
(hash-input-for-user-id-with-attributes user-id-2 {"State" "CA"} field)))
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/models/group_table_access_policy_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/models/sandbox_test.clj
similarity index 62%
rename from enterprise/backend/test/metabase_enterprise/sandbox/models/group_table_access_policy_test.clj
rename to enterprise/backend/test/metabase_enterprise/sandbox/models/sandbox_test.clj
index 57370fcb8a3..0309a0e7b4e 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/models/group_table_access_policy_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/models/sandbox_test.clj
@@ -1,7 +1,7 @@
-(ns metabase-enterprise.sandbox.models.group-table-access-policy-test
+(ns metabase-enterprise.sandbox.models.sandbox-test
(:require
[clojure.test :refer :all]
- [metabase-enterprise.sandbox.models.group-table-access-policy :as sandboxes]
+ [metabase-enterprise.sandbox.models.sandbox :as sandboxes]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.query-processor.preprocess :as qp.preprocess]
[metabase.test :as mt]
@@ -10,33 +10,33 @@
(deftest normalize-attribute-remappings-test
(testing "make sure attribute-remappings come back from the DB normalized the way we'd expect"
- (mt/with-temp [:model/GroupTableAccessPolicy gtap {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))
- :attribute_remappings {"venue_id"
- {:type "category"
- :target ["variable" ["field" (mt/id :venues :id) nil]]
- :value 5}}}]
+ (mt/with-temp [:model/Sandbox gtap {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))
+ :attribute_remappings {"venue_id"
+ {:type "category"
+ :target ["variable" ["field" (mt/id :venues :id) nil]]
+ :value 5}}}]
(is (= {"venue_id" {:type :category
:target [:variable [:field (mt/id :venues :id) nil]]
:value 5}}
- (t2/select-one-fn :attribute_remappings :model/GroupTableAccessPolicy :id (u/the-id gtap)))))
+ (t2/select-one-fn :attribute_remappings :model/Sandbox :id (u/the-id gtap)))))
(testing (str "apparently sometimes they are saved with just the target, but not type or value? Make sure these "
"get normalized correctly.")
- (mt/with-temp [:model/GroupTableAccessPolicy gtap {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))
- :attribute_remappings {"user" ["variable" ["field" (mt/id :venues :id) nil]]}}]
+ (mt/with-temp [:model/Sandbox gtap {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))
+ :attribute_remappings {"user" ["variable" ["field" (mt/id :venues :id) nil]]}}]
(is (= {"user" [:variable [:field (mt/id :venues :id) nil]]}
- (t2/select-one-fn :attribute_remappings :model/GroupTableAccessPolicy :id (u/the-id gtap))))))))
+ (t2/select-one-fn :attribute_remappings :model/Sandbox :id (u/the-id gtap))))))))
(deftest disallow-changing-table-id-test
(testing "You can't change the table_id of a sandbox after it has been created."
- (mt/with-temp [:model/GroupTableAccessPolicy gtap {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))}]
+ (mt/with-temp [:model/Sandbox gtap {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))}]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"You cannot change the table ID of a sandbox once it has been created"
- (t2/update! :model/GroupTableAccessPolicy (:id gtap) {:table_id (mt/id :checkins)}))))))
+ (t2/update! :model/Sandbox (:id gtap) {:table_id (mt/id :checkins)}))))))
(deftest disallow-queries-that-add-columns-test
(testing "Don't allow saving a Sandboxing query that contains columns not in the Table it replaces (#13715)"
@@ -44,27 +44,27 @@
(fn [query]
(mt/with-temp [:model/Card card {:dataset_query query
:result_metadata (qp.preprocess/query->expected-cols query)}
- :model/GroupTableAccessPolicy _ {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))
- :card_id (:id card)}]
+ :model/Sandbox _ {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))
+ :card_id (:id card)}]
:ok))
"Update an existing GTAP"
(fn [query]
(mt/with-temp [:model/Card card {:dataset_query query
:result_metadata (qp.preprocess/query->expected-cols query)}
- :model/GroupTableAccessPolicy gtap {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))}]
- (t2/update! :model/GroupTableAccessPolicy (:id gtap) {:card_id (:id card)})
+ :model/Sandbox gtap {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))}]
+ (t2/update! :model/Sandbox (:id gtap) {:card_id (:id card)})
:ok))
"Update query for Card associated with an existing GTAP"
(fn [query]
(mt/with-temp [:model/Card card {:dataset_query (mt/mbql-query venues)
:result_metadata (qp.preprocess/query->expected-cols (mt/mbql-query venues))}
- :model/GroupTableAccessPolicy _ {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))
- :card_id (:id card)}]
+ :model/Sandbox _ {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))
+ :card_id (:id card)}]
(t2/update! :model/Card (:id card) {:dataset_query query})
:ok))}]
(testing (str "\n" msg "\n")
@@ -87,27 +87,27 @@
(fn [metadata]
(mt/with-temp [:model/Card card {:dataset_query (mt/mbql-query venues)
:result_metadata metadata}
- :model/GroupTableAccessPolicy _ {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))
- :card_id (:id card)}]
+ :model/Sandbox _ {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))
+ :card_id (:id card)}]
:ok))
"Update an existing GTAP"
(fn [metadata]
(mt/with-temp [:model/Card card {:dataset_query (mt/mbql-query venues)
:result_metadata metadata}
- :model/GroupTableAccessPolicy gtap {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))}]
- (t2/update! :model/GroupTableAccessPolicy (:id gtap) {:card_id (:id card)})
+ :model/Sandbox gtap {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))}]
+ (t2/update! :model/Sandbox (:id gtap) {:card_id (:id card)})
:ok))
"Update query for Card associated with an existing GTAP"
(fn [metadata]
(mt/with-temp [:model/Card card {:dataset_query (mt/mbql-query venues)
:result_metadata (qp.preprocess/query->expected-cols (mt/mbql-query venues))}
- :model/GroupTableAccessPolicy _ {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))
- :card_id (:id card)}]
+ :model/Sandbox _ {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))
+ :card_id (:id card)}]
(t2/update! :model/Card (:id card) {:result_metadata metadata})
:ok))}]
(testing (str "\n" msg "\n")
@@ -126,8 +126,8 @@
(mt/with-premium-features #{:sandboxes}
(mt/with-full-data-perms-for-all-users!
(testing "Sandbox definitions in the DB are automatically added to the permissions graph"
- (mt/with-temp [:model/GroupTableAccessPolicy _gtap {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))}]
+ (mt/with-temp [:model/Sandbox _gtap {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))}]
(is (partial=
{(u/the-id (perms-group/all-users))
{(mt/id)
@@ -137,8 +137,8 @@
(sandboxes/add-sandboxes-to-permissions-graph {})))))
(testing "When perms are set at the DB level, incorporating a sandbox breaks them out to table-level"
- (mt/with-temp [:model/GroupTableAccessPolicy _gtap {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))}]
+ (mt/with-temp [:model/Sandbox _gtap {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))}]
(is (partial=
{(u/the-id (perms-group/all-users))
{(mt/id)
@@ -150,8 +150,8 @@
{:view-data :unrestricted}}})))))
(testing "When perms are set at the schema level, incorporating a sandbox breaks them out to table-level"
- (mt/with-temp [:model/GroupTableAccessPolicy _gtap {:table_id (mt/id :venues)
- :group_id (u/the-id (perms-group/all-users))}]
+ (mt/with-temp [:model/Sandbox _gtap {:table_id (mt/id :venues)
+ :group_id (u/the-id (perms-group/all-users))}]
(is (partial=
{(u/the-id (perms-group/all-users))
{(mt/id)
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj
similarity index 87%
rename from enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj
rename to enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj
index 439e90a7132..be8ee8683df 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj
@@ -1,16 +1,15 @@
-(ns ^:mb/driver-tests metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test
+(ns ^:mb/driver-tests metabase-enterprise.sandbox.query-processor.middleware.sandboxing-test
(:require
[clojure.core.async :as a]
[clojure.string :as str]
[clojure.test :refer :all]
[medley.core :as m]
- [metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions :as row-level-restrictions]
+ [metabase-enterprise.sandbox.query-processor.middleware.sandboxing :as sandboxing]
[metabase-enterprise.test :as met]
[metabase.api.common :as api]
[metabase.driver :as driver]
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.util :as driver.u]
- [metabase.legacy-mbql.normalize :as mbql.normalize]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-util :as lib.tu]
@@ -76,8 +75,8 @@
(= driver/*driver* :sqlserver)
add-top-1000
- ;; SparkSQL has to have an alias source table (or at least our driver is written as if it has to
- ;; have one.) HACK
+ ;; SparkSQL has to have an alias source table (or at least our driver is written as if it has to
+ ;; have one.) HACK
(= driver/*driver* :sparksql)
(update :from (fn [[table]]
[[table [(sql.qp/->honeysql
@@ -85,7 +84,7 @@
(h2x/identifier :table-alias @(resolve 'metabase.driver.sparksql/source-table-alias)))]]])))]
(first (sql.qp/format-honeysql driver/*driver* honeysql))))
-(defn- venues-category-native-gtap-def []
+(defn- venues-category-native-sandbox-def []
(driver/with-driver (or driver/*driver* :h2)
(assert (driver.u/supports? driver/*driver* :native-parameters (mt/db)))
{:query (mt/native-query
@@ -102,7 +101,9 @@
{:cat {:name "cat" :display_name "cat" :type "number" :required true}}})
:remappings {:cat ["variable" ["template-tag" "cat"]]}}))
-(defn- parameterized-sql-with-join-gtap-def []
+(defn- parameterized-sql-with-join-sandbox-def
+ "A SQL query for `CHECKINS` that only returns `ID` and `USER_ID`. It includes a join against `VENUES`."
+ []
(driver/with-driver (or driver/*driver* :h2)
(assert (driver.u/supports? driver/*driver* :native-parameters (mt/db)))
{:query (mt/native-query
@@ -110,6 +111,8 @@
(format-honeysql
{:select [[(identifier :checkins :id)]
[(identifier :checkins :user_id)]
+ ;; these columns are ILLEGAL, you're NOT allowed to add columns not in the original table.
+ ;; We should complain loudly and then ignore them.
[(identifier :venues :name)]
[(identifier :venues :category_id)]]
:from [[(identifier :checkins)]]
@@ -127,7 +130,7 @@
:required true}}})
:remappings {:user ["variable" ["template-tag" "user"]]}}))
-(defn- venue-names-native-gtap-def []
+(defn- venue-names-native-sandbox-def []
(driver/with-driver (or driver/*driver* :h2)
{:query (mt/native-query
{:query
@@ -152,18 +155,6 @@
:order-by [[:asc $venue_id->venues.price]]
:breakout [$venue_id->venues.price]}))))
-(deftest ^:parallel all-table-ids-test
- (testing (str "make sure that `all-table-ids` can properly find all Tables in the query, even in cases where a map "
- "has a `:source-table` and some of its children also have a `:source-table`"))
- (is (= (mt/$ids nil
- #{$$checkins $$venues $$users $$categories})
- (#'row-level-restrictions/all-table-ids
- (mt/mbql-query nil
- {:source-table $$checkins
- :joins [{:source-table $$venues}
- {:source-query {:source-table $$users
- :joins [{:source-table $$categories}]}}]})))))
-
;; TODO -- #19754 adds [[mt/remove-source-metadata]] that can be used here (once it gets merged)
(defn- remove-metadata [m]
(lib.util.match/replace m
@@ -171,8 +162,9 @@
(remove-metadata (dissoc &match :source-metadata))))
(defn- apply-row-level-permissions [query]
- (-> (qp.store/with-metadata-provider (mt/id)
- (#'row-level-restrictions/apply-sandboxing (mbql.normalize/normalize query)))
+ (-> (lib/query (mt/metadata-provider) query)
+ (#'sandboxing/apply-sandboxing)
+ lib/->legacy-MBQL
remove-metadata))
(deftest middleware-test
@@ -200,8 +192,8 @@
[:value 5 {:base_type :type/Integer
:semantic_type :type/FK
:database_type "INTEGER"}]]]
- ::row-level-restrictions/gtap? true
- :query-permissions/gtapped-table $$checkins}
+ ::sandboxing/sandbox? true
+ :query-permissions/sandboxed-table $$checkins}
:joins [{:source-query
{:source-table $$venues
:fields [$venues.id $venues.name $venues.category_id
@@ -211,19 +203,19 @@
[:value 1 {:base_type :type/Integer
:semantic_type :type/Category
:database_type "INTEGER"}]]
- ::row-level-restrictions/gtap? true
- :query-permissions/gtapped-table $$venues}
+ ::sandboxing/sandbox? true
+ :query-permissions/sandboxed-table $$venues}
:alias "v"
:strategy :left-join
:condition [:= $venue_id &v.venues.id]}]
:aggregation [[:count]]}
- ::row-level-restrictions/original-metadata [{:base_type :type/Integer
- :semantic_type :type/Quantity
- :name "count"
- :display_name "Count"
- :source :aggregation
- :field_ref [:aggregation 0]}]})
+ ::sandboxing/original-metadata [{:base_type :type/Integer
+ :semantic_type :type/Quantity
+ :name "count"
+ :display_name "Count"
+ :source :aggregation
+ :field_ref [:aggregation 0]}]})
(apply-row-level-permissions
(mt/mbql-query checkins
{:aggregation [[:count]]
@@ -235,7 +227,7 @@
(deftest middleware-native-query-test
(testing "Make sure the middleware does the correct transformation given the GTAPs we have"
(testing "Should substitute appropriate value in native query"
- (met/with-gtaps! {:gtaps {:venues (venues-category-native-gtap-def)}
+ (met/with-gtaps! {:gtaps {:venues (venues-category-native-sandbox-def)}
:attributes {"cat" 50}}
(is (=? (mt/query nil
{:database (mt/id)
@@ -244,15 +236,15 @@
:source-query {:native (str "SELECT * FROM \"PUBLIC\".\"VENUES\" "
"WHERE \"PUBLIC\".\"VENUES\".\"CATEGORY_ID\" = 50 "
"ORDER BY \"PUBLIC\".\"VENUES\".\"ID\" ASC")
- :query-permissions/gtapped-table $$venues
+ :query-permissions/sandboxed-table $$venues
:params []}}
- ::row-level-restrictions/original-metadata [{:base_type :type/Integer
- :semantic_type :type/Quantity
- :name "count"
- :display_name "Count"
- :source :aggregation
- :field_ref [:aggregation 0]}]})
+ ::sandboxing/original-metadata [{:base_type :type/Integer
+ :semantic_type :type/Quantity
+ :name "count"
+ :display_name "Count"
+ :source :aggregation
+ :field_ref [:aggregation 0]}]})
(apply-row-level-permissions
(mt/mbql-query venues
{:aggregation [[:count]]}))))))))
@@ -270,7 +262,7 @@
(deftest e2e-test-1
(mt/test-drivers (e2e-test-drivers)
(testing "Basic test around querying a table by a user with segmented only permissions and a GTAP question that is a native query"
- (met/with-gtaps! {:gtaps {:venues (venues-category-native-gtap-def)}, :attributes {"cat" 50}}
+ (met/with-gtaps! {:gtaps {:venues (venues-category-native-sandbox-def)}, :attributes {"cat" 50}}
(is (= [[10]]
(run-venues-count-query)))))))
@@ -320,7 +312,7 @@
(deftest e2e-test-7
(mt/test-drivers (e2e-test-drivers)
(testing "Tests that users can have a different parameter name in their query than they have in their user attributes"
- (met/with-gtaps! {:gtaps {:venues {:query (:query (venues-category-native-gtap-def))
+ (met/with-gtaps! {:gtaps {:venues {:query (:query (venues-category-native-sandbox-def))
:remappings {:something.different ["variable" ["template-tag" "cat"]]}}}
:attributes {"something.different" 50}}
(is (= [[10]]
@@ -329,7 +321,7 @@
(deftest e2e-test-8
(mt/test-drivers (e2e-test-drivers)
(testing "Make sure that you can still use a SQL-based GTAP without needing to have SQL read perms for the Database"
- (met/with-gtaps! {:gtaps {:venues (venue-names-native-gtap-def)}}
+ (met/with-gtaps! {:gtaps {:venues (venue-names-native-sandbox-def)}}
(is (= [[1 "Red Medicine"] [2 "Stout Burgers & Beers"]]
(mt/formatted-rows
[int str]
@@ -417,18 +409,18 @@
;; Test that we can follow FKs to related tables and breakout by columns on those related tables. This test has
;; several things wrapped up which are detailed below
-(defn- row-level-restrictions-fk-drivers
+(defn- sandboxing-fk-drivers
"Drivers to test row-level restrictions against foreign keys with."
[]
(mt/normal-drivers-with-feature :nested-queries :left-join))
-(defn- row-level-restrictions-fk-sql-drivers
+(defn- sandboxing-fk-sql-drivers
"SQL drivers to test row-level restrictions against foreign keys with."
[]
- (into #{} (filter #(isa? driver/hierarchy % :sql)) (row-level-restrictions-fk-drivers)))
+ (into #{} (filter #(isa? driver/hierarchy % :sql)) (sandboxing-fk-drivers)))
(deftest e2e-fks-test
- (mt/test-drivers (row-level-restrictions-fk-drivers)
+ (mt/test-drivers (sandboxing-fk-drivers)
(testing (str "1 - Creates a GTAP filtering question, looking for any checkins happening on or after 2014\n"
"2 - Apply the `user` attribute, looking for only our user (i.e. `user_id` = 5)\n"
"3 - Checkins are related to Venues, query for checkins, grouping by the Venue's price\n"
@@ -440,7 +432,7 @@
(run-checkins-count-broken-out-by-price-query)))))))
(deftest e2e-fks-test-2
- (mt/test-drivers (row-level-restrictions-fk-drivers)
+ (mt/test-drivers (sandboxing-fk-drivers)
(testing (str "Test that we're able to use a GTAP for an FK related table. For this test, the user has segmented "
"permissions on checkins and venues, so we need to apply a GTAP to the original table (checkins) in "
"addition to the related table (venues). This test uses a GTAP question for both tables")
@@ -451,7 +443,7 @@
(set (run-checkins-count-broken-out-by-price-query))))))))
(deftest e2e-fks-test-3
- (mt/test-drivers (row-level-restrictions-fk-drivers)
+ (mt/test-drivers (sandboxing-fk-drivers)
(testing "Test that the FK related table can be a \"default\" GTAP, i.e. a GTAP where the `card_id` is nil"
(met/with-gtaps! {:gtaps {:checkins (checkins-user-mbql-gtap-def)
:venues (dissoc (venues-price-mbql-gtap-def) :query)}
@@ -460,7 +452,7 @@
(set (run-checkins-count-broken-out-by-price-query))))))))
(deftest e2e-fks-test-4
- (mt/test-drivers (row-level-restrictions-fk-drivers)
+ (mt/test-drivers (sandboxing-fk-drivers)
(testing (str "Test that we have multiple FK related, segmented tables. This test has checkins with a GTAP "
"question with venues and users having the default GTAP and segmented permissions")
(met/with-gtaps! {:gtaps {:checkins (checkins-user-mbql-gtap-def)
@@ -498,9 +490,9 @@
(mt/user-http-request :rasta :post "dataset" (mt/mbql-query venues {:aggregation [[:count]]})))))))))
(deftest breakouts-test
- (mt/test-drivers (row-level-restrictions-fk-sql-drivers)
+ (mt/test-drivers (sandboxing-fk-sql-drivers)
(testing "Make sure that if a GTAP is in effect we can still do stuff like breakouts (#229)"
- (met/with-gtaps! {:gtaps {:venues (venues-category-native-gtap-def)}
+ (met/with-gtaps! {:gtaps {:venues (venues-category-native-sandbox-def)}
:attributes {"cat" 50}}
(is (= [[1 6] [2 4]]
(mt/format-rows-by
@@ -513,99 +505,125 @@
(deftest sql-with-join-test
(mt/test-drivers (into #{}
(filter #(driver.u/supports? % :parameterized-sql nil))
- (row-level-restrictions-fk-sql-drivers))
+ (sandboxing-fk-sql-drivers))
(testing (str "If we use a parameterized SQL GTAP that joins a Table the user doesn't have access to, does it "
"still work? (EE #230) If we pass the query in directly without anything that would require nesting "
"it, it should work")
- (is (= [[2 1]
- [72 1]]
- (mt/format-rows-by
- [int int identity int]
- (mt/rows
- (met/with-gtaps! {:gtaps {:checkins (parameterized-sql-with-join-gtap-def)}
- :attributes {"user" 1}}
- (mt/run-mbql-query checkins
- {:order-by [[:asc $id]]
- :limit 2})))))))))
+ (met/with-gtaps! {:gtaps {:checkins (parameterized-sql-with-join-sandbox-def)}
+ :attributes {"user" 1}}
+ (let [query (mt/mbql-query checkins
+ {:order-by [[:asc $id]]
+ :limit 2})]
+ ;; should only return CHECKINS.ID and CHECKINS.DATE since that is all the sandbox returns
+ (mt/with-native-query-testing-context query
+ (is (= [[2 1]
+ [72 1]]
+ (mt/formatted-rows
+ [int int]
+ (qp/process-query query))))))))))
(deftest sql-with-join-test-2
(mt/test-drivers (into #{}
(filter #(driver.u/supports? % :parameterized-sql nil))
- (row-level-restrictions-fk-sql-drivers))
+ (sandboxing-fk-sql-drivers))
(testing (str "If we use a parameterized SQL GTAP that joins a Table the user doesn't have access to, does it "
"still work? (EE #230) If we pass the query in directly without anything that would require nesting "
"it, it should work")
(is (= [[2 1]
[72 1]]
(mt/format-rows-by
- [int int identity int]
+ [int int]
(mt/rows
- (met/with-gtaps! {:gtaps {:checkins (parameterized-sql-with-join-gtap-def)}
+ (met/with-gtaps! {:gtaps {:checkins (parameterized-sql-with-join-sandbox-def)}
:attributes {"user" 1}}
(mt/run-mbql-query checkins
{:order-by [[:asc $id]]
:limit 2})))))))))
+(defn- do-correct-metadata-test [f]
+ (let [cols (fn []
+ (mt/cols
+ (mt/run-mbql-query venues
+ {:order-by [[:asc $id]]
+ :limit 2})))
+ original-cols (cols)
+ ;; `with-gtaps!` copies the test DB so this function will update the IDs in `original-cols` so they'll match
+ ;; up with the current copy
+ expected-cols (fn []
+ (for [col original-cols
+ :let [id (mt/id :venues (keyword (u/lower-case-en (:name col))))]]
+ (-> col
+ (assoc :id id
+ :table_id (mt/id :venues))
+ ;; should return a field for the original field
+ (update :field_ref (fn [[tag _id opts]]
+ [tag id (or opts {})]))
+ (dissoc :fk_target_field_id
+ :lib/original-display-name
+ :metabase.lib.query/transformation-added-base-type))))]
+ (f {:cols cols, :expected-cols expected-cols})))
+
(deftest correct-metadata-test
(testing (str "We should return the same metadata as the original Table when running a query against a sandboxed "
"Table (EE #390)\n")
- (let [cols (fn []
- (mt/cols
- (mt/run-mbql-query venues
- {:order-by [[:asc $id]]
- :limit 2})))
- original-cols (cols)
- ;; `with-gtaps!` copies the test DB so this function will update the IDs in `original-cols` so they'll match
- ;; up with the current copy
- expected-cols (fn []
- (for [col original-cols
- :let [id (mt/id :venues (keyword (u/lower-case-en (:name col))))]]
- (-> col
- (assoc :id id
- :table_id (mt/id :venues)
- :field_ref [:field id nil])
- (dissoc :fk_target_field_id))))]
- (testing "A query with a simple attributes-based sandbox should have the same metadata"
- (met/with-gtaps! {:gtaps {:venues (dissoc (venues-category-mbql-gtap-def) :query)}
- :attributes {"cat" 50}}
- (is (=? (expected-cols)
- (cols)))))
-
- (testing "A query with an equivalent MBQL query sandbox should have the same metadata"
- (met/with-gtaps! {:gtaps {:venues (venues-category-mbql-gtap-def)}
- :attributes {"cat" 50}}
- (is (=? (expected-cols)
- (cols)))))
-
- (testing "A query with an equivalent native query sandbox should have the same metadata"
- (met/with-gtaps! {:gtaps {:venues {:query (mt/native-query
- {:query
- (str "SELECT ID, NAME, CATEGORY_ID, LATITUDE, LONGITUDE, PRICE "
- "FROM VENUES "
- "WHERE CATEGORY_ID = {{cat}}")
-
- :template_tags
- {:cat {:name "cat" :display_name "cat" :type "number" :required true}}})
- :remappings {:cat ["variable" ["template-tag" "cat"]]}}}
- :attributes {"cat" 50}}
- (is (=? (expected-cols)
- (cols)))))
-
- (testing (str "If columns are added/removed/reordered we should still merge in metadata for the columns we're "
- "able to match from the original Table")
- (met/with-gtaps! {:gtaps {:venues {:query (mt/native-query
- {:query
- (str "SELECT NAME, ID, LONGITUDE, PRICE, 1 AS ONE "
- "FROM VENUES "
- "WHERE CATEGORY_ID = {{cat}}")
-
- :template_tags
- {:cat {:name "cat" :display_name "cat" :type "number" :required true}}})
- :remappings {:cat ["variable" ["template-tag" "cat"]]}}}
- :attributes {"cat" 50}}
- (let [[id-col name-col _ _ longitude-col price-col] (expected-cols)]
- (is (=? [name-col id-col longitude-col price-col]
- (cols)))))))))
+ (do-correct-metadata-test
+ (fn [{:keys [cols expected-cols]}]
+ (testing "A query with a simple attributes-based sandbox should have the same metadata"
+ (met/with-gtaps! {:gtaps {:venues (dissoc (venues-category-mbql-gtap-def) :query)}
+ :attributes {"cat" 50}}
+ (is (=? (expected-cols)
+ (cols)))))))))
+
+(deftest correct-metadata-test-2
+ (testing (str "We should return the same metadata as the original Table when running a query against a sandboxed "
+ "Table (EE #390)\n")
+ (do-correct-metadata-test
+ (fn [{:keys [cols expected-cols]}]
+ (testing "A query with an equivalent MBQL query sandbox should have the same metadata"
+ (met/with-gtaps! {:gtaps {:venues (venues-category-mbql-gtap-def)}
+ :attributes {"cat" 50}}
+ (is (=? (expected-cols)
+ (cols)))))))))
+
+(deftest correct-metadata-test-3
+ (testing (str "We should return the same metadata as the original Table when running a query against a sandboxed "
+ "Table (EE #390)\n")
+ (do-correct-metadata-test
+ (fn [{:keys [cols expected-cols]}]
+ (testing "A query with an equivalent native query sandbox should have the same metadata"
+ (met/with-gtaps! {:gtaps {:venues {:query (mt/native-query
+ {:query
+ (str "SELECT ID, NAME, CATEGORY_ID, LATITUDE, LONGITUDE, PRICE "
+ "FROM VENUES "
+ "WHERE CATEGORY_ID = {{cat}}")
+
+ :template_tags
+ {:cat {:name "cat" :display_name "cat" :type "number" :required true}}})
+ :remappings {:cat ["variable" ["template-tag" "cat"]]}}}
+ :attributes {"cat" 50}}
+ (is (=? (expected-cols)
+ (cols)))))))))
+
+(deftest correct-metadata-test-4
+ (testing (str "We should return the same metadata as the original Table when running a query against a sandboxed "
+ "Table (EE #390)\n")
+ (do-correct-metadata-test
+ (fn [{:keys [cols expected-cols]}]
+ (testing (str "If columns are removed/reordered we should still merge in metadata for the columns we're "
+ "able to match from the original Table")
+ (met/with-gtaps! {:gtaps {:venues {:query (mt/native-query
+ {:query
+ (str "SELECT NAME, ID, LONGITUDE, PRICE "
+ "FROM VENUES "
+ "WHERE CATEGORY_ID = {{cat}}")
+
+ :template_tags
+ {:cat {:name "cat" :display_name "cat" :type "number" :required true}}})
+ :remappings {:cat ["variable" ["template-tag" "cat"]]}}}
+ :attributes {"cat" 50}}
+ (let [[id-col name-col _ _ longitude-col price-col] (expected-cols)]
+ (is (=? [id-col name-col longitude-col price-col]
+ (cols))))))))))
(deftest sql-with-joins-test
(testing "Should be able to use a Saved Question with no source Metadata as a GTAP (EE #525)"
@@ -623,17 +641,19 @@
:remappings {"user_id" [:variable [:template-tag "sandbox"]]}}
:checkins {:remappings {"user_id" [:dimension $checkins.user_id]}}}
:attributes {"user_id" 1}})
- (is (= [[2 "2014-09-18T00:00:00Z" 1 31 31 "Bludso's BBQ" 5 33.8894 -118.207 2]
- [72 "2015-04-18T00:00:00Z" 1 1 1 "Red Medicine" 4 10.0646 -165.374 3]
- [80 "2013-12-27T00:00:00Z" 1 99 99 "Golden Road Brewing" 10 34.1505 -118.274 2]]
- (mt/rows
- (mt/run-mbql-query checkins
- {:joins [{:fields :all
- :source-table $$venues
- :condition [:= $venue_id &Venue.venues.id]
- :alias "Venue"}]
- :order-by [[:asc $id]]
- :limit 3})))))))
+ (let [query (mt/mbql-query checkins
+ {:joins [{:fields :all
+ :source-table $$venues
+ :condition [:= $venue_id &Venue.venues.id]
+ :alias "Venue"}]
+ :order-by [[:asc $id]]
+ :limit 3})]
+ (mt/with-native-query-testing-context query
+ ;; (4 columns from checkins) (6 columns from venues)
+ (is (= [[2 "2014-09-18T00:00:00Z" 1 31 31 "Bludso's BBQ" 5 33.8894 -118.207 2]
+ [72 "2015-04-18T00:00:00Z" 1 1 1 "Red Medicine" 4 10.0646 -165.374 3]
+ [80 "2013-12-27T00:00:00Z" 1 99 99 "Golden Road Brewing" 10 34.1505 -118.274 2]]
+ (mt/rows (qp/process-query query)))))))))
(deftest run-sql-queries-to-infer-columns-test
(testing "Run SQL queries to infer the columns when used as GTAPS (#13716)\n"
@@ -650,7 +670,7 @@
:remappings {"venue_id" [:variable [:template-tag "sandbox"]]}}
:checkins {}}
:attributes {"venue_id" 1}})
- (let [venues-gtap-card-id (t2/select-one-fn :card_id :model/GroupTableAccessPolicy
+ (let [venues-gtap-card-id (t2/select-one-fn :card_id :model/Sandbox
:group_id (:id &group)
:table_id (mt/id :venues))]
(is (integer? venues-gtap-card-id))
@@ -661,20 +681,18 @@
(is (= [[1 "Red Medicine" 1 "Red Medicine" 4 10.0646 -165.374 3]]
(mt/rows
(mt/run-mbql-query venues
- {:fields [$id $name] ; joined fields get appended automatically because we specify :all :below
- :joins [{:fields :all
- :source-table $$venues
- :condition [:= $id &Venue.id]
- :alias "Venue"}]
+ {:fields [$id $name] ; joined fields get appended automatically because we specify :all :below
+ :joins [{:fields :all
+ :source-table $$venues
+ :condition [:= $id &Venue.id]
+ :alias "Venue"}]
:order-by [[:asc $id]]
- :limit 3})))))
+ :limit 3})))))
(testing "After running the query the first time, result_metadata should have been saved for the GTAP Card"
- (is (=? [{:name "ID"
- :base_type :type/BigInteger
- :display_name "ID"}
- {:name "NAME"
- :base_type :type/Text
- :display_name "Name"}
+ (is (=? [{:name "ID"
+ :base_type :type/BigInteger}
+ {:name "NAME"
+ :base_type :type/Text}
{:name "CATEGORY_ID"}
{:name "LATITUDE"}
{:name "LONGITUDE"}
@@ -692,7 +710,7 @@
:remappings {"venue_id" [:variable [:template-tag "sandbox"]]}}
:checkins {}}
:attributes {"venue_id" 1}})
- (let [venues-gtap-card-id (t2/select-one-fn :card_id :model/GroupTableAccessPolicy
+ (let [venues-gtap-card-id (t2/select-one-fn :card_id :model/Sandbox
:group_id (:id &group)
:table_id (mt/id :venues))]
(is (integer? venues-gtap-card-id))
@@ -966,18 +984,19 @@
(testing "as sandboxed user"
(test-drill-thru-query)))))]
(do-tests)
- (qp.store/with-metadata-provider (lib.tu/remap-metadata-provider
- (mt/application-database-metadata-provider (mt/id))
- (mt/id :orders :product_id)
- (mt/id :products :title))
- (do-tests)))))))
+ (testing "with remapping"
+ (qp.store/with-metadata-provider (lib.tu/remap-metadata-provider
+ (mt/application-database-metadata-provider (mt/id))
+ (mt/id :orders :product_id)
+ (mt/id :products :title))
+ (do-tests))))))))
(defn- set-query-metadata-for-gtap-card!
"Find the GTAP Card associated with Group and table-name and add `:result_metadata` to it. Because we (probably) need
a parameter in order to run the query to get metadata, pass `param-name` and `param-value` template tag parameters
when running the query."
[group table-name param-name param-value]
- (let [card-id (t2/select-one-fn :card_id :model/GroupTableAccessPolicy
+ (let [card-id (t2/select-one-fn :card_id :model/Sandbox
:group_id (u/the-id group), :table_id (mt/id table-name))
card (t2/select-one :model/Card :id (u/the-id card-id))
results (mt/with-test-user :crowberto
@@ -993,14 +1012,16 @@
(deftest native-fk-remapping-test
(testing "FK remapping should still work for questions with native sandboxes (EE #520)"
(mt/dataset test-data
- (let [mbql-sandbox-results (met/with-gtaps! {:gtaps (mt/$ids
+ (let [remap-metadata-provider (fn []
+ (lib.tu/remap-metadata-provider
+ (mt/application-database-metadata-provider (mt/id))
+ (mt/id :orders :product_id)
+ (mt/id :products :title)))
+ mbql-sandbox-results (met/with-gtaps! {:gtaps (mt/$ids
{:orders {:remappings {"user_id" [:dimension $orders.user_id]}}
:products {:remappings {"user_cat" [:dimension $products.category]}}})
:attributes {"user_id" 1, "user_cat" "Widget"}}
- (qp.store/with-metadata-provider (lib.tu/remap-metadata-provider
- (mt/application-database-metadata-provider (mt/id))
- (mt/id :orders :product_id)
- (mt/id :products :title))
+ (qp.store/with-metadata-provider (remap-metadata-provider)
(mt/run-mbql-query orders)))]
(testing "Sanity check: merged results metadata should not get normalized incorrectly"
(is (=? {:type {:type/Number {}}}
@@ -1031,10 +1052,7 @@
(set-query-metadata-for-gtap-card! &group :orders "uid" 1))
(when products-gtap-card-has-metadata?
(set-query-metadata-for-gtap-card! &group :products "cat" "Widget"))
- (qp.store/with-metadata-provider (lib.tu/remap-metadata-provider
- (mt/application-database-metadata-provider (mt/id))
- (mt/id :orders :product_id)
- (mt/id :products :title))
+ (qp.store/with-metadata-provider (remap-metadata-provider)
(testing "Sandboxed results should be the same as they would be if the sandbox was MBQL"
(letfn [(format-col [col]
(-> (m/filter-keys simple-keyword? col)
@@ -1052,7 +1070,7 @@
(mt/rows (mt/run-mbql-query orders {:limit 1})))))))))))))
(deftest pivot-query-test
- (mt/test-drivers (row-level-restrictions-fk-drivers)
+ (mt/test-drivers (sandboxing-fk-drivers)
(testing "Pivot table queries should work with sandboxed users (#14969)"
(mt/dataset test-data
(met/with-gtaps! {:gtaps (mt/$ids
@@ -1092,8 +1110,8 @@
(testing "Make sure Sandboxing works in combination with caching (#18579)"
(mt/with-model-cleanup [[:model/QueryCache :updated_at]]
(met/with-gtaps! {:gtaps {:venues {:query (mt/mbql-query venues {:order-by [[:asc $id]], :limit 5})}}}
- (let [card-id (t2/select-one-fn :card_id :model/GroupTableAccessPolicy :group_id (u/the-id &group))
- _ (is (integer? card-id))
+ (let [card-id (t2/select-one-fn :card_id :model/Sandbox :group_id (u/the-id &group))
+ _ (is (pos-int? card-id))
query (t2/select-one-fn :dataset_query :model/Card :id card-id)
run-query (fn []
(let [results (qp/process-query (assoc query :cache-strategy {:type :ttl
@@ -1249,7 +1267,7 @@
(deftest native-sandbox-table-level-block-perms-test
(testing "A sandbox powered by a native query source card can be used even when other tables have block perms (#49969)"
- (met/with-gtaps! {:gtaps {:venues (venues-category-native-gtap-def)}
+ (met/with-gtaps! {:gtaps {:venues (venues-category-native-sandbox-def)}
:attributes {"cat" 50}}
(data-perms/set-table-permission! &group (mt/id :people) :perms/view-data :blocked)
(is (= 10 (count (mt/rows (qp/process-query (mt/mbql-query venues)))))))))
@@ -1257,10 +1275,10 @@
(deftest native-sandbox-no-query-metadata-streaming-test
(testing "A sandbox powered by a native query source card can be used via the streaming API even if the card has no
stored results_metadata (#49985)"
- (met/with-gtaps! {:gtaps {:venues (venues-category-native-gtap-def)}
+ (met/with-gtaps! {:gtaps {:venues (venues-category-native-sandbox-def)}
:attributes {"cat" 50}}
(let [sandbox-card-id (t2/select-one-fn :card_id
- :model/GroupTableAccessPolicy
+ :model/Sandbox
:group_id (:id &group)
:table_id (mt/id :venues))]
(is (nil? (t2/select-one-fn :result_metadata :model/Card sandbox-card-id)))
@@ -1320,7 +1338,7 @@
(deftest jwt-login-attributes-merge-test
(testing "Verify attribute merging behavior between jwt_attributes and login_attributes"
- (mt/test-drivers (row-level-restrictions-fk-drivers)
+ (mt/test-drivers (sandboxing-fk-drivers)
(met/with-gtaps! {:gtaps {:checkins (checkins-user-mbql-gtap-def)
:venues (venues-price-mbql-gtap-def)}}
(testing "attributes from different sources are properly merged"
@@ -1340,7 +1358,7 @@
(deftest jwt-attributes-native-query-test
(mt/test-drivers (e2e-test-drivers)
(testing "Native SQL GTAP queries work with jwt_attributes"
- (met/with-gtaps! {:gtaps {:venues (venues-category-native-gtap-def)}}
+ (met/with-gtaps! {:gtaps {:venues (venues-category-native-sandbox-def)}}
(testing "Basic test with jwt_attributes"
(tu/with-temp-vals-in-db :model/User (mt/user->id :rasta) {:jwt_attributes {"cat" 50}
:login_attributes {}}
@@ -1413,7 +1431,7 @@
(deftest jwt-attributes-different-param-names-test
(mt/test-drivers (e2e-test-drivers)
(testing "GTAP remapping with different parameter names works with jwt_attributes"
- (met/with-gtaps! {:gtaps {:venues {:query (:query (venues-category-native-gtap-def))
+ (met/with-gtaps! {:gtaps {:venues {:query (:query (venues-category-native-sandbox-def))
:remappings {:something.different ["variable" ["template-tag" "cat"]]}}}}
(tu/with-temp-vals-in-db :model/User (mt/user->id :rasta) {:jwt_attributes {"something.different" 50}
:login_attributes {}}
@@ -1433,7 +1451,7 @@
(run-venues-count-query)))))))))
(deftest jwt-attributes-fk-relationships-test
- (mt/test-drivers (row-level-restrictions-fk-drivers)
+ (mt/test-drivers (sandboxing-fk-drivers)
(testing "FK relationships and joins work correctly with jwt_attributes"
(met/with-gtaps! {:gtaps {:checkins (checkins-user-mbql-gtap-def)
:venues (dissoc (venues-price-mbql-gtap-def) :query)
@@ -1466,9 +1484,9 @@
(deftest jwt-attributes-parameterized-sql-test
(mt/test-drivers (into #{}
(filter #(driver.u/supports? % :parameterized-sql nil))
- (row-level-restrictions-fk-sql-drivers))
+ (sandboxing-fk-sql-drivers))
(testing "Parameterized SQL GTAPs work with jwt_attributes"
- (met/with-gtaps! {:gtaps {:checkins (parameterized-sql-with-join-gtap-def)}}
+ (met/with-gtaps! {:gtaps {:checkins (parameterized-sql-with-join-sandbox-def)}}
(tu/with-temp-vals-in-db :model/User (mt/user->id :rasta) {:jwt_attributes {"user" 1}
:login_attributes {}}
(mt/with-test-user :rasta
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/test_util.clj b/enterprise/backend/test/metabase_enterprise/sandbox/test_util.clj
index 3f4179e97b1..6f84468642e 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/test_util.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/test_util.clj
@@ -39,10 +39,10 @@
(f nil)))]
(do-with-card
(fn [card-id]
- (mt/with-temp [:model/GroupTableAccessPolicy _gtap {:group_id (u/the-id group)
- :table_id (data/id table-kw)
- :card_id card-id
- :attribute_remappings remappings}]
+ (mt/with-temp [:model/Sandbox _gtap {:group_id (u/the-id group)
+ :table_id (data/id table-kw)
+ :card_id card-id
+ :attribute_remappings remappings}]
(data-perms/set-database-permission! group (data/id) :perms/view-data :unrestricted)
(data-perms/set-table-permission! group (data/id table-kw) :perms/create-queries :query-builder)
(do-with-gtap-defs! group more f)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/stale/impl_test.clj b/enterprise/backend/test/metabase_enterprise/stale/impl_test.clj
index 04474b53002..6cfff5c4c84 100644
--- a/enterprise/backend/test/metabase_enterprise/stale/impl_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/stale/impl_test.clj
@@ -374,7 +374,7 @@
:offset 0
:sort-column :name
:sort-direction :asc})))
- (t2/delete! :model/GroupTableAccessPolicy :card_id gtap-card-id)
+ (t2/delete! :model/Sandbox :card_id gtap-card-id)
(is (= {:rows [{:model :model/Card :id gtap-card-id}]
:total 1}
(stale/find-candidates
diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.clj
index 544b79f8f48..f0851bfeffa 100644
--- a/src/metabase/cmd/copy.clj
+++ b/src/metabase/cmd/copy.clj
@@ -113,7 +113,7 @@
:model/NotificationRecipient
:model/NotificationCard]
(when config/ee-available?
- [:model/GroupTableAccessPolicy
+ [:model/Sandbox
:model/ConnectionImpersonation
:model/Metabot
:model/MetabotEntity
@@ -364,7 +364,7 @@
(str (name (t2/table-name model)) "_id_seq"))
;;; we changed the table name to `sandboxes` but never updated the underlying ID sequences or constraint names.
-(defmethod postgres-id-sequence-name :model/GroupTableAccessPolicy
+(defmethod postgres-id-sequence-name :model/Sandbox
[_model]
"group_table_access_policy_id_seq")
diff --git a/src/metabase/driver_api/core.clj b/src/metabase/driver_api/core.clj
index 00123c3901e..e44bc5593a6 100644
--- a/src/metabase/driver_api/core.clj
+++ b/src/metabase/driver_api/core.clj
@@ -14,6 +14,7 @@
[metabase.config.core :as config]
[metabase.connection-pool :as connection-pool]
[metabase.database-routing.core :as database-routing]
+ [metabase.driver-api.impl]
[metabase.events.core :as events]
[metabase.legacy-mbql.schema :as mbql.s]
[metabase.legacy-mbql.util :as mbql.u]
@@ -139,6 +140,7 @@
mdb/make-subname
mdb/query-canceled-exception?
mdb/spec
+ metabase.driver-api.impl/cached
mi/instance-of?
nest-query/nest-expressions
premium-features/is-hosted?
@@ -152,7 +154,6 @@
qp.relative-datetime/maybe-cacheable-relative-datetime-honeysql
qp.setup/with-qp-setup
qp.store/->legacy-metadata
- qp.store/cached
qp.store/initialized?
qp.store/metadata-provider
qp.store/with-metadata-provider
diff --git a/src/metabase/driver_api/impl.clj b/src/metabase/driver_api/impl.clj
new file mode 100644
index 00000000000..98795d7df1c
--- /dev/null
+++ b/src/metabase/driver_api/impl.clj
@@ -0,0 +1,33 @@
+(ns metabase.driver-api.impl
+ {:clj-kondo/config '{:linters
+ ;; this is actually ok here since this is a drivers namespace
+ {:discouraged-namespace {metabase.query-processor.store {:level :off}}}}}
+ (:require
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.query-processor.store :as qp.store]
+ [metabase.util :as u]))
+
+;;; replacement for the old [[metabase.query-processor.store/cached]] macro, deprecated in 57
+;;;
+;;; TODO (Cam 9/10/25) -- this is just kicking the can down the road a bit, since eventually we'll probably want to
+;;; remove this too in favor of using [[metabase.lib.metadata/general-cached-value]] directly -- since the plan is
+;;; eventually to do away with the entire [[metabase.query-processor.store]] namespace (you can pass in the MBQL 5
+;;; query to `general-cached-value` instead)
+(defmacro cached
+ "Cache the value of `body` for key(s) for the duration of this QP execution. (Body is only evaluated the once per QP
+ run; subsequent calls return the cached result.)
+
+ Note that each use of `cached` generates its own unique first key for cache keyseq; thus while it is not possible to
+ share values between multiple `cached` forms, you do not need to worry about conflicts with other places using this
+ macro.
+
+ ;; cache lookups of Card.dataset_query
+ (driver-api/cached card-id
+ (t2/select-one-fn :dataset_query Card :id card-id))"
+ {:style/indent 1}
+ [k-or-ks & body]
+ (let [ks (into [(list 'quote (gensym (str (name (ns-name *ns*)) "/misc-cache-")))] (u/one-or-many k-or-ks))]
+ `(lib.metadata/general-cached-value
+ (qp.store/metadata-provider)
+ ~ks
+ (fn [] ~@body))))
diff --git a/src/metabase/legacy_mbql/normalize.cljc b/src/metabase/legacy_mbql/normalize.cljc
index 5676eebd9af..ce97a634bcb 100644
--- a/src/metabase/legacy_mbql/normalize.cljc
+++ b/src/metabase/legacy_mbql/normalize.cljc
@@ -469,7 +469,7 @@
;;
;; HACK TODO (Cam 7/17/25) -- seems icky for the legacy MBQL schema to have to know about namespaced keys like
;; this. I guess this can go away once we stop converting back and forth between MBQL 4 and 5 inside the QP
- :metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions/original-metadata
+ :metabase-enterprise.sandbox.query-processor.middleware.sandboxing/original-metadata
identity})
(defn normalize-tokens
diff --git a/src/metabase/legacy_mbql/predicates.cljc b/src/metabase/legacy_mbql/predicates.cljc
index e18d4836676..d14d42bb1fb 100644
--- a/src/metabase/legacy_mbql/predicates.cljc
+++ b/src/metabase/legacy_mbql/predicates.cljc
@@ -19,11 +19,6 @@
[x]
((mr/validator ::mbql.s/Emptyable) x))
-(defn DatetimeExpression?
- "Is this a valid DatetimeExpression clause?"
- [x]
- ((mr/validator ::mbql.s/DatetimeExpression) x))
-
(defn FieldOrExpressionDef?
"Is this a something that is valid as a top-level expression definition?"
[x]
diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljc
index ccc14c840d3..46696f5efa5 100644
--- a/src/metabase/legacy_mbql/schema.cljc
+++ b/src/metabase/legacy_mbql/schema.cljc
@@ -6,7 +6,6 @@
[clojure.set :as set]
[clojure.string :as str]
[malli.core :as mc]
- [malli.error :as me]
[metabase.legacy-mbql.schema.helpers :as helpers :refer [is-clause?]]
[metabase.legacy-mbql.schema.macros :refer [defclause one-of]]
[metabase.lib.schema.actions :as lib.schema.actions]
@@ -25,7 +24,6 @@
[metabase.lib.schema.settings :as lib.schema.settings]
[metabase.lib.schema.template-tag :as lib.schema.template-tag]
[metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]
- [metabase.util.i18n :as i18n]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]))
@@ -393,17 +391,6 @@
"Schema for a `:field` clause."
(with-meta [:ref ::field] {:clause-name :field}))
-(def ^{:added "0.39.0"} field:id
- "Schema for a `:field` clause, with the added constraint that it must use an integer Field ID."
- (with-meta
- [:and
- field
- [:fn
- {:error/message "Must be a :field with an integer Field ID."}
- (fn [[_ id-or-name]]
- (integer? id-or-name))]]
- {:clause-name :field}))
-
(mr/def ::field-or-expression-ref
[:schema
{:doc/title "`:field` or `:expression` ref"}
@@ -1810,19 +1797,3 @@
(lib.schema.common/disallowed-keys
{:source-table "An outer query must not include inner-query keys like :source-table; this might cause us to confuse it with an inner query"
:source-query "An outer query must not include inner-query keys like :source-query; this might cause us to confuse it with an inner query"})])
-
-(def ^{:arglists '([query])} valid-query?
- "Is this a valid outer query? (Pre-compling a validator is more efficient.)"
- (mr/validator Query))
-
-(defn validate-query
- "Validator for an outer query; throw an Exception explaining why the query is invalid if it is. Returns query if
- valid."
- [query]
- (if (valid-query? query)
- query
- (let [error (mr/explain Query query)
- humanized (me/humanize error)]
- (throw (ex-info (i18n/tru "Invalid query: {0}" (pr-str humanized))
- {:error humanized
- :original error})))))
diff --git a/src/metabase/legacy_mbql/util.cljc b/src/metabase/legacy_mbql/util.cljc
index 0d453698a46..59690eb750f 100644
--- a/src/metabase/legacy_mbql/util.cljc
+++ b/src/metabase/legacy_mbql/util.cljc
@@ -10,6 +10,7 @@
[metabase.legacy-mbql.schema :as mbql.s]
[metabase.legacy-mbql.schema.helpers :as schema.helpers]
[metabase.lib.schema.common :as lib.schema.common]
+ [metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.util.match :as lib.util.match]
[metabase.util :as u]
[metabase.util.i18n :as i18n]
@@ -43,10 +44,6 @@
(str/replace \_ \-)
keyword))))
-;;; +----------------------------------------------------------------------------------------------------------------+
-;;; | Functions for manipulating queries |
-;;; +----------------------------------------------------------------------------------------------------------------+
-
(defn- combine-compound-filters-of-type
{:deprecated "0.57.0"}
[compound-type subclauses]
@@ -135,29 +132,6 @@
n
(recur source-query (inc n)))))
-(defn- map-stages*
- "Helper for [[map-stages]]; call that instead."
- [f {:keys [source-query] :as inner-query}]
- (if source-query
- ;; Recursive case: Call `map-stages*` on the `:source-query`, then `f` on this stage. Increment the stage count.
- (let [[new-source-query stage-count] (map-stages* f source-query)]
- [(-> (assoc inner-query :source-query new-source-query)
- (f stage-count))
- (inc stage-count)])
- ;; Base case: No `:source-query`, so just call `f` and return a `stage-count` of 1.
- [(f inner-query 0) 1]))
-
-(defn map-stages
- "Given a function `(f inner-query stage-number)`, recursively calls it on the stages of this (legacy MBQL)
- `inner-query`.
-
- The calls run postorder, that is the earliest/innermost stage first.
-
- Returns the updated `inner-query`."
- [f inner-query]
- (let [[updated-inner-query _stage-count] (map-stages* f inner-query)]
- updated-inner-query))
-
(defn desugar-inside
"Rewrite `:inside` filter clauses as a pair of `:between` clauses."
{:deprecated "0.57.0"}
@@ -543,7 +517,7 @@
#_{:clj-kondo/ignore [:deprecated-var]}
(-> filter-clause desugar-filter-clause negate* simplify-compound-filter))
-(mu/defn query->source-table-id :- [:maybe pos-int?]
+(mu/defn query->source-table-id :- [:maybe ::lib.schema.id/table]
"Return the source Table ID associated with `query`, if applicable; handles nested queries as well. If `query` is
`nil`, returns `nil`.
@@ -576,11 +550,6 @@
:else
source-table-id))
-(mu/defn join->source-table-id :- [:maybe pos-int?]
- "Like `query->source-table-id`, but for a join."
- [join]
- (query->source-table-id {:type :query, :query join}))
-
(mu/defn add-order-by-clause :- mbql.s/MBQLQuery
"Add a new `:order-by` clause to an MBQL `inner-query`. If the new order-by clause references a Field that is
already being used in another order-by clause, this function does nothing."
@@ -656,8 +625,6 @@
;; keep recursing deeper into the query until we get to the same level the aggregation reference was defined at
(recur {:query (get-in query [:query :source-query])} index (dec nesting-level)))))
-;;; --------------------------------- Unique names & transforming ags to have names ----------------------------------
-
(defn unique-name-generator
"Return a function that can be used to uniquify string names. Function maintains an internal counter that will suffix
any names passed to it as needed so all results will be unique.
diff --git a/src/metabase/lib/card.cljc b/src/metabase/lib/card.cljc
index 36d2cfd54df..778b392e060 100644
--- a/src/metabase/lib/card.cljc
+++ b/src/metabase/lib/card.cljc
@@ -273,3 +273,22 @@
"Is the query's source-card a model?"
[query :- ::lib.schema/query]
(= (source-card-type query) :model))
+
+(mu/defn card->underlying-query :- ::lib.schema/query
+ "Given a `card` return the underlying query that would be run if executing the Card directly. This is different from
+
+ (lib/query mp (lib.metadata/card mp card-id))
+
+ in that this creates a query based on the Card's `:dataset-query` (attaching `:result-metadata` to the last stage)
+ rather than a query that has an empty stage with a `:source-card`.
+
+ This is useful in cases where we want to splice in a Card's query directly (e.g., sanboxing) or for parameter
+ calculation purposes."
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable
+ card :- ::lib.schema.metadata/card]
+ (let [mp (lib.metadata/->metadata-provider metadata-providerable)
+ {card-query :dataset-query, result-metadata :result-metadata} card]
+ (cond-> (lib.query/query mp card-query)
+ result-metadata (lib.util/update-query-stage -1 (fn [stage]
+ (->> (assoc stage :lib/stage-metadata (lib.util/->stage-metadata result-metadata))
+ (lib.normalize/normalize ::lib.schema/stage)))))))
diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljc
index 24b9c23afcb..63052bbca2e 100644
--- a/src/metabase/lib/core.cljc
+++ b/src/metabase/lib/core.cljc
@@ -7,7 +7,7 @@
[metabase.lib.aggregation :as lib.aggregation]
[metabase.lib.binning :as lib.binning]
[metabase.lib.breakout :as lib.breakout]
- [metabase.lib.card :as lib.card]
+ [metabase.lib.card]
[metabase.lib.column-group :as lib.column-group]
[metabase.lib.common :as lib.common]
[metabase.lib.convert :as lib.convert]
@@ -31,6 +31,7 @@
[metabase.lib.join :as lib.join]
[metabase.lib.join.util]
[metabase.lib.limit :as lib.limit]
+ [metabase.lib.metadata]
[metabase.lib.metadata.calculation :as lib.metadata.calculation]
[metabase.lib.metadata.composed-provider :as lib.metadata.composed-provider]
[metabase.lib.metric :as lib.metric]
@@ -51,12 +52,13 @@
[metabase.lib.template-tags :as lib.template-tags]
[metabase.lib.temporal-bucket :as lib.temporal-bucket]
[metabase.lib.util :as lib.util]
+ [metabase.lib.walk.util]
[metabase.util.namespaces :as shared.ns]))
(comment lib.aggregation/keep-me
lib.binning/keep-me
lib.breakout/keep-me
- lib.card/keep-me
+ metabase.lib.card
lib.column-group/keep-me
lib.common/keep-me
lib.convert/keep-me
@@ -80,6 +82,7 @@
lib.join/keep-me
metabase.lib.join.util/keep-me
lib.limit/keep-me
+ metabase.lib.metadata/keep-me
lib.metadata.calculation/keep-me
lib.metadata.composed-provider/keep-me
lib.metric/keep-me
@@ -98,7 +101,8 @@
lib.table/keep-me
lib.template-tags/keep-me
lib.temporal-bucket/keep-me
- lib.util/keep-me)
+ lib.util/keep-me
+ metabase.lib.walk.util/keep-me)
(shared.ns/import-fns
[lib.aggregation
@@ -138,6 +142,8 @@
breakouts
breakouts-metadata
remove-all-breakouts]
+ [metabase.lib.card
+ card->underlying-query]
[lib.column-group
columns-group-columns
group-columns]
@@ -326,6 +332,8 @@
current-limit
limit
max-rows-limit]
+ [metabase.lib.metadata
+ general-cached-value]
[lib.metadata.calculation
column-name
describe-query
@@ -428,4 +436,8 @@
previous-stage-number
query-stage
source-table-id
- update-query-stage])
+ update-query-stage]
+ [metabase.lib.walk.util
+ all-source-card-ids
+ all-source-table-ids
+ all-template-tags])
diff --git a/src/metabase/lib/join.cljc b/src/metabase/lib/join.cljc
index da16d38da16..cf0a0b60f50 100644
--- a/src/metabase/lib/join.cljc
+++ b/src/metabase/lib/join.cljc
@@ -25,6 +25,7 @@
[metabase.lib.schema.join :as lib.schema.join]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]
+ [metabase.lib.stage.util :as lib.stage.util]
[metabase.lib.temporal-bucket :as lib.temporal-bucket]
[metabase.lib.types.isa :as lib.types.isa]
[metabase.lib.util :as lib.util]
@@ -361,10 +362,16 @@
;; should disallow refs with `:source-field`/remove it automatically.
:let [field-ref (lib.options/update-options field-ref dissoc :source-field)
match (or (lib.equality/find-matching-column field-ref cols)
+ (when-let [resolved (lib.metadata.calculation/metadata (-> (assoc query :stages (:stages join))
+ lib.stage.util/append-stage)
+ (with-join-alias field-ref nil))]
+ (when-not (:metabase.lib.field.resolution/fallback-metadata? resolved)
+ resolved))
(log/warnf "Failed to find matching column in join %s for ref %s, found:\n%s"
(pr-str join-alias)
(pr-str field-ref)
(pr-str (map (juxt :id :metabase.lib.join/join-alias :lib/source-column-alias) cols))))]
+
:when (and match
(not (false? (:active match))))]
(-> match
diff --git a/src/metabase/lib/metadata.cljc b/src/metabase/lib/metadata.cljc
index 6f24e1dccb5..2491dd84e9f 100644
--- a/src/metabase/lib/metadata.cljc
+++ b/src/metabase/lib/metadata.cljc
@@ -233,3 +233,23 @@
[metadata-providerable :- ::lib.schema.metadata/metadata-providerable
metadata-type :- ::lib.schema.metadata/type]
(lib.metadata.protocols/invoked-ids metadata-providerable metadata-type))
+
+(defn general-cached-value
+ "Get/cache a general value in a cached metadata provider. If the value is already present, it will be returned,
+ otherwise it will be calculated with
+
+ (thunk)
+
+ then saved in the cache and returned.
+
+ `ks` should be unique app-wide (e.g., it should include a namespaced key in the namespace you're using it in.)"
+ [cached-metadata-providerable ks thunk]
+ (let [mp (->metadata-provider cached-metadata-providerable)
+ _ (assert (lib.metadata.protocols/cached-metadata-provider-with-cache? mp)
+ "Not a cached metadata provider with a cache")
+ v (lib.metadata.protocols/cached-value mp ks ::not-found)]
+ (if (= v ::not-found)
+ (let [v (thunk)]
+ (lib.metadata.protocols/cache-value! mp ks v)
+ v)
+ v)))
diff --git a/src/metabase/lib/stage.cljc b/src/metabase/lib/stage.cljc
index b03e24f2a7d..054ada5a2e9 100644
--- a/src/metabase/lib/stage.cljc
+++ b/src/metabase/lib/stage.cljc
@@ -16,11 +16,22 @@
[metabase.lib.schema :as lib.schema]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.schema.metadata :as lib.schema.metadata]
+ [metabase.lib.stage.util]
[metabase.lib.util :as lib.util]
[metabase.lib.util.match :as lib.util.match]
[metabase.util :as u]
[metabase.util.i18n :as i18n]
- [metabase.util.malli :as mu]))
+ [metabase.util.malli :as mu]
+ [metabase.util.namespaces :as shared.ns]))
+
+(comment metabase.lib.stage.util/keep-me)
+
+(shared.ns/import-fns
+ [metabase.lib.stage.util
+ append-stage
+ drop-empty-stages
+ drop-stage
+ has-clauses?])
(lib.hierarchy/derive :mbql.stage/mbql ::stage)
(lib.hierarchy/derive :mbql.stage/native ::stage)
@@ -348,35 +359,6 @@
(lib.util/query-stage query previous-stage-number)
style))))
-(mu/defn has-clauses? :- :boolean
- "Does given query stage have any clauses?"
- [query :- ::lib.schema/query
- stage-number :- :int]
- (boolean (seq (dissoc (lib.util/query-stage query stage-number) :lib/type :source-table :source-card))))
-
-(mu/defn append-stage :- ::lib.schema/query
- "Adds a new blank stage to the end of the pipeline."
- [query]
- (update query :stages conj {:lib/type :mbql.stage/mbql}))
-
-(mu/defn drop-stage :- ::lib.schema/query
- "Drops the final stage in the pipeline, will no-op if it is the only stage"
- [query]
- (if (= 1 (count (:stages query)))
- query
- (update query :stages pop)))
-
-(mu/defn drop-empty-stages :- ::lib.schema/query
- "Drops all empty stages in the pipeline."
- [query :- ::lib.schema/query]
- (update query :stages (fn [stages]
- (into []
- (keep-indexed (fn [stage-number stage]
- (when (or (zero? stage-number)
- (has-clauses? query stage-number))
- stage)))
- stages))))
-
(mu/defn ensure-extra-stage :- [:tuple ::lib.schema/query :int]
"Given a query and current stage, returns a tuple of `[query next-stage-number]`.
diff --git a/src/metabase/lib/stage/util.cljc b/src/metabase/lib/stage/util.cljc
new file mode 100644
index 00000000000..8f526962868
--- /dev/null
+++ b/src/metabase/lib/stage/util.cljc
@@ -0,0 +1,37 @@
+(ns metabase.lib.stage.util
+ "General stage-related utility functions that don't require a any other Lib namespaces except for very general
+ high-level ones like `lib.schema` and `lib.util`. This namespace was spun out from [[metabase.lib.stage]] to avoid
+ circular dependencies between it and other Lib namespaces."
+ (:require
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.util :as lib.util]
+ [metabase.util.malli :as mu]))
+
+(mu/defn has-clauses? :- :boolean
+ "Does given query stage have any clauses?"
+ [query :- ::lib.schema/query
+ stage-number :- :int]
+ (boolean (seq (dissoc (lib.util/query-stage query stage-number) :lib/type :source-table :source-card))))
+
+(mu/defn append-stage :- ::lib.schema/query
+ "Adds a new blank stage to the end of the pipeline."
+ [query]
+ (update query :stages conj {:lib/type :mbql.stage/mbql}))
+
+(mu/defn drop-stage :- ::lib.schema/query
+ "Drops the final stage in the pipeline, will no-op if it is the only stage"
+ [query]
+ (if (= 1 (count (:stages query)))
+ query
+ (update query :stages pop)))
+
+(mu/defn drop-empty-stages :- ::lib.schema/query
+ "Drops all empty stages in the pipeline."
+ [query :- ::lib.schema/query]
+ (update query :stages (fn [stages]
+ (into []
+ (keep-indexed (fn [stage-number stage]
+ (when (or (zero? stage-number)
+ (has-clauses? query stage-number))
+ stage)))
+ stages))))
diff --git a/src/metabase/lib/walk/util.cljc b/src/metabase/lib/walk/util.cljc
new file mode 100644
index 00000000000..2617662b0df
--- /dev/null
+++ b/src/metabase/lib/walk/util.cljc
@@ -0,0 +1,49 @@
+(ns metabase.lib.walk.util
+ "Utility functions built on top of [[metabase.lib.walk]]."
+ (:require
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.schema.id :as lib.schema.id]
+ [metabase.lib.schema.template-tag :as lib.schema.template-tag]
+ [metabase.lib.walk :as lib.walk]
+ [metabase.util.malli :as mu]))
+
+(defn- transduce-stages
+ ([query rf]
+ (transduce-stages query (rf) rf))
+
+ ([query init rf]
+ (let [acc (volatile! init)]
+ (lib.walk/walk-stages
+ query
+ (fn [_query _path stage]
+ (vswap! acc rf stage)
+ nil))
+ (rf @acc))))
+
+(defn- stage-values-set [query xform]
+ (not-empty
+ (transduce-stages query (transient #{}) (-> conj!
+ xform
+ (completing persistent!)))))
+
+(mu/defn all-source-table-ids :- [:maybe [:set {:min 1} ::lib.schema.id/table]]
+ "Return a set of all `:source-table` Table IDs referenced anywhere in the query."
+ [query :- ::lib.schema/query]
+ (stage-values-set query (keep :source-table)))
+
+(mu/defn all-source-card-ids :- [:maybe [:set {:min 1} ::lib.schema.id/card]]
+ "Return a set of all `:source-card` Card IDs referenced anywhere in the query."
+ [query :- ::lib.schema/query]
+ (stage-values-set query (keep :source-card)))
+
+(mu/defn all-template-tags :- [:maybe [:set {:min 1} ::lib.schema.template-tag/template-tag]]
+ "Return a map of Param IDs to sets of Field IDs referenced by each template tag parameter in this `card`.
+
+ Mostly used for determining Fields referenced by Cards for purposes other than processing queries. Filters out
+ `:field` clauses which use names."
+ [query :- ::lib.schema/query]
+ (stage-values-set query (comp (filter (fn [stage]
+ (= (:lib/type stage) :mbql.stage/native)))
+ (mapcat :template-tags)
+ (map (fn [[template-tag-name template-tag]]
+ (assoc template-tag :lib.walk/template-tag-name template-tag-name))))))
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 2d0ff7a1ce2..da779839b21 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -44,7 +44,7 @@
:model/Field metabase.warehouse-schema.models.field
:model/FieldUserSettings metabase.warehouse-schema.models.field-user-settings
:model/FieldValues metabase.warehouse-schema.models.field-values
- :model/GroupTableAccessPolicy metabase-enterprise.sandbox.models.group-table-access-policy
+ :model/Sandbox metabase-enterprise.sandbox.models.sandbox
:model/HTTPAction metabase.actions.models
:model/ImplicitAction metabase.actions.models
:model/LoginHistory metabase.login-history.models.login-history
@@ -90,11 +90,11 @@
:model/Transform metabase-enterprise.transforms.models.transform
:model/TransformJob metabase-enterprise.transforms.models.transform-job
:model/TransformJobRun metabase-enterprise.transforms.models.job-run
- :model/TransformJobTransformTag metabase-enterprise.transforms.models.transform-job-transform-tag
+ :model/TransformJobTransformTag metabase-enterprise.transforms.models.transform-job-transform-tag
:model/TransformRun metabase-enterprise.transforms.models.transform-run
:model/TransformRunCancelation metabase-enterprise.transforms.models.transform-run-cancelation
:model/TransformTag metabase-enterprise.transforms.models.transform-tag
- :model/TransformTransformTag metabase-enterprise.transforms.models.transform-transform-tag
+ :model/TransformTransformTag metabase-enterprise.transforms.models.transform-transform-tag
:model/Undo metabase-enterprise.action-v2.models.undo
:model/User metabase.users.models.user
:model/UserKeyValue metabase.user-key-value.models.user-key-value
diff --git a/src/metabase/parameters/custom_values.clj b/src/metabase/parameters/custom_values.clj
index dedc48c93d0..a9de105c833 100644
--- a/src/metabase/parameters/custom_values.clj
+++ b/src/metabase/parameters/custom_values.clj
@@ -118,6 +118,8 @@
[card value-field]
(boolean
(and (not (:archived card))
+ ;; existing usage -- do not use this in new code
+ #_{:clj-kondo/ignore [:deprecated-var]}
(some? (qp.util/field->field-info value-field (:result_metadata card))))))
;;; --------------------------------------------- Putting it together ----------------------------------------------
diff --git a/src/metabase/permissions/api.clj b/src/metabase/permissions/api.clj
index fc17a4c77dc..588372ce7c6 100644
--- a/src/metabase/permissions/api.clj
+++ b/src/metabase/permissions/api.clj
@@ -48,7 +48,7 @@
(defenterprise upsert-sandboxes!
"OSS implementation of `upsert-sandboxes!`. Errors since this is an enterprise feature."
- metabase-enterprise.sandbox.models.group-table-access-policy
+ metabase-enterprise.sandbox.models.sandbox
[_sandboxes]
(throw (premium-features/ee-feature-error (tru "Sandboxes"))))
diff --git a/src/metabase/permissions/models/data_permissions/graph.clj b/src/metabase/permissions/models/data_permissions/graph.clj
index 51febbd9927..798013c4e4b 100644
--- a/src/metabase/permissions/models/data_permissions/graph.clj
+++ b/src/metabase/permissions/models/data_permissions/graph.clj
@@ -49,7 +49,7 @@
(defenterprise add-sandboxes-to-permissions-graph
"Augment the permissions graph with active connection impersonation policies. OSS implementation returns graph as-is."
- metabase-enterprise.sandbox.models.group-table-access-policy
+ metabase-enterprise.sandbox.models.sandbox
[graph & [_opts]]
graph)
diff --git a/src/metabase/permissions/models/permissions.clj b/src/metabase/permissions/models/permissions.clj
index f69cf94486f..fa5a9f6b963 100644
--- a/src/metabase/permissions/models/permissions.clj
+++ b/src/metabase/permissions/models/permissions.clj
@@ -57,7 +57,7 @@
Segmented permissions allow a User to run ad-hoc MBQL queries against the Table in question; regardless of whether
they have relevant Collection permissions, queries against the sandboxed Table are rewritten to replace the Table
itself with a special type of nested query called a
- [[metabase-enterprise.sandbox.models.group-table-access-policy]], or _GTAP_. Note that segmented permissions are
+ [[metabase-enterprise.sandbox.models.sandbox]], or _GTAP_. Note that segmented permissions are
both additive and subtractive -- they are additive because they grant (sandboxed) ad-hoc query access for a Table,
but subtractive in that any access thru a Saved Question will now be sandboxed as well.
@@ -68,7 +68,7 @@
* Only one GTAP may defined per-Group per-Table (this is an application-DB-level constraint). A User may have
multiple applicable GTAPs if they are members of multiple groups that have sandboxed anti-perms for that Table; in
that case, the QP signals an error if multiple GTAPs apply to a given Table for the current User (see
- [[metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions/assert-one-gtap-per-table]]).
+ [[metabase-enterprise.sandbox.query-processor.middleware.sandboxing/assert-one-gtap-per-table]]).
* Segmented (sandboxing) permissions and GTAPs are tied together, and a Group should be given both (or both
should be deleted) at the same time. This is *not* currently enforced as a hard application DB constraint, but is
@@ -82,7 +82,7 @@
* GTAPs are not allowed to add columns not present in the original Table, or change their effective type to
something incompatible (this constraint is in place so we other things continue to work transparently regardless
of whether the Table is swapped out.) See
- [[metabase-enterprise.sandbox.models.group-table-access-policy/check-columns-match-table]]
+ [[metabase-enterprise.sandbox.models.sandbox/check-columns-match-table]]
* *block \"anti-permissions\"* are per-Group, per-Table grants that tell Metabase to disallow running Saved
Questions unless the User has data permissions (in other words, disregard Collection permissions). These are
@@ -114,7 +114,7 @@
Users would still be prevented from poking around things on their own, however.
The Query Processor middleware in [[metabase.query-processor.middleware.permissions]],
- [[metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions]], and
+ [[metabase-enterprise.sandbox.query-processor.middleware.sandboxing]], and
[[metabase-enterprise.advanced-permissions.models.permissions.block-permissions]] determines whether the current
User has permissions to run the current query. Permissions are as follows:
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index 87e5ebb5ab4..e3df07c21aa 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -216,7 +216,7 @@
(when (map? query)
(let [query-type (lib/normalized-query-type query)]
(case query-type
- :query (-> query mbql.normalize/normalize qp.util/query->source-card-id)
+ :query (-> query mbql.normalize/normalize #_{:clj-kondo/ignore [:deprecated-var]} qp.util/query->source-card-id)
:mbql/query (-> query lib/normalize lib.util/source-card-id)
nil))))
@@ -528,7 +528,7 @@
(defenterprise pre-update-check-sandbox-constraints
"Checks additional sandboxing constraints for Metabase Enterprise Edition. The OSS implementation is a no-op."
- metabase-enterprise.sandbox.models.group-table-access-policy
+ metabase-enterprise.sandbox.models.sandbox
[_ _])
(defn- update-parameters-using-card-as-values-source
@@ -545,17 +545,19 @@
(let [model (case po-type :card 'Card :dashboard 'Dashboard)
{:keys [parameters]} (t2/select-one [model :parameters] :id po-id)
affected-param-ids-set (cond
- ;; update all parameters that use this card as source
+ ;; update all parameters that use this card as source
(:archived changes)
(set (map :parameter_id param-cards))
- ;; update only parameters that have value_field no longer in this card
+ ;; update only parameters that have value_field no longer in this card
(:result_metadata changes)
(let [param-id->parameter (m/index-by :id parameters)]
(->> param-cards
(filter (fn [param-card]
- ;; if cant find the value-field in result_metadata, then we should
- ;; remove it
+ ;; if cant find the value-field in result_metadata, then we should
+ ;; remove it
+ ;; existing usage -- do not use this in new code
+ #_{:clj-kondo/ignore [:deprecated-var]}
(nil? (qp.util/field->field-info
(get-in (param-id->parameter (:parameter_id param-card)) [:values_source_config :value_field])
(:result_metadata changes)))))
diff --git a/src/metabase/queries/models/card/metadata.clj b/src/metabase/queries/models/card/metadata.clj
index 6187245a04d..af625358829 100644
--- a/src/metabase/queries/models/card/metadata.clj
+++ b/src/metabase/queries/models/card/metadata.clj
@@ -56,6 +56,8 @@ saved later when it is ready."
result (deref futur metadata-sync-wait-ms ::timed-out)
combiner (fn [result]
(-> result
+ ;; existing usage, don't use this going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
(qp.util/combine-metadata metadata')))]
(if (= result ::timed-out)
{:metadata-future (future
diff --git a/src/metabase/query_permissions/impl.clj b/src/metabase/query_permissions/impl.clj
index 8d25a14225a..742f3e9d896 100644
--- a/src/metabase/query_permissions/impl.clj
+++ b/src/metabase/query_permissions/impl.clj
@@ -97,7 +97,7 @@
If there's no parent-source-card-id, add the source-card id to the card-ids set and
continue the match setting parent-source-card-id.
- 2. Does the stage have a :query-permissions/gtapped-table key?
+ 2. Does the stage have a :query-permissions/sandboxed-table key?
This means the stage came from a Sandbox query, so we add the table to the table-ids set.
If there's no parent-source-card-id, also add it to the table-query-ids set.
@@ -132,12 +132,12 @@
{:card-ids #{(:qp/stage-is-from-source-card m)}})
(query->source-ids (dissoc m :qp/stage-is-from-source-card) (:qp/stage-is-from-source-card m) in-sandbox?))
- (m :guard (every-pred map? :query-permissions/gtapped-table))
+ (m :guard (every-pred map? :query-permissions/sandboxed-table))
(merge-with merge-source-ids
- {:table-ids #{(:query-permissions/gtapped-table m)}}
+ {:table-ids #{(:query-permissions/sandboxed-table m)}}
(when-not (or parent-source-card-id in-sandbox?)
- {:table-query-ids #{(:query-permissions/gtapped-table m)}})
- (query->source-ids (dissoc m :query-permissions/gtapped-table :native) parent-source-card-id true))
+ {:table-query-ids #{(:query-permissions/sandboxed-table m)}})
+ (query->source-ids (dissoc m :query-permissions/sandboxed-table :native) parent-source-card-id true))
(m :guard (every-pred map? :native))
(when-not parent-source-card-id
@@ -218,7 +218,7 @@
(try
(let [query (mbql.normalize/normalize query)]
;; if we are using a Card as our source, our perms are that Card's (i.e. that Card's Collection's) read perms
- (if-let [source-card-id (qp.util/query->source-card-id query)]
+ (if-let [source-card-id #_{:clj-kondo/ignore [:deprecated-var]} (qp.util/query->source-card-id query)]
{:paths (source-card-read-perms source-card-id)}
;; otherwise if there's no source card then calculate perms based on the Tables referenced in the query
(let [query (cond-> query
@@ -281,7 +281,7 @@
(defn- has-perm-for-table?
"Checks that the current user has the permissions for tables specified in `table-id->perm`. This can be satisfied via
the user's permissions stored in the database, or permissions in `gtap-table-perms` which are supplied by the
- row-level-restrictions QP middleware when sandboxing is in effect. Returns true if access is allowed, otherwise false."
+ `sandboxing` QP middleware when sandboxing is in effect. Returns true if access is allowed, otherwise false."
[perm-type table-id->required-perm gtap-table-perms db-id]
(let [table-id->has-perm?
(into {} (for [[table-id required-perm] table-id->required-perm]
diff --git a/src/metabase/query_processor/api.clj b/src/metabase/query_processor/api.clj
index 3db8c94d51d..24ecdbf2fb1 100644
--- a/src/metabase/query_processor/api.clj
+++ b/src/metabase/query_processor/api.clj
@@ -43,7 +43,7 @@
is a wrapper for the function of the same name in the QP util namespace; it adds additional permissions checking as
well."
[outer-query]
- (when-let [source-card-id (qp.util/query->source-card-id outer-query)]
+ (when-let [source-card-id #_{:clj-kondo/ignore [:deprecated-var]} (qp.util/query->source-card-id outer-query)]
(log/infof "Source query for this query is Card %s" (pr-str source-card-id))
(api/read-check :model/Card source-card-id)
source-card-id))
diff --git a/src/metabase/query_processor/middleware/add_implicit_clauses.clj b/src/metabase/query_processor/middleware/add_implicit_clauses.clj
index b1a54a247dd..296e9587745 100644
--- a/src/metabase/query_processor/middleware/add_implicit_clauses.clj
+++ b/src/metabase/query_processor/middleware/add_implicit_clauses.clj
@@ -4,10 +4,13 @@
[clojure.walk :as walk]
[metabase.legacy-mbql.schema :as mbql.s]
[metabase.legacy-mbql.util :as mbql.u]
+ [metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.metadata.result-metadata :as lib.metadata.result-metadata]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.util.match :as lib.util.match]
[metabase.query-processor.error-type :as qp.error-type]
+ [metabase.query-processor.middleware.annotate.legacy-helper-fns :as annotate.legacy-helper-fns]
[metabase.query-processor.store :as qp.store]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
@@ -112,6 +115,9 @@
(empty? source-metadata)
(qp.store/initialized?))
;; by 'caching' this result, this log message will only be shown once for a given QP run.
+ ;;
+ ;; deprecated usage
+ #_{:clj-kondo/ignore [:deprecated-var]}
(qp.store/cached [::should-add-implicit-fields-warning]
(log/warn (str "Warning: cannot determine fields for an explicit `source-query` unless you also include"
" `source-metadata`.\n"
@@ -124,24 +130,37 @@
(mu/defn- add-implicit-fields
"For MBQL queries with no aggregation, add a `:fields` key containing all Fields in the source Table as well as any
expressions definied in the query."
- [{source-table-id :source-table, :keys [expressions source-metadata], :as inner-query}]
- (if-not (should-add-implicit-fields? inner-query)
- inner-query
- (let [fields (if source-table-id
- (sorted-implicit-fields-for-table source-table-id)
- (source-metadata->fields source-metadata))
- ;; generate a new expression ref clause for each expression defined in the query.
- expressions (for [[expression-name] expressions]
- ;; TODO - we need to wrap this in `u/qualified-name` because `:expressions` uses
- ;; keywords as keys. We can remove this call once we fix that.
- [:expression (u/qualified-name expression-name)])]
- ;; if the Table has no Fields, throw an Exception, because there is no way for us to proceed
- (when-not (seq fields)
- (throw (ex-info (tru "Table ''{0}'' has no Fields associated with it."
- (:name (lib.metadata/table (qp.store/metadata-provider) source-table-id)))
- {:type qp.error-type/invalid-query})))
- ;; add the fields & expressions under the `:fields` clause
- (assoc inner-query :fields (vec (concat fields expressions))))))
+ [{source-table-id :source-table, :keys [expressions], :as inner-query}]
+ ;; calculate metadata if needed for MBQL source queries.
+ (let [inner-query (or (when (and (:source-query inner-query)
+ (not (:source-metadata inner-query))
+ (not (:native (:source-query inner-query))))
+ (when-let [cols (->> (annotate.legacy-helper-fns/legacy-inner-query->mlv2-query (:source-query inner-query))
+ lib.metadata.result-metadata/returned-columns
+ (mapv lib/lib-metadata-column->legacy-metadata-column)
+ not-empty)]
+ (log/infof "Calculated result metadata for source query: %s" (pr-str (mapv :lib/desired-column-alias cols)))
+ (assoc inner-query :source-metadata cols)))
+ inner-query)]
+ (if-not (should-add-implicit-fields? inner-query)
+ inner-query
+ (let [fields (if source-table-id
+ (or (not-empty (sorted-implicit-fields-for-table source-table-id))
+ ;; if the Table has no Fields, throw an Exception, because there is no way for us to
+ ;; proceed
+ (throw (ex-info (tru "Table ''{0}'' has no Fields associated with it."
+ (:name (lib.metadata/table (qp.store/metadata-provider) source-table-id)))
+ {:type qp.error-type/invalid-query})))
+ (or (not-empty (source-metadata->fields (:source-metadata inner-query)))
+ (throw (ex-info "source-metadata->fields unexpectedly returned zero fields"
+ {:inner-query inner-query, :type qp.error-type/qp}))))
+ ;; generate a new expression ref clause for each expression defined in the query.
+ expressions (for [[expression-name] expressions]
+ ;; TODO - we need to wrap this in `u/qualified-name` because `:expressions` uses
+ ;; keywords as keys. We can remove this call once we fix that.
+ [:expression (u/qualified-name expression-name)])]
+ ;; add the fields & expressions under the `:fields` clause
+ (assoc inner-query :fields (vec (concat fields expressions)))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Add Implicit Breakout Order Bys |
@@ -219,10 +238,10 @@
;;; TODO (Cam 7/25/25) -- once this is converted to use Lib we can
;;; remove [[metabase.query-processor.middleware.ensure-joins-use-source-query/ensure-joins-use-source-query]]
-(defn add-implicit-clauses
+(mu/defn add-implicit-clauses :- ::mbql.s/Query
"Add an implicit `fields` clause to queries with no `:aggregation`, `breakout`, or explicit `:fields` clauses.
Add implicit `:order-by` clauses for fields specified in a `:breakout`."
- [{query-type :type, :as query}]
+ [{query-type :type, :as query} :- ::mbql.s/Query]
(if (= query-type :native)
query
(update query :query add-implicit-mbql-clauses)))
diff --git a/src/metabase/query_processor/middleware/add_remaps.clj b/src/metabase/query_processor/middleware/add_remaps.clj
index 0c1780f7891..65fe9bd068a 100644
--- a/src/metabase/query_processor/middleware/add_remaps.clj
+++ b/src/metabase/query_processor/middleware/add_remaps.clj
@@ -421,7 +421,7 @@
{{::keys [original-field-dimension-id new-field-dimension-id]} :options
:as column} :- :map
{dimension-id :id
- from-name :field_name
+ from-name :field-name
from-display-name :name
to-name :human-readable-field-name} :- ::external-remapping]
(log/trace "Considering column\n"
@@ -487,7 +487,10 @@
;;;; Transform to add additional cols to results
-(defn- create-remapped-col [col-name remapped-from base-type]
+(mu/defn- create-remapped-col
+ [col-name :- :string
+ remapped-from :- :string
+ base-type :- ::lib.schema.common/base-type]
{:description nil
:id nil
:table_id nil
@@ -546,7 +549,8 @@
:as col} :- ::column-with-optional-base-type]
(when (seq values)
(let [remap-from (:name col)
- stringified-mask (qp.store/miscellaneous-value [::large-int/column-index-mask])]
+ ;; existing usage -- don't use going forward
+ stringified-mask #_{:clj-kondo/ignore [:deprecated-var]} (qp.store/miscellaneous-value [::large-int/column-index-mask])]
{:col-index idx
:from remap-from
:to remap-to
diff --git a/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj b/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj
index b679361d83f..c7fabc59411 100644
--- a/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj
+++ b/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj
@@ -23,6 +23,8 @@
[:fn
{:error/message "Should be a legacy MBQL inner query"}
(some-fn :query :source-table :source-query)]]]
+ ;; existing usage -- don't use going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
(qp.store/cached [:mlv2-query (hash inner-query)]
(try
(lib/query-from-legacy-inner-query
diff --git a/src/metabase/query_processor/middleware/enterprise.clj b/src/metabase/query_processor/middleware/enterprise.clj
index ac27007e959..4bdf61535ae 100644
--- a/src/metabase/query_processor/middleware/enterprise.clj
+++ b/src/metabase/query_processor/middleware/enterprise.clj
@@ -26,7 +26,7 @@
(defenterprise apply-sandboxing
"Pre-processing middleware. Replaces source tables a User was querying against with source queries that (presumably)
restrict the rows returned, based on presence of sandboxes."
- metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions
+ metabase-enterprise.sandbox.query-processor.middleware.sandboxing
[query]
query)
@@ -118,7 +118,7 @@
(defenterprise merge-sandboxing-metadata
"Post-processing middleware. Merges in column metadata from the original, unsandboxed version of the query."
- metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions
+ metabase-enterprise.sandbox.query-processor.middleware.sandboxing
[_query rff]
rff)
diff --git a/src/metabase/query_processor/middleware/fetch_source_query_legacy.clj b/src/metabase/query_processor/middleware/fetch_source_query_legacy.clj
deleted file mode 100644
index 5c5b07c9ec4..00000000000
--- a/src/metabase/query_processor/middleware/fetch_source_query_legacy.clj
+++ /dev/null
@@ -1,88 +0,0 @@
-(ns ^:deprecated metabase.query-processor.middleware.fetch-source-query-legacy
- "LEGACY IMPLEMENTATION of [[metabase.query-processor.middleware.fetch-source-query]], will be removed soon."
- (:require
- [clojure.set :as set]
- [metabase.driver.ddl.interface :as ddl.i]
- [metabase.driver.util :as driver.u]
- [metabase.legacy-mbql.normalize :as mbql.normalize]
- [metabase.legacy-mbql.schema :as mbql.s]
- [metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]
- [metabase.lib.schema.id :as lib.schema.id]
- [metabase.query-processor.store :as qp.store]
- [metabase.query-processor.util.persisted-cache :as qp.persisted]
- [metabase.system.core :as system]
- [metabase.util :as u]
- [metabase.util.i18n :refer [tru]]
- [metabase.util.log :as log]
- [metabase.util.malli :as mu]))
-
-(set! *warn-on-reflection* true)
-
-;; These next two schemas are for validating the intermediate stages of the middleware. We don't need to validate the
-;; entire query
-(def ^:private SourceQueryAndMetadata
- [:map
- [:source-query mbql.s/SourceQuery]
- [:database ::mbql.s/DatabaseID]
- [:source-metadata [:maybe [:sequential ::mbql.s/legacy-column-metadata]]]
- [:source-query/model? {:optional true} :boolean]
- [:persisted-info/native {:optional true} :string]])
-
-(defn- source-query
- "Get the query to be run from the card"
- [{dataset-query :dataset-query, card-id :id, :as card}]
- (let [dataset-query (cond-> dataset-query
- (:lib/type dataset-query) lib/->legacy-MBQL)
- {db-id :database
- mbql-query :query
- {template-tags :template-tags :as native-query} :native} dataset-query]
- (or
- mbql-query
- ;; rename `:query` to `:native` because source queries have a slightly different shape
- (when-some [native-query (set/rename-keys native-query {:query :native})]
- (let [mongo? (= (driver.u/database->driver db-id) :mongo)]
- (cond-> native-query
- ;; MongoDB native queries consist of a collection and a pipelne (query)
- mongo? (update :native (fn [pipeline] {:collection (:collection native-query)
- :query pipeline}))
- (empty? template-tags) (dissoc :template-tags))))
- (throw (ex-info (tru "Missing source query in Card {0}" card-id)
- {:card card, :dataset-query dataset-query})))))
-
-(mu/defn card-id->source-query-and-metadata :- SourceQueryAndMetadata
- "Return the source query info for Card with `card-id`. Pass true as the optional second arg `log?` to enable
- logging. (The circularity check calls this and will print more than desired)"
- ([card-id :- ::lib.schema.id/card]
- (card-id->source-query-and-metadata card-id false))
-
- ([card-id :- ::lib.schema.id/card log? :- :boolean]
- (let [;; todo: we need to cache this. We are running this in preprocess, compile, and then again
- card (or (lib.metadata/card (qp.store/metadata-provider) card-id)
- (throw (ex-info (tru "Card {0} does not exist." card-id)
- {:card-id card-id})))
- persisted-info (:lib/persisted-info card)
- {{database-id :database} :dataset-query
- result-metadata :result-metadata
- card-type :type} card
- persisted? (qp.persisted/can-substitute? card persisted-info)
- source-query (source-query card)]
- (when (and persisted? log?)
- (log/infof "Found substitute cached query for card %s from %s.%s"
- card-id
- (ddl.i/schema-name {:id database-id} (system/site-uuid))
- (:table-name persisted-info)))
- ;; log the query at this point, it's useful for some purposes
- (log/debugf "Fetched source query from Card %s:\n%s" card-id (u/pprint-to-str 'yellow source-query))
- (cond-> {:source-query (cond-> source-query
- ;; This will be applied, if still appropriate, by the peristence middleware
- persisted?
- (assoc :persisted-info/native
- (qp.persisted/persisted-info-native-query
- (u/the-id (lib.metadata/database (qp.store/metadata-provider)))
- persisted-info)))
- :database database-id
- :source-metadata (sequence (comp (map mbql.normalize/normalize-source-metadata)
- (remove :remapped_from))
- result-metadata)}
- (= card-type :model) (assoc :source-query/model? true)))))
diff --git a/src/metabase/query_processor/middleware/large_int.clj b/src/metabase/query_processor/middleware/large_int.clj
index fd65276dfe8..51695e0c29e 100644
--- a/src/metabase/query_processor/middleware/large_int.clj
+++ b/src/metabase/query_processor/middleware/large_int.clj
@@ -82,6 +82,8 @@
(let [rff' (when js-int-to-string?
(fn [metadata]
(let [mask (column-index-mask (:cols metadata))]
+ ;; existing usage -- don't use going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
(qp.store/store-miscellaneous-value! [::column-index-mask] mask)
(result-large-int->string mask (rff metadata)))))]
(or rff' rff)))
diff --git a/src/metabase/query_processor/middleware/permissions.clj b/src/metabase/query_processor/middleware/permissions.clj
index 565ad6bceea..b559dca7e13 100644
--- a/src/metabase/query_processor/middleware/permissions.clj
+++ b/src/metabase/query_processor/middleware/permissions.clj
@@ -82,15 +82,15 @@
(fn [_query _path-type _path stage-or-join]
(dissoc stage-or-join :qp/stage-is-from-source-card))))
-(defn remove-gtapped-table-keys
- "Pre-processing middleware. Removes any instances of the `:query-permissions/gtapped-table` key which is added by the
+(defn remove-sandboxed-table-keys
+ "Pre-processing middleware. Removes any instances of the `:query-permissions/sandboxed-table` key which is added by the
row-level-restriction middleware when sandboxes are resolved in a query. Since we rely on this for permission
enforcement, we want to disallow users from passing it in themselves (like the functions above)."
[query]
(lib.walk/walk
query
(fn [_query _path-type _path stage-or-join]
- (dissoc stage-or-join :query-permissions/gtapped-table))))
+ (dissoc stage-or-join :query-permissions/sandboxed-table))))
(mu/defn check-query-permissions*
"Check that User with `user-id` has permissions to run `query`, or throw an exception."
diff --git a/src/metabase/query_processor/middleware/persistence.clj b/src/metabase/query_processor/middleware/persistence.clj
index 90c4aef068f..2c932d88582 100644
--- a/src/metabase/query_processor/middleware/persistence.clj
+++ b/src/metabase/query_processor/middleware/persistence.clj
@@ -8,13 +8,13 @@
"Removes persisted information if user is sandboxed or uses connection impersonation. `:persisted-info/native` is set
in [[metabase.query-processor.middleware.fetch-source-query]].
- Sandboxing is detected by the presence of a :query-permissions/gtapped-table key anywhere in the provided query
+ Sandboxing is detected by the presence of a :query-permissions/sandboxed-table key anywhere in the provided query
It may be be possible to use the persistence cache with sandboxing and/or impersonation at a later date with further
work, but for now we skip the cache in these cases."
[query]
(if (and api/*current-user-id*
- (or (some? (lib.util.match/match-one query (m :guard (every-pred map? :query-permissions/gtapped-table))))
+ (or (some? (lib.util.match/match-one query (m :guard (every-pred map? :query-permissions/sandboxed-table))))
(perms/impersonation-enforced-for-db? (:database query))))
(lib.util.match/replace query
(x :guard (every-pred map? :persisted-info/native))
diff --git a/src/metabase/query_processor/middleware/results_metadata.clj b/src/metabase/query_processor/middleware/results_metadata.clj
index 666cde64a77..9eb8ca4f81b 100644
--- a/src/metabase/query_processor/middleware/results_metadata.clj
+++ b/src/metabase/query_processor/middleware/results_metadata.clj
@@ -72,7 +72,11 @@
;; don't want to update metadata when we use a Card as a source Card.
(not (:qp/source-card-id query))
;; Only update changed metadata
- (not= (comparable-metadata actual-metadata) (comparable-metadata (qp.store/miscellaneous-value [::card-stored-metadata]))))
+ (not= (comparable-metadata actual-metadata)
+ (comparable-metadata
+ ;; existing usage -- don't use going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
+ (qp.store/miscellaneous-value [::card-stored-metadata]))))
(when-let [error (me/humanize (mr/explain [:sequential ::lib.schema.metadata/lib-or-legacy-column] actual-metadata))]
(throw (ex-info "Invalid result metadata!" {:error error, :metadata actual-metadata})))
(t2/update! :model/Card card-id {:result_metadata actual-metadata
@@ -149,4 +153,6 @@
(when-let [result-metadata (:result_metadata card)]
(if-let [error (me/humanize (mr/explain [:sequential ::lib.schema.metadata/lib-or-legacy-column] result-metadata))]
(log/errorf "Invalid card result metadata, ignoring it: %s" (pr-str error))
+ ;; existing usage -- don't use going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
(qp.store/store-miscellaneous-value! [::card-stored-metadata] result-metadata))))
diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.clj
index 6eda2352869..c4a29050a36 100644
--- a/src/metabase/query_processor/preprocess.clj
+++ b/src/metabase/query_processor/preprocess.clj
@@ -95,7 +95,7 @@
[#'normalize/normalize-preprocessing-middleware
(ensure-mbql5 #'qp.perms/remove-permissions-key)
(ensure-mbql5 #'qp.perms/remove-source-card-keys)
- (ensure-mbql5 #'qp.perms/remove-gtapped-table-keys)
+ (ensure-mbql5 #'qp.perms/remove-sandboxed-table-keys)
(ensure-mbql5 #'qp.constraints/maybe-add-default-userland-constraints)
(ensure-mbql5 #'validate/validate-query)
(ensure-mbql5 #'fetch-source-query/resolve-source-cards)
@@ -112,7 +112,7 @@
(ensure-legacy #'qp.add-source-metadata/add-source-metadata-for-source-queries)
(ensure-mbql5 #'qp.middleware.enterprise/apply-impersonation)
(ensure-mbql5 #'qp.middleware.enterprise/attach-destination-db-middleware)
- (ensure-legacy #'qp.middleware.enterprise/apply-sandboxing)
+ (ensure-mbql5 #'qp.middleware.enterprise/apply-sandboxing)
(ensure-legacy #'qp.persistence/substitute-persisted-query)
(ensure-legacy #'qp.add-implicit-clauses/add-implicit-clauses) ; #61398
;; this needs to be done twice, once before adding remaps (since we want to add remaps inside joins) and then again
@@ -120,7 +120,7 @@
;; specific columns.
(ensure-legacy #'resolve-joins/resolve-joins) ; #61398
(ensure-mbql5 #'qp.add-remaps/add-remapped-columns)
- #'qp.resolve-fields/resolve-fields ; this middleware actually works with either MBQL 5 or legacy
+ #'qp.resolve-fields/resolve-fields ; this middleware actually works with either MBQL 5 or legacy
(ensure-mbql5 #'binning/update-binning-strategy)
(ensure-mbql5 #'desugar/desugar)
(ensure-mbql5 #'qp.add-default-temporal-unit/add-default-temporal-unit)
@@ -129,7 +129,7 @@
(ensure-mbql5 #'resolve-joined-fields/resolve-joined-fields)
(ensure-mbql5 #'qp.remove-inactive-field-refs/remove-inactive-field-refs)
;; yes, this is called a second time, because we need to handle any joins that got added
- (ensure-legacy #'qp.middleware.enterprise/apply-sandboxing)
+ (ensure-mbql5 #'qp.middleware.enterprise/apply-sandboxing)
(ensure-legacy #'qp.cumulative-aggregations/rewrite-cumulative-aggregations)
(ensure-mbql5 #'qp.wrap-value-literals/wrap-value-literals)
(ensure-mbql5 #'auto-parse-filter-values/auto-parse-filter-values)
diff --git a/src/metabase/query_processor/store.clj b/src/metabase/query_processor/store.clj
index 7f3f225bbc4..9ed07b2eece 100644
--- a/src/metabase/query_processor/store.clj
+++ b/src/metabase/query_processor/store.clj
@@ -12,6 +12,8 @@
Of course, it would be entirely possible to call `(t2/select-one Field :id 10)` every time you needed information
about that Field, but fetching all Fields in a single pass and storing them for reuse is dramatically more efficient
than fetching those Fields potentially dozens of times in a single query execution."
+ ;; This whole namespace is in the process of deprecation so ignore deprecated vars in this namespace.
+ {:clj-kondo/config '{:linters {:deprecated-var {:level :off}}}}
(:require
[metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
[metabase.lib.core :as lib]
@@ -58,16 +60,19 @@
(mu/defn store-miscellaneous-value!
"Store a miscellaneous value in a the cache. Persists for the life of this QP invocation, including for recursive
- calls."
+ calls.
+
+ DEPRECATED -- use [[metabase.lib.metadata/general-cached-value]] going forward."
+ {:deprecated "0.57.0"}
[ks :- [:sequential :any]
v]
(swap! *store* assoc-in ks v))
-;;; TODO (Cam 7/7/25) -- now that we use cached metadata providers consistently and cached metadata providers support
-;;; general value caching we should use those facilities instead. We can remove the bespoke logic here and
-;;; use the stuff in [[metabase.lib.metadata.cache]] instead going forward
(mu/defn miscellaneous-value
- "Fetch a miscellaneous value from the cache. Unlike other Store functions, does not throw if value is not found."
+ "Fetch a miscellaneous value from the cache. Unlike other Store functions, does not throw if value is not found.
+
+ DEPRECATED -- use [[metabase.lib.metadata/general-cached-value]] going forward."
+ {:deprecated "0.57.0"}
([ks]
(miscellaneous-value ks nil))
@@ -80,7 +85,10 @@
value, stores it in the cache, and returns the value. You can use this to ensure a given function is only ran once
during the duration of a QP execution.
- See also `cached` macro."
+ See also `cached` macro.
+
+ DEPRECATED -- use [[metabase.lib.metadata/general-cached-value]] going forward."
+ {:deprecated "0.57.0"}
[ks thunk]
(let [cached-value (miscellaneous-value ks ::not-found)]
(if-not (= cached-value ::not-found)
@@ -99,8 +107,10 @@
;; cache lookups of Card.dataset_query
(qp.store/cached card-id
- (t2/select-one-fn :dataset_query Card :id card-id))"
- {:style/indent 1}
+ (t2/select-one-fn :dataset_query Card :id card-id))
+
+ DEPRECATED -- use [[metabase.lib.core/general-cached-value]] going forward."
+ {:style/indent 1, :deprecated "0.57.0"}
[k-or-ks & body]
;; for the unique key use a gensym prefixed by the namespace to make for easier store debugging if needed
(let [ks (into [(list 'quote (gensym (str (name (ns-name *ns*)) "/misc-cache-")))] (u/one-or-many k-or-ks))]
diff --git a/src/metabase/query_processor/streaming/common.clj b/src/metabase/query_processor/streaming/common.clj
index 224cea336a5..7bfa9233752 100644
--- a/src/metabase/query_processor/streaming/common.clj
+++ b/src/metabase/query_processor/streaming/common.clj
@@ -32,6 +32,8 @@
[t]
(u.date/with-time-zone-same-instant
t
+ ;; existing usage -- don't use going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
(qp.store/cached ::results-timezone (t/zone-id (qp.timezone/results-timezone-id)))))
(defprotocol FormatValue
diff --git a/src/metabase/query_processor/util.clj b/src/metabase/query_processor/util.clj
index 61f4ea1a069..0212ecf9493 100644
--- a/src/metabase/query_processor/util.clj
+++ b/src/metabase/query_processor/util.clj
@@ -144,6 +144,7 @@
(defn query->source-card-id
"Return the ID of the Card used as the \"source\" query of this query, if applicable; otherwise return `nil`."
+ {:deprecated "0.57.0"}
^Integer [outer-query]
(let [source-table (get-in outer-query [:query :source-table])]
(when (string? source-table)
@@ -156,39 +157,48 @@
"A standard and repeatable way to address a column. Names can collide and sometimes are not unique. Field refs should
be stable, except we have to exclude the last part as extra information can be tucked in there. Names can be
non-unique at times, numeric ids are not guaranteed."
+ {:deprecated "0.57.0"}
[[tyype identifier]]
[tyype identifier])
-(def ^:private field-options-for-identification
+(def ^:private ^{:deprecated "0.57.0"} field-options-for-identification
"Set of FieldOptions that only mattered for identification purposes." ;; base-type is required for field that use name instead of id
- #{:source-field :join-alias :base-type})
+ #{:source-field :join-alias})
(defn- field-normalizer
+ {:deprecated "0.57.0"}
[field]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(let [[type id-or-name options] (mbql.normalize/normalize-tokens field)]
[type id-or-name (select-keys options field-options-for-identification)]))
+;;; TODO (Cam 9/10/25) -- this logic is all wrong and needs to use Lib instead
(defn field->field-info
- "Given a field and result_metadata, return a map of information about the field if result_metadata contains a matched field. "
- [field result-metadata]
- (let [[_ttype id-or-name options :as field] (field-normalizer field)]
+ "Given a field ref and result_metadata, return a map of information about the field if result_metadata contains a
+ matched field.
+
+ DEPRECATED -- this is broken, please use Lib instead going forward."
+ {:deprecated "0.57.0"}
+ [field-ref cols]
+ #_{:clj-kondo/ignore [:deprecated-var]}
+ (let [[_ttype id-or-name options :as field-ref] (field-normalizer field-ref)]
(or
;; try match field_ref first
(first (filter (fn [field-info]
- (= field
+ (= field-ref
(-> field-info
:field_ref
field-normalizer)))
- result-metadata))
+ cols))
;; if not match name and base type for aggregation or field with string id
- (first (filter (fn [field-info]
- (and (= (:name field-info)
+ (first (filter (fn [col]
+ (and (= (:name col)
id-or-name)
(= (:base-type options)
- (:base_type field-info))))
- result-metadata)))))
+ (:base_type col))))
+ cols)))))
-(def ^:private preserved-keys
+(def ^:private ^{:deprecated "0.57.0"} preserved-keys
"Keys that can survive merging metadata from the database onto metadata computed from the query. When merging
metadata, the types returned should be authoritative. But things like semantic_type, display_name, and description
can be merged on top."
@@ -203,7 +213,9 @@
metadata in general, so need to blend the saved metadata on top of the computed metadata. First argument should be
the metadata from a run from the query, and `pre-existing` should be the metadata from the database we wish to
ensure survives."
+ {:deprecated "0.57.0"}
[fresh pre-existing]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(let [by-name (m/index-by :name pre-existing)]
(for [{:keys [source] :as col} fresh]
(if-let [existing (and (not= :aggregation source)
diff --git a/src/metabase/tiles/api.clj b/src/metabase/tiles/api.clj
index 0435383436e..3a0db8727d8 100644
--- a/src/metabase/tiles/api.clj
+++ b/src/metabase/tiles/api.clj
@@ -168,6 +168,8 @@
(defn- result->points
[{{:keys [rows cols]} :data} lat-field-ref lon-field-ref]
+ ;; existing usages, don't use this going forward.
+ #_{:clj-kondo/ignore [:deprecated-var]}
(let [lat-key (qp.util/field-ref->key lat-field-ref)
lon-key (qp.util/field-ref->key lon-field-ref)
find-fn (fn [lat-or-lon-key]
diff --git a/src/metabase/xrays/automagic_dashboards/core.clj b/src/metabase/xrays/automagic_dashboards/core.clj
index dbfbf08bc0a..976c4c6b882 100644
--- a/src/metabase/xrays/automagic_dashboards/core.clj
+++ b/src/metabase/xrays/automagic_dashboards/core.clj
@@ -232,7 +232,7 @@
(def ^:private ^{:arglists '([card-or-question])} nested-query?
"Is this card or question derived from another model or question?"
- (comp some? qp.util/query->source-card-id :dataset_query))
+ (comp some? #_{:clj-kondo/ignore [:deprecated-var]} qp.util/query->source-card-id :dataset_query))
(def ^:private ^{:arglists '([card-or-question])} native-query?
"Is this card or question native (SQL)?"
@@ -240,7 +240,7 @@
(defn- source-question
[card-or-question]
- (when-let [source-card-id (qp.util/query->source-card-id (:dataset_query card-or-question))]
+ (when-let [source-card-id #_{:clj-kondo/ignore [:deprecated-var]} (qp.util/query->source-card-id (:dataset_query card-or-question))]
(t2/select-one :model/Card :id source-card-id)))
(defn- table-like?
diff --git a/test/metabase/driver/sql/query_processor_test.clj b/test/metabase/driver/sql/query_processor_test.clj
index a636f7a8d2a..17fc6f592f5 100644
--- a/test/metabase/driver/sql/query_processor_test.clj
+++ b/test/metabase/driver/sql/query_processor_test.clj
@@ -1400,7 +1400,7 @@
(update :query #(str/split-lines (driver/prettify-native-form :h2 %))))))))))
;;; see also [[metabase.query-processor.util.add-alias-info-test/resolve-incorrect-field-ref-for-expression-test]]
-;;; and [[metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test/evil-field-ref-for-an-expression-test]]
+;;; and [[metabase-enterprise.sandbox.query-processor.middleware.sandboxing-test/evil-field-ref-for-an-expression-test]]
(deftest ^:parallel evil-field-ref-for-an-expression-test
(testing "If we accidentally use a :field ref for an :expression, the query should still compile correctly"
;; (this is actually mostly checking that `add-alias-info` or someone else rewrites the `:field` ref as an
diff --git a/test/metabase/driver_api/impl_test.clj b/test/metabase/driver_api/impl_test.clj
new file mode 100644
index 00000000000..8e476ff9df2
--- /dev/null
+++ b/test/metabase/driver_api/impl_test.clj
@@ -0,0 +1,19 @@
+(ns metabase.driver-api.impl-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.driver-api.core :as driver-api]
+ [metabase.lib.test-metadata :as meta]))
+
+(deftest ^:parallel cached-test
+ (testing "make sure `cached` only evaluates its body once during the duration of a QP run"
+ (let [eval-count (atom 0)
+ cached-value (fn []
+ (driver-api/cached :value
+ (swap! eval-count inc)
+ :ok))]
+ (driver-api/with-metadata-provider meta/metadata-provider
+ (is (= :ok (cached-value)))
+ (is (= :ok (cached-value)))
+ (is (= {:value :ok, :eval-count 1}
+ {:value (cached-value)
+ :eval-count @eval-count}))))))
diff --git a/test/metabase/legacy_mbql/normalize_test.cljc b/test/metabase/legacy_mbql/normalize_test.cljc
index 8b5f41e3221..71bd04e07d3 100644
--- a/test/metabase/legacy_mbql/normalize_test.cljc
+++ b/test/metabase/legacy_mbql/normalize_test.cljc
@@ -1517,7 +1517,7 @@
(t/is (= fingerprint
(mbql.normalize/normalize fingerprint)))
(doseq [path [[:query :source-metadata]
- [:metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions/original-metadata]
+ [:metabase-enterprise.sandbox.query-processor.middleware.sandboxing/original-metadata]
[:info :metadata/model-metadata]
[:info :pivot/result-metadata]
[:query :joins 0 :source-metadata]]]
diff --git a/test/metabase/legacy_mbql/schema_test.cljc b/test/metabase/legacy_mbql/schema_test.cljc
index 082ee380b30..bad2a6859f0 100644
--- a/test/metabase/legacy_mbql/schema_test.cljc
+++ b/test/metabase/legacy_mbql/schema_test.cljc
@@ -78,14 +78,11 @@
bad-query (assoc-in correct-query [:native :template-tags "foo" :name] "filter")]
(testing (str "correct-query " (pr-str correct-query))
(is (not (me/humanize (mr/explain mbql.s/Query correct-query))))
- (is (= correct-query
- (mbql.s/validate-query correct-query))))
+ (is (mr/validate ::mbql.s/Query correct-query)))
(testing (str "bad-query " (pr-str bad-query))
(is (me/humanize (mr/explain mbql.s/Query bad-query)))
- (is (thrown-with-msg?
- #?(:clj clojure.lang.ExceptionInfo :cljs cljs.core.ExceptionInfo)
- #"keys in template tag map must match the :name of their values"
- (mbql.s/validate-query bad-query)))))))
+ (is (= {:native {:template-tags ["keys in template tag map must match the :name of their values"]}}
+ (me/humanize (mr/explain ::mbql.s/Query bad-query))))))))
(deftest ^:parallel coalesce-aggregation-test
(testing "should be able to nest aggregation functions within a coalesce"
@@ -100,8 +97,7 @@
[:coalesce [:sum [:field 36 {:base-type :type/Float}]] 1]]
{:name "Avg discount", :display-name "Avg discount"}]]}
:parameters []}]
- (is (not (me/humanize (mr/explain mbql.s/Query query))))
- (is (= query (mbql.s/validate-query query))))))
+ (is (not (me/humanize (mr/explain mbql.s/Query query)))))))
(deftest ^:parallel year-of-era-test
(testing "year-of-era aggregations should be recognized"
@@ -112,8 +108,7 @@
:aggregation [[:count]],
:breakout [[:field 49 {:base-type :type/Date, :temporal-unit :year-of-era, :source-field 43}]]}
:parameters []}]
- (is (not (me/humanize (mr/explain mbql.s/Query query))))
- (is (= query (mbql.s/validate-query query))))))
+ (is (not (me/humanize (mr/explain mbql.s/Query query)))))))
(deftest ^:parallel aggregation-reference-test
(are [schema] (nil? (me/humanize (mr/explain schema [:aggregation 0])))
diff --git a/test/metabase/legacy_mbql/util_test.cljc b/test/metabase/legacy_mbql/util_test.cljc
index 16496cd8f4f..8fede3ebb83 100644
--- a/test/metabase/legacy_mbql/util_test.cljc
+++ b/test/metabase/legacy_mbql/util_test.cljc
@@ -183,28 +183,6 @@
[:= [:field 4 nil] 300]]))
"Should be able to combine multiple compound clauses"))
-(t/deftest ^:parallel map-stages-test
- (let [test-fn (fn [inner-query stage-number]
- (assoc inner-query ::stage-number stage-number))]
- (t/is (=? {:source-table 1
- :filter [:= [:field 1 nil] 100]
- :aggregation [[:count]]
- ::stage-number 0}
- (mbql.u/map-stages test-fn {:source-table 1
- :filter [:= [:field 1 nil] 100]
- :aggregation [[:count]]})))
- (t/is (=? {:source-query {:source-table 1
- :filter [:= [:field 1 nil] 100]
- :aggregation [[:count]]
- ::stage-number 0}
- :expressions {"negated" [:* [:field 1 nil] -1]}
-
- ::stage-number 1}
- (mbql.u/map-stages test-fn {:source-query {:source-table 1
- :filter [:= [:field 1 nil] 100]
- :aggregation [[:count]]}
- :expressions {"negated" [:* [:field 1 nil] -1]}})))))
-
(t/deftest ^:parallel desugar-time-interval-test
(t/is (= [:between
[:field 1 {:temporal-unit :month}]
@@ -653,19 +631,6 @@
(mbql.u/negate-filter-clause
[:inside [:field 1 nil] [:field 2 nil] 10.0 -20.0 -10.0 20.0])))))
-(t/deftest ^:parallel join->source-table-id-test
- (let [join {:strategy :left-join
- :condition [:=
- [:field 48 nil]
- [:field 44 {:join-alias "products"}]]
- :alias "products"}]
- (t/is (= 5
- (mbql.u/join->source-table-id (assoc join :source-table 5))))
- (t/is (= 5
- (mbql.u/join->source-table-id (assoc join :source-query {:source-table 5}))))))
-
-;;; ---------------------------------------------- aggregation-at-index ----------------------------------------------
-
(def ^:private query-with-some-nesting
{:database 1
:type :query
@@ -685,8 +650,6 @@
(t/is (= expected
(apply mbql.u/aggregation-at-index query-with-some-nesting input))))))
-;;; --------------------------------- Unique names & transforming ags to have names ----------------------------------
-
(t/deftest ^:parallel uniquify-names
(t/testing "can we generate unique names?"
(t/is (= ["count" "sum" "count_2" "count_3"]
diff --git a/test/metabase/lib/convert_test.cljc b/test/metabase/lib/convert_test.cljc
index 57e328b26e1..d0f9758ef4e 100644
--- a/test/metabase/lib/convert_test.cljc
+++ b/test/metabase/lib/convert_test.cljc
@@ -823,7 +823,7 @@
:display_name "ID"
:base_type :type/Integer}]}
- :metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions/original-metadata
+ :metabase-enterprise.sandbox.query-processor.middleware.sandboxing/original-metadata
[{:base-type :type/Text
:semantic-type :type/Category
:table-id 32600
@@ -1147,7 +1147,7 @@
(testing "native queries"
(let [query {:type :native}]
(testing "pass the legacy schema"
- (is (mbql.s/valid-query? query)))
+ (is (mr/validate ::mbql.s/Query query)))
(testing "pass the pMBQL schema after conversion"
(is (nil? (->> query
lib.convert/->pMBQL
@@ -1158,7 +1158,7 @@
(testing "MBQL queries"
(let [query {:type :query}]
(testing "pass the legacy schema"
- (is (mbql.s/valid-query? query)))
+ (is (mr/validate ::mbql.s/Query query)))
(testing "pass the pMBQL schema after conversion"
(is (nil? (->> query
lib.convert/->pMBQL
diff --git a/test/metabase/lib/walk/util_test.cljc b/test/metabase/lib/walk/util_test.cljc
new file mode 100644
index 00000000000..af02823e1ad
--- /dev/null
+++ b/test/metabase/lib/walk/util_test.cljc
@@ -0,0 +1,33 @@
+(ns metabase.lib.walk.util-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.lib.core :as lib]
+ [metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util.macros :as lib.tu.macros]
+ [metabase.lib.walk.util :as lib.walk.util]))
+
+(deftest ^:parallel all-source-table-ids-test
+ (testing (str "make sure that `all-table-ids` can properly find all Tables in the query, even in cases where a map "
+ "has a `:source-table` and some of its children also have a `:source-table`"))
+ (is (= (lib.tu.macros/$ids nil
+ #{$$checkins $$venues $$users $$categories})
+ (lib.walk.util/all-source-table-ids
+ (lib/query
+ meta/metadata-provider
+ (lib.tu.macros/mbql-query nil
+ {:source-table $$checkins
+ :joins [{:source-table $$venues
+ :alias "V"
+ :condition [:=
+ $checkins.venue-id
+ &V.venues.id]}
+ {:source-query {:source-table $$users
+ :joins [{:source-table $$categories
+ :alias "Cat"
+ :condition [:=
+ $users.id
+ &Cat.categories.id]}]}
+ :alias "U"
+ :condition [:=
+ $checkins.user-id
+ &U.users.id]}]}))))))
diff --git a/test/metabase/permissions/test_util.clj b/test/metabase/permissions/test_util.clj
index 9eff695febe..a4b7cc09e88 100644
--- a/test/metabase/permissions/test_util.clj
+++ b/test/metabase/permissions/test_util.clj
@@ -15,7 +15,7 @@
;; Select sandboxes _before_ permissions.
(let [original-perms (t2/select :model/Permissions)
original-sandboxes (if config/ee-available?
- (t2/select :model/GroupTableAccessPolicy)
+ (t2/select :model/Sandbox)
[])]
(try
(thunk)
@@ -23,12 +23,12 @@
(binding [perms/*allow-root-entries* true
perms/*allow-admin-permissions-changes* true]
(when config/ee-available?
- (t2/delete! :model/GroupTableAccessPolicy))
+ (t2/delete! :model/Sandbox))
(t2/delete! :model/Permissions)
;; Insert perms _before_ sandboxes because of a foreign key constraint on sandboxes.permission_id
(t2/insert! :model/Permissions original-perms)
(when config/ee-available?
- (t2/insert! :model/GroupTableAccessPolicy original-sandboxes)))))))
+ (t2/insert! :model/Sandbox original-sandboxes)))))))
(defmacro with-restored-perms!
"Runs `body`, and restores permissions and sandboxes to their original state afterwards."
diff --git a/test/metabase/query_processor/card_test.clj b/test/metabase/query_processor/card_test.clj
index 97e32371359..d93381060de 100644
--- a/test/metabase/query_processor/card_test.clj
+++ b/test/metabase/query_processor/card_test.clj
@@ -246,6 +246,8 @@
(is (= [{:name "NAME"
:display_name "Name"
:base_type :type/Text}]
+ ;; existing usage -- don't use going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
(qp.store/miscellaneous-value [::qp.results-metadata/card-stored-metadata]))))))))
;;; adapted from [[metabase.queries.api.card-test/model-card-test-2]]
diff --git a/test/metabase/query_processor/middleware/permissions_test.clj b/test/metabase/query_processor/middleware/permissions_test.clj
index 19d9e6f1fdf..ba8fc22cb94 100644
--- a/test/metabase/query_processor/middleware/permissions_test.clj
+++ b/test/metabase/query_processor/middleware/permissions_test.clj
@@ -767,13 +767,13 @@
#"You do not have permissions to run this query"
(process-query))))))))
-(deftest e2e-ignore-user-supplied-gtapped-tables-test
- (testing "You shouldn't be able to bypass security restrictions by passing in `:query-permissions/gtapped-table` in the query"
+(deftest e2e-ignore-user-supplied-sandboxed-tables-test
+ (testing "You shouldn't be able to bypass security restrictions by passing in `:query-permissions/sandboxed-table` in the query"
(mt/with-no-data-perms-for-all-users!
(perms/set-table-permission! (perms/all-users-group) (mt/id :venues) :perms/create-queries :no)
(perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/view-data :unrestricted)
(let [bad-query {:database (mt/id), :type :query, :query {:source-query {:native "SELECT * FROM VENUES LIMIT 1"
- :query-permissions/gtapped-table (mt/id :venues)}}
+ :query-permissions/sandboxed-table (mt/id :venues)}}
:query-permissions/perms {:gtaps {:perms/view-data :unrestricted
:perms/create-queries :query-builder-and-native}}}]
(mt/with-test-user :rasta
@@ -785,7 +785,7 @@
(letfn [(process-query []
(qp/process-query bad-query))]
(testing "Testing that we will still throw due to the :query-permissions/perms stripping"
- (with-redefs [qp.perms/remove-gtapped-table-keys identity]
+ (with-redefs [qp.perms/remove-sandboxed-table-keys identity]
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"You do not have permissions to run this query"
diff --git a/test/metabase/query_processor/store_test.clj b/test/metabase/query_processor/store_test.clj
index bcb7c057f49..6fbe189d364 100644
--- a/test/metabase/query_processor/store_test.clj
+++ b/test/metabase/query_processor/store_test.clj
@@ -1,4 +1,6 @@
(ns metabase.query-processor.store-test
+ ;; The parent namespace is in the process of deprecation so ignore deprecated vars in this namespace.
+ {:clj-kondo/config '{:linters {:deprecated-var {:level :off}}}}
(:require
[clojure.test :refer :all]
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
diff --git a/test/metabase/query_processor/util/add_alias_info_test.clj b/test/metabase/query_processor/util/add_alias_info_test.clj
index 3e619e5db18..e65cd0107fb 100644
--- a/test/metabase/query_processor/util/add_alias_info_test.clj
+++ b/test/metabase/query_processor/util/add_alias_info_test.clj
@@ -1266,7 +1266,7 @@
first)))))
;;; see also [[metabase.driver.sql.query-processor-test/evil-field-ref-for-an-expression-test]]
-;;; and [[metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test/evil-field-ref-for-an-expression-test]]
+;;; and [[metabase-enterprise.sandbox.query-processor.middleware.sandboxing-test/evil-field-ref-for-an-expression-test]]
(deftest ^:parallel resolve-incorrect-field-ref-for-expression-test
(testing "resolve the incorrect use of a :field ref for an expression correctly"
(let [query (lib/query
diff --git a/test/metabase/query_processor_test/parameters_test.clj b/test/metabase/query_processor_test/parameters_test.clj
index 54ef46e6c54..c5bb5e312b3 100644
--- a/test/metabase/query_processor_test/parameters_test.clj
+++ b/test/metabase/query_processor_test/parameters_test.clj
@@ -719,6 +719,8 @@
[int str]
(qp/process-query query))))))))))))))
+;;; TODO (Cam 9/9/25) -- I added this in #61114 but I don't remember exactly what I was testing... I think this is a
+;;; port of one of the Cypress e2e tests but I don't remember which one. Give this a better name.
(deftest ^:parallel x-test
(mt/test-drivers (mt/normal-drivers)
(let [query (lib/query
diff --git a/test/metabase/query_processor_test/persistence_test.clj b/test/metabase/query_processor_test/persistence_test.clj
index 94c1b8a0839..0dd1e57ed5f 100644
--- a/test/metabase/query_processor_test/persistence_test.clj
+++ b/test/metabase/query_processor_test/persistence_test.clj
@@ -90,7 +90,7 @@
:source-table (str "card__" (:id model))})]
(is (= [[num-rows-query]] (mt/rows (qp/process-query query-on-top)))))))))))))
-;; sandbox tests in metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test
+;; sandbox tests in metabase-enterprise.sandbox.query-processor.middleware.sandboxing-test
;; impersonation tests in metabase-enterprise.advanced-permissions.driver.impersonation-test
(defn- populate-metadata [{query :dataset_query, id :id, :as _model}]