Skip to content

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

Don't strip values from impersonation validation (#74440)

Riley Thompsonaa971184b0de
diff --git a/src/metabase/sql_parsing/core.clj b/src/metabase/sql_parsing/core.clj
index 5a712b4b5af..3fc48658d0e 100644
--- a/src/metabase/sql_parsing/core.clj
+++ b/src/metabase/sql_parsing/core.clj
@@ -537,14 +537,19 @@
"Validates that a query is a single read statement (SELECT) or a single write statement (INSERT, UPDATE, DELETE)
and returns the query reconstructed from the parsed AST."
[dialect sql stmt-type]
- (let [sql (strip-large-values sql)]
- (-> (with-open [^Closeable ctx (python.pool/python-context)]
- (with-python-timeout ctx default-timeout-ms
- (-> ^Value (common/eval-python ctx "sql_tools.is_single_stmt_of_type")
- (.execute ^Value (object-array [sql stmt-type dialect]))
- .asString)))
- json/decode+kw
- (perf/update-keys (comp keyword u/->kebab-case-en)))))
+ (let [stripped-sql (strip-large-values sql)
+ result (-> (with-open [^Closeable ctx (python.pool/python-context)]
+ (with-python-timeout ctx default-timeout-ms
+ (-> ^Value (common/eval-python ctx "sql_tools.is_single_stmt_of_type")
+ (.execute ^Value (object-array [stripped-sql stmt-type dialect]))
+ .asString)))
+ json/decode+kw
+ (perf/update-keys (comp keyword u/->kebab-case-en)))]
+ ;; The `:sql` in the `result` is the reconstructed SQL from the SQLGlot parser.
+ ;; We generally want to use the reconstructed SQL, but if the original SQL had its values stripped (to avoid GraalPy OOM)
+ ;; then we need to return the original SQL to preserve the values. (#74284)
+ (cond-> result
+ (not= sql stripped-sql) (assoc :sql sql))))
(comment
(referenced-tables "postgres" "select * from transactions")
diff --git a/test/metabase/sql_tools/core_test.clj b/test/metabase/sql_tools/core_test.clj
index e6374c6e497..f500dd324d9 100644
--- a/test/metabase/sql_tools/core_test.clj
+++ b/test/metabase/sql_tools/core_test.clj
@@ -230,3 +230,14 @@
"SELECT * FROM foo INTERSECT ALL SELECT * FROM bar EXCEPT ALL SELECT * FROM baz"
"SELECT * FROM foo EXCEPT ALL SELECT * FROM bar UNION ALL SELECT * FROM baz"
"SELECT * FROM foo EXCEPT ALL SELECT * FROM bar INTERSECT ALL SELECT * FROM baz"))))
+
+(deftest ^:parallel is-single-stmt-of-type-not-stripped-test
+ (testing "we don't remove value clauses when validating impersonated queries (#74284)"
+ (let [values-query (str "SELECT x FROM (VALUES " (str/join ", " (repeat 105 "(1)")) ") AS t(x)")]
+ (are [sql is-single-stmt?] (= {:is-single-stmt? is-single-stmt? :sql sql}
+ (sql-tools/is-single-stmt-of-type? :postgres sql "read"))
+ values-query true
+ (str "SELECT 1; " values-query) false
+ (str "SET ROLE none; " values-query) false
+ (str values-query "; SELECT 1") false
+ (str values-query "; SET ROLE none") false))))