Skip to content

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

Apply the configured path settings to SQLite database files (#83497)

Nathan Voxland187143311b22
diff --git a/src/metabase/driver/settings.clj b/src/metabase/driver/settings.clj
index 22e0716eae6..f6033d9f18d 100644
--- a/src/metabase/driver/settings.clj
+++ b/src/metabase/driver/settings.clj
@@ -232,6 +232,26 @@
Sample Database (sync, schema refresh, fingerprinting, etc.) bind this to `true`."
false)
+(def ^:private sqlite-sample-database-path
+ "The exact `:db` path string of the bundled Sample Database, registered by the sample-data module when it extracts
+ the file, or nil before then. On a hosted instance, SQLite may open no other file; on self-hosted, this one is exempt
+ from the `readable-paths` and `writable-paths` allowlists. Exact-string match is enough: a stored Database row
+ carries the registered string verbatim, so a match can only name the Sample Database file itself."
+ (atom nil))
+
+(defn register-sqlite-sample-database-path!
+ "Record `path` as the bundled Sample Database's file, replacing any path recorded before. Called by the sample-data
+ module each time it extracts the file."
+ [path]
+ (reset! sqlite-sample-database-path path))
+
+(defn sqlite-sample-database-path?
+ "Whether `db` (a SQLite `:db` connection detail) is exactly the path registered via
+ [[register-sqlite-sample-database-path!]]."
+ [db]
+ (boolean (and (string? db)
+ (= db @sqlite-sample-database-path))))
+
(defn- -jdbc-data-warehouse-unreturned-connection-timeout-seconds []
(or (setting/get-value-of-type :integer :jdbc-data-warehouse-unreturned-connection-timeout-seconds)
(long (/ *query-timeout-ms* 1000))))
diff --git a/src/metabase/driver/sqlite.clj b/src/metabase/driver/sqlite.clj
index cdc85842be8..c4f9297605e 100644
--- a/src/metabase/driver/sqlite.clj
+++ b/src/metabase/driver/sqlite.clj
@@ -1,5 +1,5 @@
(ns metabase.driver.sqlite
- (:refer-clojure :exclude [mapv])
+ (:refer-clojure :exclude [mapv some])
(:require
[clojure.java.io :as io]
[clojure.java.jdbc :as jdbc]
@@ -23,7 +23,7 @@
[metabase.util.honey-sql-2 :as h2x]
[metabase.util.i18n :refer [tru]]
[metabase.util.malli :as mu]
- [metabase.util.performance :refer [mapv]])
+ [metabase.util.performance :refer [mapv some]])
(:import
(java.net MalformedURLException URL)
(java.sql Connection ResultSet Types)
@@ -83,20 +83,103 @@
(or (str/includes? line "SQLite format 3")
(str/includes? line "This file contains an SQLite"))))))
-(defmethod driver/validate-db-details! :sqlite
- [_driver _details]
- ;; On hosted Metabase, SQLite is only valid for the bundled Sample Database. The internal flows that need to test
- ;; connections to that DB (sync, schema refresh, fingerprinting, etc.) wrap their calls in
- ;; `(binding [driver.settings/*allow-testing-sqlite-connections* true] ...)`. Mirrors the H2 pattern.
- (when (and (driver-api/is-hosted?)
- (not driver.settings/*allow-testing-sqlite-connections*))
+(defn- sqlite-uri-decode
+ "`s` with each well-formed `%XX` escape decoded, as SQLite does for a `file:` URI. A malformed escape stays as it is
+ without affecting the others."
+ [^String s]
+ (str/replace s #"(?:%[0-9A-Fa-f]{2})+"
+ (fn [^String run]
+ (String. (byte-array (map #(unchecked-byte (Integer/parseInt (subs run (inc %) (+ % 3)) 16))
+ (range 0 (count run) 3)))
+ "UTF-8"))))
+
+(defn- file-uri-path
+ "The decoded path SQLite opens for a `file:` URI with no `?`, or nil when it opens no local file. `file:/a`,
+ `file:///a` and `file://localhost/a` are `/a` and `file:a` is `a`. SQLite ignores everything from `#` on, decodes
+ each `%XX` escape, ends the path at a decoded NUL, and refuses any authority but an empty one or (case-sensitively)
+ `localhost`."
+ [uri]
+ (let [path (subs (first (str/split uri #"#" 2)) (count "file:"))
+ path (if (str/starts-with? path "//")
+ (let [path-start (or (str/index-of path "/" 2) (count path))]
+ (when (contains? #{"" "localhost"} (subs path 2 path-start))
+ (subs path path-start)))
+ path)]
+ (some-> path sqlite-uri-decode (str/split #"\u0000" 2) first)))
+
+(defn- db-local-file
+ "The file on the Metabase host that SQLite opens for the `:db` detail, or nil when `:db` is not a form the driver
+ supports: a plain path, or a `file:` URI, with no `?` in either.
+
+ Every other form is unsupported: in-memory names, `:resource:` downloads, other URL schemes (`jar:`, `http:` ...), a
+ `file:` URI whose authority is neither empty nor `localhost`, and anything with a `?`. sqlite-jdbc reads its own
+ settings from after a `?` in a plain path as well as in a URI, and strips them from the name it opens, so with one
+ the file SQLite opens is not the one these checks see. Refusing these as a whole means no SQLite or sqlite-jdbc
+ option reaches a connection. SQLite matches the `file:` prefix case-sensitively, so another case is refused as a URL
+ scheme, and a value starting with `:` is refused as a special name."
+ [db]
+ (when (and (string? db) (not (str/blank? db)) (not (str/includes? db "?")))
+ (if (str/starts-with? db "file:")
+ (let [path (file-uri-path db)]
+ (when-not (or (str/blank? path) (= path ":memory:"))
+ path))
+ ;; a scheme of two or more characters, so a Windows drive letter is still a path
+ (when-not (or (str/starts-with? db ":")
+ (re-find #"^[A-Za-z][A-Za-z0-9+.-]+:" db))
+ db))))
+
+(defn- db-local-files
+ "Every file [[db-local-file]] names for `db`, read both as given and trimmed, so a check does not depend on whether
+ whitespace around it reaches SQLite. Throws when either reading is not a supported form."
+ [db]
+ (let [files (map db-local-file (distinct [db (some-> db str/trim)]))]
+ (when (some nil? files)
+ (throw (ex-info (tru "SQLite database must be a file path or a file: URI without a \"?\".")
+ {:status-code 400})))
+ (set files)))
+
+(defn- check-db-file!
+ "Throw unless SQLite may open the database `details` describe. On hosted Metabase, SQLite is only valid for the
+ bundled Sample Database, which callers exempt before calling this. Otherwise `:db` must be a supported form naming a
+ file on the Metabase host that `readable-paths` allows, and that `writable-paths` allows too unless the connection is
+ read-only."
+ [{:keys [db read-only?]}]
+ (when (driver-api/is-hosted?)
(throw (ex-info (tru "SQLite is not available as a data warehouse on Metabase Cloud.")
- {:status-code 400}))))
+ {:status-code 400})))
+ (doseq [path (db-local-files db)]
+ (driver-api/ensure-readable-path! path)
+ (when-not read-only?
+ (driver-api/ensure-writable-path! path))))
+
+(defn- sample-database?
+ "Whether `details` open the bundled Sample Database the way Metabase does: read-only, at the exact path the
+ sample-data module registered."
+ [{:keys [db read-only?]}]
+ (boolean (and read-only?
+ (driver.settings/sqlite-sample-database-path? db))))
+
+(defmethod driver/validate-db-details! :sqlite
+ [_driver details]
+ ;; The bundled Sample Database is the one file Metabase itself opens, so it is exempt from the checks: it lives in the
+ ;; plugins directory, which neither `readable-paths` nor a hosted instance's allowlist need cover. Two things must
+ ;; both hold for the exemption here:
+ ;; - the caller is an internal flow that needs it (sync, schema refresh, fingerprinting, etc.), which wraps its
+ ;; calls in `(binding [driver.settings/*allow-testing-sqlite-connections* true] ...)`, so that a user-facing
+ ;; endpoint such as `POST /api/database` cannot create a connection to it, and
+ ;; - the details are the Sample Database's own: read-only, at the exact path the sample-data module registered.
+ ;; Sync binds the flag for every database, so the flag alone would let it open whatever `:db` a stored row
+ ;; carries, such as one written by a serialization import.
+ (when-not (and driver.settings/*allow-testing-sqlite-connections*
+ (sample-database? details))
+ (check-db-file! details))
+ nil)
(defmethod driver/can-connect? :sqlite
[driver details]
(driver/validate-db-details! driver details)
- (if (confirm-file-is-sqlite (:db details))
+ ;; read the header of the local file the checks above validated, opened as a plain file
+ (if (confirm-file-is-sqlite (io/file (db-local-file (:db details))))
(sql-jdbc.conn/can-connect? driver details)
false))
@@ -123,9 +206,12 @@
(u/lower-case-en (if (instance? clojure.lang.Named k) (name k) (str k)))))
(defmethod sql-jdbc.conn/connection-details->spec :sqlite
- [_ {:keys [db read-only?]
- :or {db "sqlite.db"}
- :as details}]
+ [_ {:keys [db read-only?] :as details}]
+ ;; Every connection is built from this spec, including one for a Database row that never went through a connection
+ ;; test (a serialization import, or a row stored before the path settings were set), so the file checks run here too.
+ ;; The Sample Database is exempt by its details alone: queries on it do not bind the testing flag.
+ (when-not (sample-database? details)
+ (check-db-file! details))
(merge {:classname "org.sqlite.JDBC"
:subprotocol "sqlite"
:subname db}
@@ -162,7 +248,9 @@
;; Two things in `:db` have the client fetch the database file from a URL, and no SSH tunnel carries either, so they
;; are reported here, where they are checked whether or not a tunnel is in use, rather than as a connection host:
;; - `:resource:<url>`, which SQLite-JDBC reads from that URL (after trying the classpath);
- ;; - a `:db` that is itself a URL, which the file check in [[can-connect?]] opens with `io/input-stream`.
+ ;; - a `:db` that is itself a URL.
+ ;; The file checks in [[check-db-file!]] refuse both forms before a connection opens; reporting their hosts here keeps
+ ;; them under the network policy as well.
(let [db (when (string? db) db)
resource (some-> db (str/trim) (->> (re-find #"(?i)^:resource:(.*)$")) second)]
(into ((get-method driver/connection-parameter-hosts :sql-jdbc) driver details)
diff --git a/src/metabase/sample_data/impl.clj b/src/metabase/sample_data/impl.clj
index e581d514441..e87f0bd5d7e 100644
--- a/src/metabase/sample_data/impl.clj
+++ b/src/metabase/sample_data/impl.clj
@@ -3,6 +3,7 @@
(:require
[clojure.java.io :as io]
[clojure.string :as str]
+ [metabase.driver.settings :as driver.settings]
[metabase.driver.util :as driver.u]
[metabase.plugins.core :as plugins]
[metabase.sample-data.db :as sample-data.db]
@@ -59,8 +60,12 @@
[engine dest-path]
(case engine
;; SQLite `:details` only need a filesystem path. URL-decode in case it got URL-encoded from a JAR `URL`.
- ;; The bundled file is read-only.
- :sqlite {:db (codec/url-decode dest-path), :read-only? true}
+ ;; The bundled file is read-only. Register the path so the driver's checks (the hosted-instance guard and the
+ ;; readable/writable path allowlists) will permit opening this one file -- see
+ ;; [[metabase.driver.settings/register-sqlite-sample-database-path!]].
+ :sqlite (let [db (codec/url-decode dest-path)]
+ (driver.settings/register-sqlite-sample-database-path! db)
+ {:db db, :read-only? true})
;; H2 connects to the file by path (sans the `.mv.db` suffix).
:h2 {:db (-> (str "file:" dest-path)
(str/replace #"\.mv\.db$" "")
diff --git a/test/metabase/driver/sqlite_test.clj b/test/metabase/driver/sqlite_test.clj
index 2583b5a31be..72fdb60fd1c 100644
--- a/test/metabase/driver/sqlite_test.clj
+++ b/test/metabase/driver/sqlite_test.clj
@@ -6,6 +6,7 @@
[clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[metabase.driver :as driver]
+ [metabase.driver.settings :as driver.settings]
[metabase.driver.sql :as driver.sql]
[metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.driver.sql-jdbc.sync :as sql-jdbc.sync]
@@ -14,6 +15,7 @@
[metabase.driver.util :as driver.u]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.models.serialization :as serdes]
[metabase.query-processor.test :as qp]
[metabase.sync.core :as sync]
[metabase.test :as mt]
@@ -23,6 +25,285 @@
(set! *warn-on-reflection* true)
+(deftest unsupported-db-forms-test
+ ;; Only a plain file path or a local `file:` URI, without a `?` in either, names a database. Everything else SQLite
+ ;; or sqlite-jdbc accepts -- in-memory names, `:resource:` downloads, other URL schemes, parameters -- is refused.
+ (mt/with-premium-features #{}
+ (doseq [db [nil
+ ""
+ " "
+ ":memory:"
+ " :memory:"
+ "file::memory:"
+ "file::memory:?cache=shared"
+ "file:/etc/x.db?mode=ro"
+ "file:/etc/x.db?mode=memory"
+ "file:/etc/x.db?vfs=memdb"
+ "file:x.db?mode=ro"
+ "file:/etc/x.db?"
+ ;; even where SQLite would read it as part of the dropped `#` fragment: any `?` is refused
+ "file:/etc/x.db#frag?mode=memory"
+ ":resource:file:/etc/x.db"
+ ":resource:http://example.com/x.db"
+ ":resource: file:/etc/x.db"
+ ":resource:url:file:/etc/x.db"
+ ":resource:jar:file:/etc/x.jar!/x.db"
+ ":RESOURCE:file:/etc/x.db"
+ "jar:file:/etc/x.jar!/x.db"
+ "http://example.com/x.db"
+ "https://example.com/x.db"
+ " https://example.com/x.db"
+ "ftp://example.com/x.db"
+ ;; SQLite's `file:` prefix is case-sensitive, so this would be a relative path named `FILE:`
+ "FILE:/etc/x.db"
+ ;; SQLite refuses any authority but an empty one or `localhost`
+ "file://example.com/etc/x.db"
+ ;; sqlite-jdbc strips its own settings from after a `?` in a plain path too, so the file it opens is not
+ ;; the one the path checks would normalize this to
+ "/etc/x.db?jdbc.explicit_readonly=../../allowed-dir/x.db"
+ "/etc/x.db?mode=memory"
+ "/etc/x.db?"
+ "x.db?foo=bar"
+ ;; refused even where it is part of the file name
+ "/allowed-dir/we?ird.db"]]
+ (testing (pr-str db)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite database must be a file path or a file: URI"
+ (driver/validate-db-details! :sqlite {:db db})))))
+ (testing "a Windows drive letter is a path, not a URL scheme"
+ (is (nil? (driver/validate-db-details! :sqlite {:db "C:\\data\\x.db"}))))))
+
+(deftest db-file-must-be-in-readable-paths-test
+ ;; the database file is a path on the Metabase host that an admin types in, so it has to be somewhere
+ ;; `readable-paths` allows -- in either form that names a file
+ (mt/with-premium-features #{}
+ (mt/with-temp-env-var-value! [mb-readable-paths "/allowed-dir"]
+ (testing "a file outside the allowed directories is refused"
+ (doseq [db ["/etc/x.db"
+ "/allowed-dir/../etc/x.db"
+ "file:/etc/x.db"
+ "file:///etc/x.db"
+ "file://localhost/etc/x.db"
+ ;; SQLite drops a URI's `#` fragment, `..` segments in it included
+ "file:/etc/x.db#/../../allowed-dir/x.db"
+ ;; a relative `file:` URI names a file relative to the working directory
+ "file:x.db"
+ ;; SQLite decodes each well-formed escape on its own, whatever else the path holds
+ "file:/allowed-dir/%zz/%2E%2E/%2E%2E/etc/x.db"
+ ;; and a decoded NUL ends the path
+ "file:/etc/x.db%00/../../allowed-dir/x.db"
+ ;; surrounding whitespace is part of a path, which then names a file relative to the working
+ ;; directory
+ " /allowed-dir/x.db"
+ " file:/etc/x.db"]]
+ (testing db
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Reading from path is disallowed"
+ (driver/validate-db-details! :sqlite {:db db}))))))
+ (testing "a file inside one is allowed"
+ (doseq [db ["/allowed-dir/x.db"
+ "file:/allowed-dir/x.db"
+ "file:/allowed-dir/x.db#frag"
+ "file://localhost/allowed-dir/x.db"
+ "file:/allowed-dir/100%25.db"
+ "file:/allowed-dir/50%.db"
+ "/allowed-dir/x.db "]]
+ (testing db
+ (is (nil? (driver/validate-db-details! :sqlite {:db db}))))))
+ (testing "the flag Metabase's own flows bind does not exempt an arbitrary file, such as a stored row's `:db`"
+ (binding [driver.settings/*allow-testing-sqlite-connections* true]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Reading from path is disallowed"
+ (driver/validate-db-details! :sqlite {:db "/etc/x.db"}))))))))
+
+(defn- do-with-temp-file!
+ "Call `f` with the path of a new empty temp file ending in `suffix`, and delete it afterwards, along with any journal
+ SQLite left beside it."
+ [suffix f]
+ (let [path (.getPath (java.io.File/createTempFile "sqlite-test" suffix))]
+ (try
+ (f path)
+ (finally
+ (doseq [file [path (str path "-journal") (str path "-wal") (str path "-shm")]]
+ (io/delete-file file true))))))
+
+(defn- do-with-temp-sqlite-file!
+ "Call `f` with the path of a new SQLite database file holding an empty table `t`, and delete it afterwards."
+ [f]
+ (do-with-temp-file!
+ ".sqlite"
+ (fn [path]
+ (jdbc/execute! {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname path} ["CREATE TABLE t (x INTEGER)"])
+ (f path))))
+
+(deftest can-connect-reads-only-the-checked-file-test
+ (testing "the connection check reads the header of the local file the path checks validated"
+ (mt/with-premium-features #{}
+ (do-with-temp-sqlite-file!
+ (fn [path]
+ (is (true? (driver/can-connect? :sqlite {:db path})))
+ (is (true? (driver/can-connect? :sqlite {:db (str "file:" path)})))
+ (testing "a file that is not a SQLite database fails the check"
+ (do-with-temp-file!
+ ".txt"
+ (fn [other]
+ (spit other "not a database")
+ (is (false? (driver/can-connect? :sqlite {:db other}))))))
+ (testing "an unsupported form is refused before anything is read"
+ (doseq [db [":memory:" (str "file:" path "?mode=memory")]]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite database must be a file path or a file: URI"
+ (driver/can-connect? :sqlite {:db db}))))))))))
+
+(defn- do-with-registered-sample-path!
+ "Call `f` with the path of a temp file registered as the bundled Sample Database, then restore the registered path
+ and delete the file."
+ [f]
+ (do-with-temp-file!
+ ".sqlite"
+ (fn [path]
+ (let [registered @#'driver.settings/sqlite-sample-database-path
+ original @registered]
+ (try
+ (driver.settings/register-sqlite-sample-database-path! path)
+ (f path)
+ (finally
+ (reset! registered original)))))))
+
+(deftest sample-database-exemption-test
+ (testing "the bundled Sample Database may sit outside the allowed paths, but only for the flows that bind the flag"
+ (do-with-registered-sample-path!
+ (fn [sample-path]
+ (mt/with-premium-features #{}
+ (mt/with-temp-env-var-value! [mb-readable-paths "NONE" mb-writable-paths "NONE"]
+ (binding [driver.settings/*allow-testing-sqlite-connections* true]
+ (is (nil? (driver/validate-db-details! :sqlite {:db sample-path :read-only? true})))
+ (testing "only for a read-only connection, as the Sample Database is opened"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Reading from path is disallowed"
+ (driver/validate-db-details! :sqlite {:db sample-path})))))
+ (testing "a user-facing endpoint does not bind it, so the path is checked like any other"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Reading from path is disallowed"
+ (driver/validate-db-details! :sqlite {:db sample-path}))))
+ (testing "and the flag alone exempts nothing else"
+ (binding [driver.settings/*allow-testing-sqlite-connections* true]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Reading from path is disallowed"
+ (driver/validate-db-details! :sqlite {:db "/etc/hosts"})))))))))))
+
+(deftest hosted-sqlite-path-guard-test
+ (testing "On a hosted instance, the SQLite driver only opens the registered Sample Database file. A
+ Database row carrying an attacker-chosen `:db` -- e.g. from a serialization import, which never tests the
+ connection -- must not be openable by sync, which binds *allow-testing-sqlite-connections* for every DB."
+ (do-with-registered-sample-path!
+ (fn [sample-path]
+ (mt/with-premium-features #{:hosting}
+ (testing "a non-sample path is refused"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite is not available"
+ (driver/validate-db-details! :sqlite {:db "/etc/hosts"}))))
+ (testing "the sync binding does not let can-connect? open a non-sample file"
+ (binding [driver.settings/*allow-testing-sqlite-connections* true]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite is not available"
+ (driver/can-connect? :sqlite {:db "/etc/hosts"})))))
+ (testing "the Sample Database is only reachable by the internal flows that bind the flag"
+ (binding [driver.settings/*allow-testing-sqlite-connections* true]
+ (is (nil? (driver/validate-db-details! :sqlite {:db sample-path :read-only? true}))))
+ (testing "so a user-facing endpoint, which does not bind it, cannot create a connection to it"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite is not available"
+ (driver/validate-db-details! :sqlite {:db sample-path :read-only? false}))))))))))
+
+(deftest db-file-must-be-in-writable-paths-test
+ ;; a connection that is not read-only can write the file (and its journal), so `writable-paths` applies as well
+ (mt/with-premium-features #{}
+ (mt/with-temp-env-var-value! [mb-writable-paths "/allowed-dir"]
+ (testing "a writable connection to a file outside the writable paths is refused"
+ (doseq [details [{:db "/etc/x.db"}
+ {:db "file:/etc/x.db"}
+ {:db "file:/etc/x.db" :read-only? false}]]
+ (testing (pr-str details)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Writing to path is disallowed"
+ (driver/validate-db-details! :sqlite details))))))
+ (testing "a read-only connection and a file inside the writable paths are allowed"
+ (doseq [details [{:db "/etc/x.db" :read-only? true}
+ {:db "file:/etc/x.db" :read-only? true}
+ {:db "/allowed-dir/x.db"}]]
+ (testing (pr-str details)
+ (is (nil? (driver/validate-db-details! :sqlite details))))))
+ (testing "the readable paths still apply to a read-only connection"
+ (mt/with-temp-env-var-value! [mb-readable-paths "/allowed-dir"]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Reading from path is disallowed"
+ (driver/validate-db-details! :sqlite {:db "/etc/x.db" :read-only? true}))))))))
+
+(defn- native-rows [database sql]
+ (mt/rows (qp/process-query {:database (u/the-id database), :type :native, :native {:query sql}})))
+
+(deftest stored-database-rows-are-checked-when-connecting-test
+ ;; A Database row can reach the app DB without a connection test, e.g. from a serialization import or from before
+ ;; the path settings were set, so opening a connection for one applies the same checks.
+ (do-with-temp-sqlite-file!
+ (fn [path]
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Database database {:engine :sqlite :details {:db path}}
+ :model/Database in-memory {:engine :sqlite :details {:db ":memory:"}}
+ :model/Database no-path {:engine :sqlite :details {}}]
+ (testing "a query opens a file the path settings allow"
+ (is (= [] (native-rows database "SELECT x FROM t"))))
+ (testing "a query is refused when the readable paths exclude the file"
+ (mt/with-temp-env-var-value! [mb-readable-paths "/allowed-dir"]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Reading from path is disallowed"
+ (native-rows database "SELECT x FROM t")))))
+ (testing "a query on a writable connection is refused when the writable paths exclude the file"
+ (mt/with-temp-env-var-value! [mb-writable-paths "/allowed-dir"]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Writing to path is disallowed"
+ (native-rows database "SELECT x FROM t")))))
+ (testing "a query on an unsupported form is refused"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite database must be a file path or a file: URI"
+ (native-rows in-memory "SELECT 1"))))
+ (testing "a query on a row whose path carries sqlite-jdbc settings after a `?` is refused"
+ (mt/with-temp [:model/Database with-settings {:engine :sqlite
+ :details {:db (str path "?jdbc.explicit_readonly=../x.db")}}]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite database must be a file path or a file: URI"
+ (native-rows with-settings "SELECT x FROM t")))))
+ (testing "a query on a row with no database path is refused"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite database must be a file path or a file: URI"
+ (native-rows no-path "SELECT 1"))))))
+ (testing "on a hosted instance, a query on any database but the Sample Database is refused"
+ (mt/with-premium-features #{:hosting}
+ (mt/with-temp [:model/Database database {:engine :sqlite :details {:db path}}]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite is not available as a data warehouse on Metabase Cloud"
+ (native-rows database "SELECT x FROM t")))))))))
+
+(deftest serialization-imported-database-is-checked-when-connecting-test
+ (testing "a SQLite database written by a serialization import cannot be queried outside the readable paths"
+ (do-with-temp-sqlite-file!
+ (fn [path]
+ (mt/with-premium-features #{}
+ (mt/with-temp-env-var-value! [mb-readable-paths "/allowed-dir"]
+ (let [database (serdes/load-one! {:serdes/meta [{:model "Database" :id "Imported SQLite"}]
+ :name "Imported SQLite"
+ :engine "sqlite"
+ :details {:db path}
+ :created_at "2026-01-01T00:00:00Z"
+ :updated_at "2026-01-01T00:00:00Z"}
+ nil)]
+ (try
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Reading from path is disallowed"
+ (native-rows database "SELECT x FROM t")))
+ (finally
+ (t2/delete! :model/Database :id (u/the-id database)))))))))))
+
+(deftest sample-database-queries-test
+ (testing "queries on the registered Sample Database open it wherever it sits, as Metabase extracts that file itself"
+ (do-with-registered-sample-path!
+ (fn [sample-path]
+ (jdbc/execute! {:classname "org.sqlite.JDBC" :subprotocol "sqlite" :subname sample-path}
+ ["CREATE TABLE IF NOT EXISTS t (x INTEGER)"])
+ (mt/with-temp-env-var-value! [mb-readable-paths "NONE" mb-writable-paths "NONE"]
+ (doseq [features [#{} #{:hosting}]]
+ (mt/with-premium-features features
+ (mt/with-temp [:model/Database database {:engine :sqlite :details {:db sample-path :read-only? true}}
+ :model/Database writable {:engine :sqlite :details {:db sample-path}}]
+ (testing (pr-str features)
+ (is (= [] (native-rows database "SELECT x FROM t")))
+ (testing "but not for a writable connection to the same file, e.g. from a serialization import"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Reading from path is disallowed|SQLite is not available as a data warehouse"
+ (native-rows writable "INSERT INTO t VALUES (1)")))))))))))))
+
(deftest default-schema-test
(mt/test-driver :sqlite
(is (nil? (driver.sql/default-schema :sqlite (mt/db))))))
@@ -328,49 +609,59 @@
#"SQL error or missing database \(no such table: fdw_test\.products\)"
(qp/process-query (mt/native-query {:query "SELECT count(*) FROM fdw_test.products;"})))))))))
-(defn- load-extension-refusal
- "The error SQLite gives when asked to load an extension that does not exist over a connection built from `details`:
- `not authorized` while extension loading is disabled, `no such file` once it tries to open the file."
+(defn- load-extension-refusal!
+ "The error SQLite gives when asked to load an extension that does not exist over a connection built from `details`
+ to a temp database file: `not authorized` while extension loading is disabled, `no such file` once it tries to open
+ the file."
[details]
- (let [spec (sql-jdbc.conn/connection-details->spec :sqlite (merge {:db ":memory:"} details))]
- (try
- (jdbc/query spec ["SELECT load_extension('/nonexistent/metabase-test-extension')"])
- ::loaded
- (catch Exception e
- (re-find #"not authorized|no such file" (ex-message e))))))
-
-(deftest ^:parallel extension-loading-is-always-disabled-test
- (testing "loading an extension runs native code in the Metabase process, so it is disabled whatever the details say"
- ;; detail keys reach the client as connection properties, and it also reads settings from the database path
- (doseq [details [{}
- {:enable_load_extension true}
- {:enable_load_extension "true"}
- {:db ":memory:?enable_load_extension=true"}
- {:db "file::memory:?ENABLE_LOAD_EXTENSION=true"}
- ;; a namespaced or differently-cased key names the same connection property once it reaches the
- ;; client, and the JSON decoder keeps such keys
- {:foo/enable_load_extension "true"}
- {:ENABLE_LOAD_EXTENSION "true"}
- {:foo/Enable_Load_Extension true}]]
- (testing (pr-str details)
- (is (= "not authorized" (load-extension-refusal details)))))))
+ (do-with-temp-sqlite-file!
+ (fn [path]
+ (let [spec (sql-jdbc.conn/connection-details->spec :sqlite (merge {:db path} details))]
+ (try
+ (jdbc/query spec ["SELECT load_extension('/nonexistent/metabase-test-extension')"])
+ ::loaded
+ (catch Exception e
+ (re-find #"not authorized|no such file" (ex-message e))))))))
+
+(deftest extension-loading-is-always-disabled-test
+ (mt/with-premium-features #{}
+ (testing "loading an extension runs native code in the Metabase process, so it is disabled whatever the details say"
+ ;; detail keys reach the client as connection properties
+ (doseq [details [{}
+ {:enable_load_extension true}
+ {:enable_load_extension "true"}
+ ;; a namespaced or differently-cased key names the same connection property once it reaches the
+ ;; client, and the JSON decoder keeps such keys
+ {:foo/enable_load_extension "true"}
+ {:ENABLE_LOAD_EXTENSION "true"}
+ {:foo/Enable_Load_Extension true}]]
+ (testing (pr-str details)
+ (is (= "not authorized" (load-extension-refusal! details)))))
+ (testing "the client also reads settings from a database path's query, so such a path is refused outright"
+ (doseq [db ["file:/tmp/x.db?enable_load_extension=true"
+ "file::memory:?ENABLE_LOAD_EXTENSION=true"
+ ":memory:?enable_load_extension=true"]]
+ (testing db
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"SQLite database must be a file path or a file: URI"
+ (sql-jdbc.conn/connection-details->spec :sqlite {:db db})))))))))
(deftest protected-connection-properties-cannot-be-overridden-test
- (testing "properties the driver sets for safety survive a namespaced or differently-cased detail key"
- (doseq [[k v] [[:foo/limit_attached "10"]
- [:LIMIT_ATTACHED "10"]
- [:foo/enable_load_extension "true"]]]
- (let [spec (sql-jdbc.conn/connection-details->spec :sqlite {:db ":memory:" k v})]
- (testing (pr-str k)
- (is (= 0 (:limit_attached spec)))
- (is (= "false" (:enable_load_extension spec)))
- (is (= [] (->> (keys spec)
- (filter #(re-find #"(?i)limit_attached|enable_load_extension" (name %)))
- (remove #{:limit_attached :enable_load_extension})))))))
- (testing "a read-only database cannot be made writable the same way"
- (let [spec (sql-jdbc.conn/connection-details->spec :sqlite {:db ":memory:" :read-only? true :foo/open_mode "6"})]
- (is (not-any? #(= "foo" (namespace %)) (keys spec)))
- (is (= (:open_mode spec) (:open_mode (sql-jdbc.conn/connection-details->spec :sqlite {:db ":memory:" :read-only? true}))))))))
+ (mt/with-premium-features #{}
+ (testing "properties the driver sets for safety survive a namespaced or differently-cased detail key"
+ (doseq [[k v] [[:foo/limit_attached "10"]
+ [:LIMIT_ATTACHED "10"]
+ [:foo/enable_load_extension "true"]]]
+ (let [spec (sql-jdbc.conn/connection-details->spec :sqlite {:db "/tmp/x.db" k v})]
+ (testing (pr-str k)
+ (is (= 0 (:limit_attached spec)))
+ (is (= "false" (:enable_load_extension spec)))
+ (is (= [] (->> (keys spec)
+ (filter #(re-find #"(?i)limit_attached|enable_load_extension" (name %)))
+ (remove #{:limit_attached :enable_load_extension})))))))
+ (testing "a read-only database cannot be made writable the same way"
+ (let [spec (sql-jdbc.conn/connection-details->spec :sqlite {:db "/tmp/x.db" :read-only? true :foo/open_mode "6"})]
+ (is (not-any? #(= "foo" (namespace %)) (keys spec)))
+ (is (= (:open_mode spec) (:open_mode (sql-jdbc.conn/connection-details->spec :sqlite {:db "/tmp/x.db" :read-only? true})))))))))
(deftest resource-urls-are-subject-to-the-network-policy-test
;; `:resource:<url>` has the client fetch the database file from that URL