The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Strip internal query-processor keys at the query boundary (#80392)
Alexander Polyankinabf7c47f3c53
diff --git a/enterprise/backend/src/metabase_enterprise/impersonation/middleware.clj b/enterprise/backend/src/metabase_enterprise/impersonation/middleware.cljindex 3bd711f9547..fbce2930e8b 100644--- a/enterprise/backend/src/metabase_enterprise/impersonation/middleware.clj+++ b/enterprise/backend/src/metabase_enterprise/impersonation/middleware.clj@@ -10,12 +10,6 @@^{:clj-kondo/ignore [:deprecated-namespace :discouraged-namespace]} [metabase.query-processor.store :as qp.store][metabase.util.i18n :refer [tru]]))-(defenterprise remove-impersonation-keys- "Pre-processing middleware. Removes the internal `:impersonation/*` keys from the top-level query."- :feature :none- [query]- (dissoc query :impersonation/role :impersonation/admin? :impersonation/allow-write?))-(defenterprise apply-impersonation"Pre-processing middleware. Validates that native queries on impersonated databases are single SELECT statements,and adds an impersonation role key to the query for non-admin users. Currently used solely for caching."diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljcindex 64211e3310d..6e08f1338f6 100644--- a/src/metabase/lib/core.cljc+++ b/src/metabase/lib/core.cljc@@ -1608,6 +1608,7 @@check-measure-cyclescheck-measure-overwrite][metabase.lib.serialize+ prepare-after-deserializationprepare-for-serialization][lib.stageappend-stagediff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljcindex 926897aee3a..85720dd62da 100644--- a/src/metabase/lib/schema.cljc+++ b/src/metabase/lib/schema.cljc@@ -63,7 +63,9 @@(mr/def ::stage.common[:map- {:decode/normalize normalize-stage-common}+ {:decode/normalize normalize-stage-common+ :decode/api common/remove-internal-keys+ :encode/serialize common/remove-internal-keys}[:parameters {:optional true} [:ref ::lib.schema.parameter/parameters]][:lib/stage-metadata {:optional true} [:ref ::lib.schema.metadata/stage]]])@@ -499,13 +501,13 @@(defn- serialize-query [query];; this stuff all gets added in when you actually run a query with one of the QP entrypoints, and is not considered;; to be part of the query itself. It doesn't get saved along with the query in the app DB.+ ;;+ ;; [[common/internal-key?]] also drops all internal namespaced keys the query processor adds, keeping `:lib` keys like+ ;; `:lib/type`.(let [keys-to-remove #{:lib/metadata :info :parameters :viz-settings}](m/filter-keys (fn [k](and (not (contains? keys-to-remove k))- (or (simple-keyword? k)- ;; remove all random namespaced keys like- ;; `:metabase.query-permissions.impl/perms`. Keep `:lib` keys like `:lib/type`- (= (namespace k) "lib"))))+ (not (common/internal-key? k))))query)))(defn- encode-query-for-hashing [query]@@ -527,6 +529,7 @@[:map{:description "Valid MBQL 5 query.":decode/normalize #'normalize-query+ :decode/api #'common/remove-internal-keys:encode/serialize #'serialize-query:encode/for-hashing #'encode-query-for-hashing}[:lib/type [:=diff --git a/src/metabase/lib/schema/common.cljc b/src/metabase/lib/schema/common.cljcindex fdef21acf94..2c905367b68 100644--- a/src/metabase/lib/schema/common.cljc+++ b/src/metabase/lib/schema/common.cljc@@ -68,6 +68,27 @@[m](-> m normalize-map-no-kebab-case map->kebab-case))+(defn internal-key?+ "True if `k` is a namespaced key outside the `:lib` namespace. These are internal keys the query processor adds to a+ query as it runs, as opposed to the `:lib/*` and simple keys that make up a query itself. Handles string keys too,+ since keys are not always keywordized yet when this runs."+ [k]+ (let [k (cond-> k (string? k) keyword)]+ (and (qualified-keyword? k)+ (not= "lib" (namespace k)))))++(defn remove-internal-keys+ "For use as a `:decode/deserialize` (and `:encode/serialize`) transformer on a query/stage/join/options map: remove+ every [[internal-key?]] from map `m`."+ [m]+ (if-not (map? m)+ m+ (reduce-kv (fn [acc k _v]+ (cond-> acc+ (internal-key? k) (dissoc k)))+ m+ m)))+(defn normalize-string-key"Base normalization behavior for things that should be string map keys. Converts keywords to strings if needed. Thisis mostly to work around the REST API recursively keywordizing the entire request body by default."@@ -286,6 +307,7 @@{:default {}}[:map{:decode/normalize #'normalize-options-map+ :decode/api #'remove-internal-keys:encode/for-hashing #'encode-map-for-hashing}[:lib/uuid ::uuid];; these options aren't required for any clause in particular, but if they're present they must follow these schemas.diff --git a/src/metabase/lib/schema/join.cljc b/src/metabase/lib/schema/join.cljcindex a00d2134e21..f13c2fba38c 100644--- a/src/metabase/lib/schema/join.cljc+++ b/src/metabase/lib/schema/join.cljc@@ -119,7 +119,10 @@(mr/def ::join[:and[:map- {:default {}, :decode/normalize normalize-join}+ {:default {}+ :decode/normalize normalize-join+ :decode/api common/remove-internal-keys+ :encode/serialize common/remove-internal-keys}[:lib/type [:= {:default :mbql/join, :decode/normalize common/normalize-keyword} :mbql/join]][:stages [:ref :metabase.lib.schema/stages]][:conditions ::conditions]diff --git a/src/metabase/lib/schema/ref.cljc b/src/metabase/lib/schema/ref.cljcindex 90f3c52fb0c..7b5ffe57803 100644--- a/src/metabase/lib/schema/ref.cljc+++ b/src/metabase/lib/schema/ref.cljc@@ -199,7 +199,7 @@[:tuple[:= {:decode/normalize common/normalize-keyword} :field][:ref ::field.options]- [:or ::id/field :string]]+ [:or :string ::id/field]][:multi {:dispatch (fn [clause];; apparently it still tries to dispatch when humanizing errors even if the `:tuple`;; schema above failed, so we need to check that this is actually a tuple here again.diff --git a/src/metabase/lib/serialize.cljc b/src/metabase/lib/serialize.cljcindex 97394e6728a..5bb12a8b831 100644--- a/src/metabase/lib/serialize.cljc+++ b/src/metabase/lib/serialize.cljc@@ -1,6 +1,7 @@(ns metabase.lib.serialize"Logic for preparising an MBQL 5 query for JSON serialization (for the REST API or app DB). Removes things like- QP-specific keys added during preprocessing."+ QP-specific keys added during preprocessing, and -- in the other direction -- strips those keys back out again after+ a query is deserialized."(:require[malli.core :as mc][malli.transform :as mtx]@@ -22,3 +23,20 @@([schema x]((encoder schema) x)))++(defn- deserializer [schema]+ (mr/cached ::deserializer+ schema+ (fn []+ (mc/decoder schema (mtx/transformer {:name :api})))))++(defn prepare-after-deserialization+ "Inverse of [[prepare-for-serialization]]: run on a query `x` right after it is decoded from JSON coming in from a+ REST API request or the application database, to strip the internal query-processor keys that the query processor adds+ itself during preprocessing -- after this runs -- so stripping them here has no effect on legitimately-added keys.+ Stripping logic is defined in the schemas; grep for `:decode/api` in the `metabase.lib.schema*` namespaces."+ ([x]+ (prepare-after-deserialization ::lib.schema/query x))++ ([schema x]+ ((deserializer schema) x)))diff --git a/src/metabase/lib_be/models/transforms.clj b/src/metabase/lib_be/models/transforms.cljindex d50e83e1997..91ff9de7c71 100644--- a/src/metabase/lib_be/models/transforms.clj+++ b/src/metabase/lib_be/models/transforms.clj@@ -102,7 +102,9 @@(throw (ex-info (format "Expected deserialized query to be a map, got ^%s %s"(.getCanonicalName (class query)) (pr-str query)){:query query})))- (normalize-query query)))+ (-> query+ normalize-query+ lib/prepare-after-deserialization)))(fn [e](log/errorf "Error deserializing dataset_query from app DB: %s" (ex-message e)){}))))diff --git a/src/metabase/lib_be/schema.clj b/src/metabase/lib_be/schema.cljindex 8bc10c3c2e9..e8a9ea49da4 100644--- a/src/metabase/lib_be/schema.clj+++ b/src/metabase/lib_be/schema.clj@@ -2,6 +2,7 @@(:refer-clojure :exclude [empty?])(:require[metabase.lib-be.models.transforms :as lib-be.transforms]+ [metabase.lib.core :as lib][metabase.lib.schema :as lib.schema][metabase.lib.util :as lib.util][metabase.util.i18n :refer [deferred-tru tru]]@@ -17,7 +18,8 @@[query message](if (map? query)(try- (lib-be.transforms/normalize-query nil query {:strict? true})+ (-> (lib-be.transforms/normalize-query nil query {:strict? true})+ lib/prepare-after-deserialization)(catch Exception e(throw (ex-info (ex-message e){:status-code (or (:status-code (ex-data e)) 400)}))))diff --git a/src/metabase/query_processor/middleware/permissions.clj b/src/metabase/query_processor/middleware/permissions.cljindex 37a26a1d991..e7bf69fdb80 100644--- a/src/metabase/query_processor/middleware/permissions.clj+++ b/src/metabase/query_processor/middleware/permissions.clj@@ -5,12 +5,11 @@[metabase.audit-app.core :as audit][metabase.lib.core :as lib][metabase.lib.metadata.protocols :as lib.metadata.protocols]- [metabase.lib.options :as lib.options][metabase.lib.schema :as lib.schema]- [metabase.lib.walk :as lib.walk][metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]][metabase.query-permissions.core :as query-perms]+ [metabase.query-processor.pipeline :as qp.pipeline][metabase.query-processor.schema :as qp.schema]^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store][metabase.query-processor.util :as qp.util]@@ -67,68 +66,13 @@(throw (ex-info (tru "Querying this database requires the audit-app feature flag")query)))-(defn remove-permissions-key- "Pre-processing middleware. Removes the `:query-permissions/perms` key from the query. This is where we store important permissions- information like perms coming from sandboxing (GTAPs). This is programmatically added by middleware when appropriate,- but we definitely don't want users passing it in themselves. So remove it if it's present."- [query]- (dissoc query :query-permissions/perms))--(defenterprise remove-impersonation-keys- "OSS implementation of `remove-impersonation-keys`. Connection impersonation is EE-only, so there is nothing to strip."- metabase-enterprise.impersonation.middleware- [query]- query)--(defn remove-source-card-keys- "Pre-processing middleware. Removes any instances of the `:qp/stage-is-from-source-card` key which is added by the- fetch-source-query middleware when source cards are resolved in a query. Since we rely on this for permission enforcement,- we want to disallow users from passing it in themselves (like `remove-permissions-key` above)."- [query]- (lib.walk/walk- query- (fn [_query _path-type _path stage-or-join]- (dissoc stage-or-join :qp/stage-is-from-source-card))))--(def ^:private allowed-stage-keys- #{:persisted-info/native- :qp/stage-is-from-source-card- :qp/stage-had-source-card- :source-query/model?- :source-query/native-model?- :query-permissions/referenced-card-ids})--(defn- allowed-clause-key?- [k]- (case (namespace k)- (nil "lib") true- false))--(defn- allowed-stage-key?- [k]- (or (allowed-clause-key? k)- (contains? allowed-stage-keys k)))--(defn- remove-keys- [m allowed?]- (reduce-kv (fn [m k _v]- (cond-> m- (not (allowed? k)) (dissoc k)))- m- m))--(defn remove-namespaced-options- "Pre-processing middleware. Strip namespaced keys that are not in the allow-list from every stage, join, and clause- options map in `query`."- [query]- (-> query- (lib.walk/walk- (fn [_query _path-type _path stage-or-join]- (remove-keys stage-or-join allowed-stage-key?)))- (lib.walk/walk-clauses- (fn [_query _path-type _path clause]- (when-let [options (lib.options/options clause)]- (lib.options/with-options clause (remove-keys options allowed-clause-key?)))))))+(mu/defn remove-internal-keys :- ::lib.schema/query+ "Pre-processing middleware. Strip internal query-processor keys from the incoming `query` so that they can only ever+ be set by the query processor itself, not supplied by a client. Skipped while re-running pivot sub-queries, which+ legitimately carry these keys."+ [query :- ::lib.schema/query]+ (cond-> query+ (not qp.pipeline/*pivot?*) lib/prepare-after-deserialization))(mu/defn record-referenced-card-ids :- ::lib.schema/query"Pre-processing middleware. Record the source-card IDs referenced by `query` under the@@ -136,16 +80,6 @@[query :- ::lib.schema/query](u/assoc-dissoc query :query-permissions/referenced-card-ids (lib/all-source-card-ids-recursive query)))-(defn remove-persisted-info-native-keys- "Pre-processing middleware. Removes any `:persisted-info/native` keys from the query. This key is populated later by- the fetch-source-query middleware to point at a persisted/cached native query, so any value already present at this- stage is stale and is cleared (like the functions above)."- [query]- (lib.walk/walk- query- (fn [_query _path-type _path stage-or-join]- (dissoc stage-or-join :persisted-info/native))))-(mu/defn check-query-permissions*"Check that User with `user-id` has permissions to run `query`, or throw an exception."[query :- ::qp.schema/any-query]diff --git a/src/metabase/query_processor/pipeline.clj b/src/metabase/query_processor/pipeline.cljindex c0faac507d1..ed5497bb01e 100644--- a/src/metabase/query_processor/pipeline.clj+++ b/src/metabase/query_processor/pipeline.clj@@ -7,6 +7,12 @@[metabase.util.i18n :as i18n][metabase.util.log :as log]))+(def ^:dynamic *pivot?*+ "True while [[metabase.query-processor.pivot]] is re-running its generated sub-queries through the query processor.+ These sub-queries carry internal `:qp.pivot/*` keys and already-derived annotations, so preprocessing must not strip+ internal keys from them."+ false)+(def ^:dynamic ^clojure.core.async.impl.channels.ManyToManyChannel *canceled-chan*"If this channel is bound, you can send it a message to cancel the query. You can check if it has received a messageto see if the query has been canceled.diff --git a/src/metabase/query_processor/pivot.clj b/src/metabase/query_processor/pivot.cljindex 0976ade1b1a..e398ca92863 100644--- a/src/metabase/query_processor/pivot.clj+++ b/src/metabase/query_processor/pivot.clj@@ -816,12 +816,15 @@;; run-pivot-query, so binding it here from the query's :info map would be;; redundant and could mis-set it for ad-hoc queries that carry a :card-id in :info.(qp.setup/with-qp-setup [query query]- (let [query (qp.middleware.normalize/normalize-preprocessing-middleware query)+ (let [query (-> query+ qp.middleware.normalize/normalize-preprocessing-middleware+ lib/prepare-after-deserialization)db (query-database query)nativable? (native-path-applicable? db query)use-native? (and nativable? (qp.settings/use-native-pivot-tables))primary (if use-native? run-native-pivot-query run-pivot-query-multi)secondary (if use-native? run-pivot-query-multi run-native-pivot-query)]- (if (and nativable? (pivot-parity-enabled?))- (run-with-parity-check primary secondary query rff use-native?)- (primary query rff))))))+ (binding [qp.pipeline/*pivot?* true]+ (if (and nativable? (pivot-parity-enabled?))+ (run-with-parity-check primary secondary query rff use-native?)+ (primary query rff)))))))diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.cljindex 811e2ead705..eaff3e0b7f7 100644--- a/src/metabase/query_processor/preprocess.clj+++ b/src/metabase/query_processor/preprocess.clj@@ -60,10 +60,7 @@All of these middlewares assume MBQL 5.";; ↓↓↓ PRE-PROCESSING ↓↓↓ happens from TOP TO BOTTOM[#'normalize/normalize-preprocessing-middleware- #'qp.perms/remove-permissions-key- #'qp.perms/remove-impersonation-keys- #'qp.perms/remove-source-card-keys- #'qp.perms/remove-persisted-info-native-keys+ #'qp.perms/remove-internal-keys#'qp.perms/record-referenced-card-ids#'qp.constraints/maybe-add-default-userland-constraints#'validate/validate-query@@ -76,7 +73,6 @@#'expand-macros/expand-macros#'nest-for-pivot/nest-for-pivot#'qp.resolve-referenced/resolve-referenced-card-resources- #'qp.perms/remove-namespaced-options#'parameters/substitute-parameters#'qp.resolve-source-table/resolve-source-tables#'qp.auto-bucket-datetimes/auto-bucket-datetimesdiff --git a/test/metabase/lib/schema/ref_test.cljc b/test/metabase/lib/schema/ref_test.cljcindex 175bf02e443..1b8f83e86b4 100644--- a/test/metabase/lib/schema/ref_test.cljc+++ b/test/metabase/lib/schema/ref_test.cljc@@ -38,12 +38,12 @@;; I don't know why the Cljs versions give us slightly different answers, but I think that's an upstream Malli;; problem, so I'm not going to spend too much time digging in to it. Close enough.[:field {:lib/uuid "ede8dc3c-de7e-49ec-a78c-bacfb43f2301"} :1]- #?(:clj [nil nil ["should be a positive int" "should be a string"]]- :cljs [nil nil ["should be a positive int" "should be a string"]])+ #?(:clj [nil nil ["should be a string" "should be a positive int"]]+ :cljs [nil nil ["should be a string" "should be a positive int"]])[:field {:lib/uuid "ede8dc3c-de7e-49ec-a78c-bacfb43f2301"} -1]- #?(:clj [nil nil ["should be a positive int" "should be a string" "should be a positive int"]]- :cljs [nil nil ["should be a positive int" "should be a string" "should be a positive int"]]))))+ #?(:clj [nil nil ["should be a string" "should be a positive int" "should be a positive int"]]+ :cljs [nil nil ["should be a string" "should be a positive int" "should be a positive int"]]))))(deftest ^:parallel field-with-empty-name-test(testing "We need to support fields with empty names, this is legal in SQL Server (QUE-1418)"diff --git a/test/metabase/lib_be/models/transforms_test.clj b/test/metabase/lib_be/models/transforms_test.cljindex deaee1a8762..4a002b47cc3 100644--- a/test/metabase/lib_be/models/transforms_test.clj+++ b/test/metabase/lib_be/models/transforms_test.clj@@ -6,7 +6,8 @@[metabase.models.interface :as mi][metabase.test :as mt][metabase.util.json :as json]- [metabase.util.malli :as mu]))+ [metabase.util.malli :as mu]+ [toucan2.core :as t2]))(deftest ^:parallel handle-bad-template-tags-test(testing (str "an malformed template tags map like the one below is invalid. Rather than potentially destroy an entire API "@@ -161,3 +162,20 @@:display-name "Bar":type :card:card-id 123}}}}))))))++(deftest transform-query-out-strips-internal-keys-test+ (testing "an internal namespaced key is stripped when a dataset_query is read back out of the app DB"+ (is (not (contains? ((:out lib-be/transform-query)+ (json/encode {:database (mt/id)+ :type :query+ :query {:source-table (mt/id :venues)}+ :a/b 1}))+ :a/b)))))++(deftest card-dataset-query-strips-internal-keys-test+ (testing "a forged internal namespaced key in a Card's :dataset_query does not survive a round-trip through the app DB"+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query {:database (mt/id)+ :type :query+ :query {:source-table (mt/id :venues)}+ :a/b 1}}]+ (is (not (contains? (:dataset_query (t2/select-one :model/Card :id card-id)) :a/b))))))diff --git a/test/metabase/query_permissions/impl_test.clj b/test/metabase/query_permissions/impl_test.cljindex 45833779cd0..3167ef540ea 100644--- a/test/metabase/query_permissions/impl_test.clj+++ b/test/metabase/query_permissions/impl_test.clj@@ -338,7 +338,7 @@:card-ids #{card-1-id card-2-id}:paths #{(format "/collection/%d/read/" collection-1-id)(format "/collection/%d/read/" collection-2-id)}}- (query-perms/required-perms-for-query native-query)))+ (query-perms/required-perms-for-query native-query :already-preprocessed? true)))(testing "MBQL 5 query"(is (= {:perms/create-queries :query-builder-and-native:perms/view-data :unrestricted@@ -347,7 +347,8 @@(format "/collection/%d/read/" collection-2-id)}}(query-perms/required-perms-for-query(lib/query (mt/metadata-provider)- (lib/->mbql5 native-query)))))))))))+ (lib/->mbql5 native-query))+ :already-preprocessed? true)))))))))(deftest ^:parallel native-query-source-card-id-join-permissions-test(testing "MBQL query with native source card (#30077)"diff --git a/test/metabase/query_processor/preprocess_test.clj b/test/metabase/query_processor/preprocess_test.cljindex 58a5f17b7e3..56f802402a4 100644--- a/test/metabase/query_processor/preprocess_test.clj+++ b/test/metabase/query_processor/preprocess_test.clj@@ -637,3 +637,8 @@:lib/source-column-alias "count":lib/desired-column-alias "count"}](qp.preprocess/query->expected-cols query))))))))++(deftest ^:parallel remove-internal-keys-test+ (testing "an internal namespaced key supplied in an incoming query does not survive preprocessing"+ (is (not (contains? (qp.preprocess/preprocess (assoc (mt/mbql-query venues) :a/b 1))+ :a/b)))))