Skip to content

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

Consistency pass over database routing invariants (#78066)

Timothy S. Dean3df32386973f
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 3f21d9e4066..2bb588e578f 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -736,6 +736,7 @@
clojurewerkz.quartzite.schedule.simple/schedule macros.quartz/simple-schedule
clojurewerkz.quartzite.triggers/build macros.quartz/build-trigger
metabase-enterprise.database-routing.e2e-test/with-temp-dbs! macros.metabase-enterprise.database-routing.e2e-test/with-temp-dbs!
+ metabase-enterprise.database-routing.e2e-test/with-routing-setup! macros.metabase-enterprise.database-routing.e2e-test/with-routing-setup!
metabase-enterprise.impersonation.util-test/with-impersonations! macros.metabase-enterprise.impersonation.util-test/with-impersonations!
metabase-enterprise.query-reference-validation.api-test/with-test-setup! macros.metabase-enterprise.query-reference-validation.api-test/with-test-setup!
metabase-enterprise.sandbox.test-util/with-gtaps! macros.metabase-enterprise.sandbox.test-util/with-gtaps!
diff --git a/.clj-kondo/macros/metabase_enterprise/database_routing/e2e_test.clj b/.clj-kondo/macros/metabase_enterprise/database_routing/e2e_test.clj
index 970dcc06a07..41e2ff8d633 100644
--- a/.clj-kondo/macros/metabase_enterprise/database_routing/e2e_test.clj
+++ b/.clj-kondo/macros/metabase_enterprise/database_routing/e2e_test.clj
@@ -3,3 +3,8 @@
(defmacro with-temp-dbs! [bindings & body]
`(let [~@(interleave bindings (repeat nil))]
~@body))
+
+(defmacro with-routing-setup! [[router-binding destinations] & body]
+ `(let [~router-binding nil
+ ~@(interleave (map first destinations) (repeat nil))]
+ ~@body))
diff --git a/enterprise/backend/test/metabase_enterprise/data_complexity_score/complexity_test.clj b/enterprise/backend/test/metabase_enterprise/data_complexity_score/complexity_test.clj
index 49a04a174c4..c8c8037f824 100644
--- a/enterprise/backend/test/metabase_enterprise/data_complexity_score/complexity_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_complexity_score/complexity_test.clj
@@ -326,10 +326,17 @@
:model/Table {hidden :id} {:db_id plain-db :name "hidden_table"
:active true :visibility_type "hidden"}
:model/Table {technical :id} {:db_id plain-db :name "technical_table"
- :active true :visibility_type "technical"}
- :model/Table {routed :id} {:db_id routed-db :name "routed_table"
- :active true :visibility_type nil}]
- (let [metabot-entities (:metabot (#'complexity/enumerate-catalogs nil))
+ :active true :visibility_type "technical"}]
+ ;; A table can't exist on a routed (destination) db in production (destinations aren't synced),
+ ;; so a normal `with-temp :model/Table` trips the destination-permission guard. Insert it
+ ;; directly to fabricate the routed table this exclusion test needs.
+ (let [routed (t2/insert-returning-pk! (t2/table-name :model/Table)
+ {:db_id routed-db
+ :name "routed_table"
+ :active true
+ :created_at :%now
+ :updated_at :%now})
+ metabot-entities (:metabot (#'complexity/enumerate-catalogs nil))
ids (into #{} (comp (filter #(= :table (:kind %))) (map :id)) metabot-entities)]
(testing "visible non-routed table is included"
(is (contains? ids visible)))
diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/e2e_test.clj
index 35c8a3e0da0..83448d20c08 100644
--- a/enterprise/backend/test/metabase_enterprise/database_routing/e2e_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/database_routing/e2e_test.clj
@@ -16,6 +16,7 @@
[metabase.driver :as driver]
[metabase.driver.settings :as driver.settings]
[metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
+ [metabase.permissions.models.permissions-group :as perms-group]
[metabase.query-processor.test :as qp]
[metabase.sync.core :as sync]
[metabase.sync.task.sync-databases :as task.sync-databases]
@@ -51,6 +52,47 @@
(fn [^java.sql.Connection conn]
(jdbc/execute! {:connection conn} [statement]))))
+(defmacro with-routing-setup!
+ "Stands up a router + destination databases for a routing test.
+
+ - `router-binding` → a synced `:model/Database` (real H2, `my_database_name` table). Owns the
+ metadata; queries compile against it.
+ - Each destination → a `[binding name]` pair. `binding` → a `:model/Database` with its own real H2 DB,
+ inserted with `:router_database_id` set, not synced.
+ - inserted, not flipped: `router_database_id` is immutable after insert.
+ - not synced: routing runs the router-compiled SQL against the destination's connection.
+ - `name` must equal the user's routing attribute: destinations resolve by name.
+ - Caller wires the `:model/DatabaseRouter` and attributes. Each destination binding is a usable DB map.
+
+ (with-routing-setup! [router-db [[dest-1 \"destination-db-1\"]
+ [dest-2 \"destination-db-2\"]]]
+ ...)"
+ {:style/indent 1}
+ [[router-binding destinations] & body]
+ (letfn [(wrap-destinations [dests body]
+ (if (empty? dests)
+ `(do ~@body)
+ (let [[sym name] (first dests)]
+ ;; Real H2 DB for this destination, via `with-blank-db`. Discard the normal DB row it
+ ;; registers; the destination is a separate row, inserted prod-shaped below.
+ `(one-off-dbs/with-blank-db
+ (let [details# (:details (data/db))]
+ (doseq [statement# ["CREATE USER IF NOT EXISTS GUEST PASSWORD 'guest';"
+ "SET DB_CLOSE_DELAY -1;"
+ "CREATE TABLE \"my_database_name\" (str TEXT NOT NULL);"
+ "GRANT ALL ON \"my_database_name\" TO GUEST;"]]
+ (jdbc/execute! one-off-dbs/*conn* [statement#]))
+ (mt/with-temp [:model/Database ~sym
+ {:engine :h2
+ :name ~name
+ :details details#
+ :router_database_id (u/the-id ~router-binding)}]
+ ~(wrap-destinations (rest dests) body)))))))]
+ ;; Router: a normal synced DB, exactly as `with-temp-dbs!` builds one.
+ `(with-temp-dbs! [~router-binding]
+ (sync/sync-database! ~router-binding)
+ ~(wrap-destinations destinations body))))
+
(deftest destination-databases-get-used
(mt/with-premium-features #{:database-routing}
(binding [driver.settings/*allow-testing-h2-connections* true]
@@ -63,12 +105,8 @@
(met/with-user-attributes!
:lucky
{"db_name" "destination-db-2"}
- (with-temp-dbs! [router-db destination-db-1 destination-db-2]
- ;; configure the destination Databases
- (t2/update! :model/Database (u/the-id destination-db-1) {:name "destination-db-1" :router_database_id (u/the-id router-db)})
- (t2/update! :model/Database (u/the-id destination-db-2) {:name "destination-db-2" :router_database_id (u/the-id router-db)})
- ;; sync the Router database
- (sync/sync-database! router-db)
+ (with-routing-setup! [router-db [[destination-db-1 "destination-db-1"]
+ [destination-db-2 "destination-db-2"]]]
;; Configure the router database and set up a card that uses it.
(mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
:user_attribute "db_name"}
@@ -93,10 +131,7 @@
(testing "POST /api/dataset at a destination id is rejected, not leaked"
(mt/with-premium-features #{:database-routing}
(binding [driver.settings/*allow-testing-h2-connections* true]
- (with-temp-dbs! [router-db destination-db]
- (t2/update! :model/Database (u/the-id destination-db)
- {:name "destination-db" :router_database_id (u/the-id router-db)})
- (sync/sync-database! router-db)
+ (with-routing-setup! [router-db [[destination-db "destination-db"]]]
(mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
:user_attribute "db_name"}]
(execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('tenant-b-secret')")
@@ -119,12 +154,7 @@
(mt/with-premium-features #{:database-routing}
(binding [driver.settings/*allow-testing-h2-connections* true]
(met/with-user-attributes! :rasta {"db_name" "destination-db"}
- (with-temp-dbs! [router-db destination-db]
- ;; wiring an already-created (perm-carrying) DB as a destination mirrors the vulnerable
- ;; state: the destination retains permissions, so perms alone do not block access.
- (t2/update! :model/Database (u/the-id destination-db)
- {:name "destination-db" :router_database_id (u/the-id router-db)})
- (sync/sync-database! router-db)
+ (with-routing-setup! [router-db [[destination-db "destination-db"]]]
(mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
:user_attribute "db_name"}]
(execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('secret')")
@@ -148,7 +178,25 @@
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"(?i)cannot query a destination database directly"
- (qp/process-query a-query)))))))))))))))
+ (qp/process-query a-query)))))))
+ (testing "the guard rejects a non-superuser whose permission check would otherwise pass"
+ ;; Grant the destination perms via a raw insert that bypasses the model hook.
+ ;; Normally impossible: destinations never carry data_permissions rows.
+ ;; Proves a non-superuser's perms don't matter — only the routing guard rejects the query.
+ (t2/query {:insert-into :data_permissions
+ :values [{:group_id (:id (perms-group/all-users))
+ :perm_type "perms/view-data"
+ :perm_value "unrestricted"
+ :db_id (u/the-id destination-db)}
+ {:group_id (:id (perms-group/all-users))
+ :perm_type "perms/create-queries"
+ :perm_value "query-builder-and-native"
+ :db_id (u/the-id destination-db)}]})
+ (mt/with-test-user :rasta
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"(?i)cannot query a destination database directly"
+ (qp/process-query (:native direct-queries))))))))))))))
;; The connection-pool guard is the backstop for non-query paths (sync, actions, downloads); it must
;; fire in production too, so exercise it directly rather than through the query pipeline.
@@ -156,22 +204,19 @@
(testing "connection-pool backstop rejects direct destination access"
(mt/with-premium-features #{:database-routing}
(binding [driver.settings/*allow-testing-h2-connections* true]
- (with-temp-dbs! [router-db destination-db]
- (t2/update! :model/Database (u/the-id destination-db)
- {:name "destination-db" :router_database_id (u/the-id router-db)})
- (mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
- :user_attribute "db_name"}]
- (with-redefs [config/is-prod? true]
- (testing "direct destination access is forbidden"
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"(?i)cannot query a destination database directly"
- (common/check-allowed-access! (u/the-id destination-db)))))
- (testing "destination access is allowed inside a routing-on context (legit routed query)"
- (is (nil? (database-routing/with-database-routing-on
- (common/check-allowed-access! (u/the-id destination-db))))))
- (testing "the router database itself is not treated as a forbidden destination"
- (is (nil? (common/check-allowed-access! (u/the-id router-db))))))))))))
+ (mt/with-temp [:model/Database {router-id :id} {}
+ :model/Database {dest-id :id} {:router_database_id router-id}]
+ (with-redefs [config/is-prod? true]
+ (testing "direct destination access is forbidden"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"(?i)cannot query a destination database directly"
+ (common/check-allowed-access! dest-id))))
+ (testing "destination access is allowed inside a routing-on context (legit routed query)"
+ (is (nil? (database-routing/with-database-routing-on
+ (common/check-allowed-access! dest-id)))))
+ (testing "the router database itself is not treated as a forbidden destination"
+ (is (nil? (common/check-allowed-access! router-id))))))))))
(deftest an-error-is-thrown-if-user-attribute-is-missing-or-no-match
(mt/with-premium-features #{:database-routing}
@@ -179,9 +224,7 @@
(met/with-user-attributes!
:crowberto
{"db_name" "nonexistent_database_name"}
- (with-temp-dbs! [router-db destination-db]
- (t2/update! :model/Database (u/the-id destination-db) {:name "my database name" :router_database_id (u/the-id router-db)})
- (sync/sync-database! router-db)
+ (with-routing-setup! [router-db [[_destination-db "my database name"]]]
(mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
:user_attribute "db_name"}]
(testing "Anonymous access is prohibited"
@@ -211,9 +254,7 @@
(met/with-user-attributes!
:rasta
{"db_name" "destination database"}
- (with-temp-dbs! [router-db destination-db]
- (t2/update! :model/Database (u/the-id destination-db) {:name "destination database" :router_database_id (u/the-id router-db)})
- (sync/sync-database! router-db)
+ (with-routing-setup! [router-db [[destination-db "destination database"]]]
(execute-statement! router-db "INSERT INTO \"my_database_name\" (str) VALUES ('router')")
(execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('destination')")
(mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
@@ -270,12 +311,8 @@
(met/with-user-attributes!
:lucky
{"db_name" "destination-db-2"}
- (with-temp-dbs! [router-db destination-db-1 destination-db-2]
- ;; configure the destination Databases
- (t2/update! :model/Database (u/the-id destination-db-1) {:name "destination-db-1" :router_database_id (u/the-id router-db)})
- (t2/update! :model/Database (u/the-id destination-db-2) {:name "destination-db-2" :router_database_id (u/the-id router-db)})
- ;; sync the Router database
- (sync/sync-database! router-db)
+ (with-routing-setup! [router-db [[destination-db-1 "destination-db-1"]
+ [destination-db-2 "destination-db-2"]]]
;; Configure the router database and set up a card that uses it.
(mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
:user_attribute "db_name"}]
@@ -294,13 +331,6 @@
(is (= {:values [["destination-2"]] :field_id field-id :has_more_values false}
response))))))))))))
-(defn- wire-routing [{:keys [parent children]}]
- (t2/update! :model/Database :id [:in (map :id children)]
- {:router_database_id (:id parent)})
- (doseq [child children]
- (t2/update! :model/Database :id (:id child)
- {:details (assoc (:details child) :destination-database true)})))
-
(defmulti router-dataset-name
"Name for router dataset"
{:arglists '([driver])}
@@ -391,93 +421,102 @@
(deftest db-routing-e2e-test
(mt/test-drivers (mt/normal-driver-select {:+features [:database-routing]})
(mt/with-premium-features #{:database-routing}
- (binding [tx/*use-routing-details* true]
- (mt/dataset (routed-dataset driver/*driver*)
- (let [routed (mt/db)]
- (binding [tx/*use-routing-details* false]
- (mt/dataset (router-dataset driver/*driver*)
- (let [router (mt/db)]
- (t2/update! :model/Database (u/the-id routed)
- {:details (merge (:details routed)
- (routed-dataset-details driver/*driver*))})
- (t2/update! :model/Database (u/the-id router)
- {:details (merge (:details router)
- (router-dataset-details driver/*driver*))})
- (let [router (t2/select-one :model/Database :id (u/the-id router))
- routed (t2/select-one :model/Database :id (u/the-id routed))]
- (sync/sync-database! router {:scan :schema})
- (sync/sync-database! routed {:scan :schema})
- (wire-routing {:parent router :children [routed]})
- (mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router)
- :user_attribute "db_name"}]
- (met/with-user-attributes! :rasta {"db_name" (:name routed)}
- (mt/with-current-user (mt/user->id :crowberto)
- (is (= [[1 "original-foo"] [2 "original-bar"]]
- (->> (mt/query t)
- (mt/process-query)
- (mt/formatted-rows [int str])))))
- (mt/with-current-user (mt/user->id :rasta)
- (is (= [[1 "routed-foo"] [2 "routed-bar"]]
- (->> (mt/query t)
- (mt/process-query)
- (mt/formatted-rows [int str]))))))
- (testing "sync task can see database"
- (let [job-data (reify qc/JobDataMapConversion
- ;; i'm doing this at the "job-data" level so it's as close to what runs in
- ;; the task itself without actually hitting scheduler stuff.
- (from-job-data [_] {"db-id" (u/the-id router)})
- (to-job-data [_]))
- results (#'task.sync-databases/sync-and-analyze-database! job-data)
- step-with-name (fn [step-name]
- (->> results :metadata-results :steps
- (some (fn [step] (when (= step-name (first step)) (second step))))))]
- (is (set/subset? #{"sync-fields" "sync-tables"}
- (->> results :metadata-results :steps (map first) set)))
- ;; this is usually 1 total tables, but some cloud dbs put multiple databases inside of a
- ;; single catalog
- (is (=? {:updated-tables 0 :total-tables pos-int?}
- (step-with-name "sync-tables"))))))))))))))))
+ ;; Router: a normal synced DB that owns the Table/Field rows (matches prod + the H2 `with-routing-setup!`).
+ (mt/dataset (router-dataset driver/*driver*)
+ (let [router (mt/db)]
+ (t2/update! :model/Database (u/the-id router)
+ {:details (merge (:details router)
+ (router-dataset-details driver/*driver*))})
+ (let [router (t2/select-one :model/Database :id (u/the-id router))]
+ (sync/sync-database! router {:scan :schema})
+ ;; Load the physical routed warehouse only for its connection-details + name; discard the normal
+ ;; `:model/Database` row `mt/dataset` registers. The destination is inserted prod-shaped below.
+ (let [[routed-name routed-details]
+ (binding [tx/*use-routing-details* true]
+ (mt/dataset (routed-dataset driver/*driver*)
+ (let [routed (mt/db)]
+ [(:name routed)
+ (merge (:details routed)
+ (routed-dataset-details driver/*driver*))])))]
+ ;; Not synced — routing compiles against the router's metadata, not the destination's.
+ (mt/with-temp [:model/Database _routed {:engine driver/*driver*
+ :name routed-name
+ :details routed-details
+ :router_database_id (u/the-id router)}
+ :model/DatabaseRouter _ {:database_id (u/the-id router)
+ :user_attribute "db_name"}]
+ (met/with-user-attributes! :rasta {"db_name" routed-name}
+ (mt/with-current-user (mt/user->id :crowberto)
+ (is (= [[1 "original-foo"] [2 "original-bar"]]
+ (->> (mt/query t)
+ (mt/process-query)
+ (mt/formatted-rows [int str])))))
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (= [[1 "routed-foo"] [2 "routed-bar"]]
+ (->> (mt/query t)
+ (mt/process-query)
+ (mt/formatted-rows [int str]))))))
+ (testing "sync task can see database"
+ (let [job-data (reify qc/JobDataMapConversion
+ ;; i'm doing this at the "job-data" level so it's as close to what runs in
+ ;; the task itself without actually hitting scheduler stuff.
+ (from-job-data [_] {"db-id" (u/the-id router)})
+ (to-job-data [_]))
+ results (#'task.sync-databases/sync-and-analyze-database! job-data)
+ step-with-name (fn [step-name]
+ (->> results :metadata-results :steps
+ (some (fn [step] (when (= step-name (first step)) (second step))))))]
+ (is (set/subset? #{"sync-fields" "sync-tables"}
+ (->> results :metadata-results :steps (map first) set)))
+ ;; this is usually 1 total tables, but some cloud dbs put multiple databases inside of a
+ ;; single catalog
+ (is (=? {:updated-tables 0 :total-tables pos-int?}
+ (step-with-name "sync-tables")))))))))))))
(deftest athena-region-bucket-routing-test
(mt/test-driver :athena
(mt/with-premium-features #{:database-routing}
- (binding [tx/*use-routing-details* true]
- (mt/dataset (mt/dataset-definition "db-routing-data"
- [["t_0"
- [{:field-name "f", :base-type :type/Text}]
- [["us-east-2-foo"]
- ["us-east-2-bar"]]]])
- (let [routed (mt/db)]
- (binding [tx/*use-routing-details* false]
- (mt/dataset (mt/dataset-definition "db-routing-data"
- [["t_0"
- [{:field-name "f", :base-type :type/Text}]
- [["us-east-1-foo"]
- ["us-east-1-bar"]]]])
- (let [router (mt/db)]
- (t2/update! :model/Database (u/the-id routed)
- {:details (assoc (:details routed)
- :dbname nil
- :s3_staging_dir (tx/db-test-env-var-or-throw :athena :s3-staging-dir-routing)
- :region (tx/db-test-env-var-or-throw :athena :region-routing))})
- (t2/update! :model/Database (u/the-id router)
- {:details (assoc (:details router)
- :dbname nil)})
- (let [router (t2/select-one :model/Database :id (u/the-id router))
- routed (t2/select-one :model/Database :id (u/the-id routed))]
- (sync/sync-database! router {:scan :schema})
- (sync/sync-database! routed {:scan :schema})
- (wire-routing {:parent router :children [routed]})
- (mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router)
- :user_attribute "db_name"}]
- (met/with-user-attributes! :rasta {"db_name" (:name routed)}
- (mt/with-current-user (mt/user->id :crowberto)
- (is (= [[1 "us-east-1-foo"] [2 "us-east-1-bar"]]
- (->> (mt/query t_0)
- (mt/process-query)
- (mt/formatted-rows [int str])))))
- (mt/with-current-user (mt/user->id :rasta)
- (is (= [[1 "us-east-2-foo"] [2 "us-east-2-bar"]]
- (->> (mt/query t_0)
- (mt/process-query)
- (mt/formatted-rows [int str])))))))))))))))))
+ ;; Router: a normal synced DB that owns the Table/Field rows (matches prod + the H2 `with-routing-setup!`).
+ (mt/dataset (mt/dataset-definition "db-routing-data"
+ [["t_0"
+ [{:field-name "f", :base-type :type/Text}]
+ [["us-east-1-foo"]
+ ["us-east-1-bar"]]]])
+ (let [router (mt/db)]
+ (t2/update! :model/Database (u/the-id router)
+ {:details (assoc (:details router) :dbname nil)})
+ (let [router (t2/select-one :model/Database :id (u/the-id router))]
+ (sync/sync-database! router {:scan :schema})
+ ;; Load the physical routed warehouse only for its connection-details + name; discard the normal
+ ;; `:model/Database` row `mt/dataset` registers. The destination is inserted prod-shaped below.
+ (let [[routed-name routed-details]
+ (binding [tx/*use-routing-details* true]
+ (mt/dataset (mt/dataset-definition "db-routing-data"
+ [["t_0"
+ [{:field-name "f", :base-type :type/Text}]
+ [["us-east-2-foo"]
+ ["us-east-2-bar"]]]])
+ (let [routed (mt/db)]
+ [(:name routed)
+ (assoc (:details routed)
+ :dbname nil
+ :s3_staging_dir (tx/db-test-env-var-or-throw :athena :s3-staging-dir-routing)
+ :region (tx/db-test-env-var-or-throw :athena :region-routing))])))]
+ ;; Not synced — routing compiles against the router's metadata, not the destination's.
+ (mt/with-temp [:model/Database _routed {:engine :athena
+ :name routed-name
+ :details routed-details
+ :router_database_id (u/the-id router)}
+ :model/DatabaseRouter _ {:database_id (u/the-id router)
+ :user_attribute "db_name"}]
+ (met/with-user-attributes! :rasta {"db_name" routed-name}
+ (mt/with-current-user (mt/user->id :crowberto)
+ (is (= [[1 "us-east-1-foo"] [2 "us-east-1-bar"]]
+ (->> (mt/query t_0)
+ (mt/process-query)
+ (mt/formatted-rows [int str])))))
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (= [[1 "us-east-2-foo"] [2 "us-east-2-bar"]]
+ (->> (mt/query t_0)
+ (mt/process-query)
+ (mt/formatted-rows [int str]))))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/embedding_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/embedding_test.clj
index 992ed638999..b358bfe0046 100644
--- a/enterprise/backend/test/metabase_enterprise/database_routing/embedding_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/database_routing/embedding_test.clj
@@ -3,9 +3,8 @@
(:require
[buddy.sign.jwt :as jwt]
[clojure.test :refer [deftest is testing]]
- [metabase-enterprise.database-routing.e2e-test :refer [with-temp-dbs! execute-statement!]]
+ [metabase-enterprise.database-routing.e2e-test :refer [execute-statement! with-routing-setup!]]
[metabase.driver.settings :as driver.settings]
- [metabase.sync.core :as sync]
[metabase.test :as mt]
[metabase.test.http-client :as client]
[metabase.util :as u]
@@ -41,11 +40,7 @@
(testing "Guest embedding should work with database routing by bypassing routing"
(mt/with-premium-features #{:database-routing}
(binding [driver.settings/*allow-testing-h2-connections* true]
- (with-temp-dbs! [router-db destination-db]
- ;; Set up router and destination database
- (t2/update! :model/Database (u/the-id destination-db) {:name "destination-db" :router_database_id (u/the-id router-db)})
- ;; Sync the router database to ensure tables are available
- (sync/sync-database! router-db)
+ (with-routing-setup! [router-db [[destination-db "destination-db"]]]
;; Set up database routing configuration
(mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
:user_attribute "db_name"}
diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/query_execution_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/query_execution_test.clj
index 1ae8f5b6726..365c5465dce 100644
--- a/enterprise/backend/test/metabase_enterprise/database_routing/query_execution_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/database_routing/query_execution_test.clj
@@ -10,7 +10,6 @@
[metabase.driver.settings :as driver.settings]
[metabase.query-processor :as qp]
[metabase.query-processor.util :as qp.util]
- [metabase.sync.core :as sync]
[metabase.test :as mt]
[metabase.util :as u]
[toucan2.core :as t2]))
@@ -23,10 +22,7 @@
(binding [driver.settings/*allow-testing-h2-connections* true
qp.util/*execute-async?* false]
(met/with-user-attributes! :rasta {"db_name" "destination-db"}
- (e2e/with-temp-dbs! [router-db destination-db]
- (t2/update! :model/Database (u/the-id destination-db)
- {:name "destination-db" :router_database_id (u/the-id router-db)})
- (sync/sync-database! router-db)
+ (e2e/with-routing-setup! [router-db [[destination-db "destination-db"]]]
(mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
:user_attribute "db_name"}]
(e2e/execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('hi')")
diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/sandboxing_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/sandboxing_test.clj
index 79c6cbbb998..3f8b956a52b 100644
--- a/enterprise/backend/test/metabase_enterprise/database_routing/sandboxing_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/database_routing/sandboxing_test.clj
@@ -9,7 +9,6 @@
[metabase.lib.metadata :as lib.metadata]
[metabase.permissions.core :as perms]
[metabase.permissions.models.data-permissions :as data-perms]
- [metabase.sync.core :as sync]
[metabase.test :as mt]
[metabase.util :as u]
[toucan2.core :as t2]))
@@ -19,10 +18,7 @@
(mt/with-premium-features #{:database-routing :sandboxes :advanced-permissions}
(binding [driver.settings/*allow-testing-h2-connections* true]
(met/with-user-attributes! :rasta {"db_name" "destination-db" "filter_val" "keep"}
- (e2e/with-temp-dbs! [router-db destination-db]
- (t2/update! :model/Database (u/the-id destination-db)
- {:name "destination-db" :router_database_id (u/the-id router-db)})
- (sync/sync-database! router-db)
+ (e2e/with-routing-setup! [router-db [[destination-db "destination-db"]]]
(e2e/execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('keep')")
(e2e/execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('drop')")
(e2e/execute-statement! router-db "INSERT INTO \"my_database_name\" (str) VALUES ('router-only')")
diff --git a/resources/migrations/063/20260717_delete_destination_db_permissions.yaml b/resources/migrations/063/20260717_delete_destination_db_permissions.yaml
new file mode 100644
index 00000000000..ac3db4556dd
--- /dev/null
+++ b/resources/migrations/063/20260717_delete_destination_db_permissions.yaml
@@ -0,0 +1,15 @@
+## Destination databases (those with a non-null router_database_id) must never carry permissions of
+## their own — their permissions are resolved through the router. Delete any data_permissions rows
+## left pointing at a destination db.
+
+databaseChangeLog:
+ - changeSet:
+ id: v63.destperm-cleanup
+ author: galdre
+ comment: Delete data_permissions rows for destination databases (they must never carry permissions).
+ changes:
+ - sql:
+ sql: >-
+ DELETE FROM data_permissions
+ WHERE db_id IN (SELECT id FROM metabase_database WHERE router_database_id IS NOT NULL)
+ rollback: # nothing to restore; a cleanup DELETE of invalid rows is intentionally irreversible
diff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.clj
index f12fff8a150..4c9764759ee 100644
--- a/src/metabase/permissions/models/data_permissions.clj
+++ b/src/metabase/permissions/models/data_permissions.clj
@@ -5,6 +5,7 @@
[medley.core :as m]
[metabase.api.common :as api]
[metabase.app-db.cluster-lock :as cluster-lock]
+ [metabase.app-db.core :as mdb]
[metabase.audit-app.core :as audit]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.models.interface :as mi]
@@ -668,9 +669,26 @@
(throw (ex-info (str/join (mu/explain ::permissions.schema/data-permission-type perm_type)) permission)))
(assert-value-matches-perm-type perm_type perm_value))
+;; Memoized per application DB. Destination status is immutable after creation, so the cache can't go stale.
+(def ^:private destination-db-id?
+ "Whether `db-id` is a destination database — one with `router_database_id` set."
+ (mdb/memoize-for-application-db
+ (fn [db-id]
+ (t2/exists? :model/Database :id db-id :router_database_id [:not= nil]))))
+
+(defn assert-no-destination-db-permissions!
+ "Throws if any row in `perm-rows` targets a destination database — one with `router_database_id`
+ set. Destinations are reachable only through their router and must never carry `data_permissions`
+ rows."
+ [perm-rows]
+ (when-let [dest-ids (seq (into #{} (comp (keep :db_id) (filter destination-db-id?)) perm-rows))]
+ (throw (ex-info (tru "Cannot grant permissions on a destination database.")
+ {:status-code 400 :destination-db-ids dest-ids}))))
+
(t2/define-before-insert :model/DataPermissions
[permission]
(assert-valid-permission permission)
+ (assert-no-destination-db-permissions! [permission])
permission)
(t2/define-before-update :model/DataPermissions
@@ -728,6 +746,9 @@
hitting database limits for the number of parameters in a prepared statement. This is only really applicable when a DB
has more than ~10k tables and we're transitioning from database-level permissions to table-level permissions."
[new-perms]
+ ;; The before-insert hook already runs this per row, so this call is dormant. Un-comment it if perms
+ ;; are ever inserted by a path that bypasses the hook (e.g. t2/query).
+ #_(assert-no-destination-db-permissions! new-perms)
(doseq [batched-new-perms (partition-all permission-batch-size new-perms)]
(t2/insert! :model/DataPermissions batched-new-perms)))
diff --git a/src/metabase/warehouses/models/database.clj b/src/metabase/warehouses/models/database.clj
index f587b8a790c..2c8d2170cae 100644
--- a/src/metabase/warehouses/models/database.clj
+++ b/src/metabase/warehouses/models/database.clj
@@ -23,7 +23,7 @@
[metabase.sync.schedules :as sync.schedules]
[metabase.util :as u]
[metabase.util.honey-sql-2 :as h2x]
- [metabase.util.i18n :refer [trs]]
+ [metabase.util.i18n :refer [trs tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.quick-task :as quick-task]
@@ -71,16 +71,23 @@
;; cause duplication rather than good matching if the two instances are later linked by serdes.
#_(derive :hook/entity-id))
+(defn is-destination?
+ "Is this database a destination database for some router database?"
+ [db]
+ (boolean (:router_database_id db)))
+
(methodical/defmethod t2.with-temp/do-with-temp* :before :model/Database
[_model _explicit-attributes f]
(fn [temp-object]
- ;; Grant All Users full perms on the temp-object so that tests don't have to manually set permissions
- (perms/set-database-permission! (perms/all-users-group) temp-object :perms/view-data :unrestricted)
- (perms/set-database-permission! (perms/all-users-group) temp-object :perms/create-queries :query-builder-and-native)
- (perms/set-database-permission! (perms/all-users-group) temp-object :perms/download-results :one-million-rows)
- (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/view-data :blocked)
- (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/create-queries :no)
- (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/download-results :no)
+ ;; Grant All Users full perms so tests don't have to set permissions — but skip destination
+ ;; databases, which must never carry data_permissions rows (they are reached only via routing).
+ (when-not (is-destination? temp-object)
+ (perms/set-database-permission! (perms/all-users-group) temp-object :perms/view-data :unrestricted)
+ (perms/set-database-permission! (perms/all-users-group) temp-object :perms/create-queries :query-builder-and-native)
+ (perms/set-database-permission! (perms/all-users-group) temp-object :perms/download-results :one-million-rows)
+ (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/view-data :blocked)
+ (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/create-queries :no)
+ (perms/set-database-permission! (perms/all-external-users-group) temp-object :perms/download-results :no))
(f temp-object)))
(defn- should-read-audit-db?
@@ -220,11 +227,6 @@
:else (throw (ex-info "Illegal options combination."
(select-keys database [:let-user-control-scheduling :is_full_sync :is_on_demand]))))))
-(defn is-destination?
- "Is this database a destination database for some router database?"
- [db]
- (boolean (:router_database_id db)))
-
(defn should-sync?
"Should this database be synced at all? Destination (router-child) databases are never synced.
This is the gate for *explicit*, user-requested syncs (e.g. the Sync-now button), which run
@@ -475,8 +477,17 @@
(t2/update! :model/Database :uploads_enabled true {:uploads_enabled false :uploads_table_prefix nil :uploads_schema_name nil}))
db)
+(defn- assert-router-database-id-not-mutated!
+ "Throws if `database`'s pending update changes `router_database_id`. A destination's link to its
+ router is set at creation and is immutable thereafter."
+ [database]
+ (when (contains? (t2/changes database) :router_database_id)
+ (throw (ex-info (tru "Cannot change router_database_id; a destination database is established at creation, not by updating an existing database.")
+ {:status-code 400}))))
+
(t2/define-before-update :model/Database
[database]
+ (assert-router-database-id-not-mutated! database)
;; Note: the "sample database may not be edited" policy is enforced at the API layer
;; ([[metabase.warehouses-rest.api]] PUT /:id), so internally-derived updates - e.g. the sample
;; database engine migration in [[metabase.sample-data.impl]] - can change the engine here.
diff --git a/test/metabase/actions/settings_test.clj b/test/metabase/actions/settings_test.clj
index 1b7dc7daaf2..91f18da3844 100644
--- a/test/metabase/actions/settings_test.clj
+++ b/test/metabase/actions/settings_test.clj
@@ -3,7 +3,8 @@
[clojure.test :refer :all]
[metabase.driver.util :as driver.u]
[metabase.settings.core :as setting]
- [metabase.test :as mt]))
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
(defn- extract-disabled-reasons*
"Extract disabled reasons from enabled-for-db? call. If no reasons, rethrow the exception."
@@ -32,8 +33,17 @@
(testing "returns database routing reason for destination databases"
(mt/with-temp [:model/Database router-db {:initial_sync_status "complete"}
:model/Database target-db {:initial_sync_status "complete", :router_database_id (:id router-db)}
- :model/Table _ {:db_id (:id router-db) :is_writable true}
- :model/Table _ {:db_id (:id target-db) :is_writable true}]
+ :model/Table _ {:db_id (:id router-db) :is_writable true}]
+ ;; Give the destination a writable table so routing is its only disabled reason (not
+ ;; `no-writable-tables`). A destination can't have tables in production, so a normal
+ ;; `with-temp :model/Table` trips the destination-permission guard — insert it directly.
+ (t2/insert-returning-pk! (t2/table-name :model/Table)
+ {:db_id (:id target-db)
+ :name "destination-table"
+ :is_writable true
+ :active true
+ :created_at :%now
+ :updated_at :%now})
(is (= [:setting/database-routing]
(disabled-reasons router-db)))
(is (= [:setting/database-routing]
diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.clj
index 025a5181fc6..1dae814dd77 100644
--- a/test/metabase/app_db/schema_migrations_test.clj
+++ b/test/metabase/app_db/schema_migrations_test.clj
@@ -3247,6 +3247,40 @@
(testing "invalid JSON task_details is skipped by JSON_VALID, run stays null (GDGT-2680)"
(is (nil? (nid invalid))))))))))))
+(deftest delete-destination-db-permissions-test
+ (testing "v63.destperm-cleanup: data_permissions rows for destination dbs (router_database_id set) are deleted; rows for normal dbs remain"
+ (impl/test-migrations ["v63.destperm-cleanup" "v63.destperm-cleanup"] [migrate!]
+ (let [new-db! (fn [name & {:as extra}]
+ (t2/insert-returning-pk! :metabase_database
+ (merge {:name name
+ :engine "postgres"
+ :created_at :%now
+ :updated_at :%now
+ :details "{}"}
+ extra)))
+ group-id (t2/insert-returning-pk! :permissions_group {:name "Destperm Test Group"})
+ router-id (new-db! "Router DB")
+ dest-id (new-db! "Destination DB" :router_database_id router-id)
+ normal-id (new-db! "Normal DB")
+ new-perm! (fn [db-id]
+ (t2/insert-returning-pk! :data_permissions
+ {:group_id group-id
+ :perm_type "perms/view-data"
+ :db_id db-id
+ :perm_value "unrestricted"}))
+ dest-perm (new-perm! dest-id)
+ normal-perm (new-perm! normal-id)]
+ (testing "seeded rows exist before the migration"
+ (is (some? (t2/select-one-fn :id :data_permissions :id dest-perm)))
+ (is (some? (t2/select-one-fn :id :data_permissions :id normal-perm))))
+ (migrate!)
+ (testing "destination db permissions are deleted"
+ (is (nil? (t2/select-one-fn :id :data_permissions :id dest-perm)))
+ (is (zero? (t2/count :data_permissions :db_id dest-id))))
+ (testing "normal db permissions are untouched"
+ (is (some? (t2/select-one-fn :id :data_permissions :id normal-perm)))
+ (is (= 1 (t2/count :data_permissions :db_id normal-id))))))))
+
(deftest move-metabot-conversation-state-to-messages-test
(testing "v64.2026-07-06: the legacy conversation state blob moves to the earliest live assistant message, then the column drops"
(impl/test-migrations ["v64.2026-07-06T00:00:01" "v64.2026-07-06T00:00:02"] [migrate!]
diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.clj
index 407c4ab51af..f894157343c 100644
--- a/test/metabase/metabot/tools/resources_test.clj
+++ b/test/metabase/metabot/tools/resources_test.clj
@@ -848,38 +848,46 @@
(deftest read-destination-backed-entities-return-errors-test
(testing "destination-backed entity resources cannot expose destination database metadata"
(mt/with-current-user (mt/user->id :crowberto)
- (mt/with-temp [:model/Database {router-id :id} {}
- :model/Database {destination-id :id} {:router_database_id router-id}
- :model/Table {table-id :id} {:db_id destination-id :active true}
- :model/Card {model-id :id} {:type :model :database_id destination-id}
- :model/Card {question-id :id} {:type :question :database_id destination-id}
- :model/Card {metric-id :id} {:type :metric :database_id destination-id}
- :model/Measure {measure-id :id} {:table_id table-id}
- :model/Segment {segment-id :id} {:table_id table-id}]
- (with-redefs [mi/can-read? (constantly true)]
- (doseq [uri [(str "metabase://table/" table-id)
- (str "metabase://table/" table-id "/fields")
- (str "metabase://table/" table-id "/fields/42")
- (str "metabase://table/" table-id "/derived")
- (str "metabase://model/" model-id)
- (str "metabase://model/" model-id "/fields")
- (str "metabase://model/" model-id "/fields/42")
- (str "metabase://model/" model-id "/sources")
- (str "metabase://question/" question-id)
- (str "metabase://question/" question-id "/fields")
- (str "metabase://question/" question-id "/fields/42")
- (str "metabase://question/" question-id "/sources")
- (str "metabase://metric/" metric-id)
- (str "metabase://metric/" metric-id "/dimensions")
- (str "metabase://metric/" metric-id "/dimensions/42")
- (str "metabase://measure/" measure-id)
- (str "metabase://segment/" segment-id)]]
- (testing uri
- ;; Match the guard's 404 message exactly: a plain `error?` check can't tell the
- ;; destination-database guard from unrelated failures like "Field 42 not found".
- (is (= "Not found."
- (-> (read-resource/read-resource {:uris [uri]}) :resources first :error))
- "destination-backed entity resource must 404 via the destination-database guard"))))))))
+ (mt/with-temp [:model/Database {router-id :id} {}
+ :model/Database {destination-id :id} {:router_database_id router-id}]
+ ;; A table can't exist on a destination in production (destinations aren't synced), so a normal
+ ;; `with-temp :model/Table` trips the destination-permission guard. Insert it directly to work
+ ;; around that guard and confirm the metabot guard rejects it anyway. (Cascades away with the db.)
+ (let [table-id (t2/insert-returning-pk! (t2/table-name :model/Table)
+ {:db_id destination-id
+ :name "destination-table"
+ :active true
+ :created_at :%now
+ :updated_at :%now})]
+ (mt/with-temp [:model/Card {model-id :id} {:type :model :database_id destination-id}
+ :model/Card {question-id :id} {:type :question :database_id destination-id}
+ :model/Card {metric-id :id} {:type :metric :database_id destination-id}
+ :model/Measure {measure-id :id} {:table_id table-id}
+ :model/Segment {segment-id :id} {:table_id table-id}]
+ (with-redefs [mi/can-read? (constantly true)]
+ (doseq [uri [(str "metabase://table/" table-id)
+ (str "metabase://table/" table-id "/fields")
+ (str "metabase://table/" table-id "/fields/42")
+ (str "metabase://table/" table-id "/derived")
+ (str "metabase://model/" model-id)
+ (str "metabase://model/" model-id "/fields")
+ (str "metabase://model/" model-id "/fields/42")
+ (str "metabase://model/" model-id "/sources")
+ (str "metabase://question/" question-id)
+ (str "metabase://question/" question-id "/fields")
+ (str "metabase://question/" question-id "/fields/42")
+ (str "metabase://question/" question-id "/sources")
+ (str "metabase://metric/" metric-id)
+ (str "metabase://metric/" metric-id "/dimensions")
+ (str "metabase://metric/" metric-id "/dimensions/42")
+ (str "metabase://measure/" measure-id)
+ (str "metabase://segment/" segment-id)]]
+ (testing uri
+ ;; Match the guard's 404 message exactly: a plain `error?` check can't tell the
+ ;; destination-database guard from unrelated failures like "Field 42 not found".
+ (is (= "Not found."
+ (-> (read-resource/read-resource {:uris [uri]}) :resources first :error))
+ "destination-backed entity resource must 404 via the destination-database guard"))))))))))
(deftest read-database-models-test
(mt/with-current-user (mt/user->id :crowberto)
diff --git a/test/metabase/permissions/models/data_permissions_test.clj b/test/metabase/permissions/models/data_permissions_test.clj
index 4e9bb4b83ac..759a45c5718 100644
--- a/test/metabase/permissions/models/data_permissions_test.clj
+++ b/test/metabase/permissions/models/data_permissions_test.clj
@@ -33,6 +33,78 @@
(is (not (data-perms/at-least-as-permissive? :perms/view-data :blocked :legacy-no-self-service)))
(is (data-perms/at-least-as-permissive? :perms/view-data :blocked :blocked))))
+(deftest destination-db-permissions-insert-throws-test
+ (testing "inserting a DataPermissions row for a destination database throws"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}
+ :model/Database {router-db-id :id} {}
+ :model/Database {destination-db-id :id} {:router_database_id router-db-id}]
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"destination database"
+ (t2/insert! :model/DataPermissions {:db_id destination-db-id
+ :group_id group-id
+ :perm_type :perms/view-data
+ :perm_value :unrestricted}))))))
+
+(deftest destination-db-permissions-batch-insert-throws-test
+ (testing "batch-insert-permissions! throws for a destination database row"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}
+ :model/Database {router-db-id :id} {}
+ :model/Database {destination-db-id :id} {:router_database_id router-db-id}]
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"destination database"
+ (data-perms/batch-insert-permissions!
+ [{:db_id destination-db-id
+ :group_id group-id
+ :perm_type :perms/view-data
+ :perm_value :unrestricted}]))))))
+
+(deftest assert-no-destination-db-permissions!-test
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}
+ :model/Database {normal-db-id :id} {}
+ :model/Database {router-db-id :id} {}
+ :model/Database {destination-db-id :id} {:router_database_id router-db-id}]
+ (let [dest-row {:db_id destination-db-id :group_id group-id
+ :perm_type :perms/view-data :perm_value :unrestricted}
+ normal-row {:db_id normal-db-id :group_id group-id
+ :perm_type :perms/view-data :perm_value :unrestricted}]
+ (testing "a single destination-db row throws"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"destination database"
+ (data-perms/assert-no-destination-db-permissions! [dest-row]))))
+ (testing "a batch mixing a destination-db row with normal-db rows throws"
+ (is (thrown-with-msg?
+ ExceptionInfo
+ #"destination database"
+ (data-perms/assert-no-destination-db-permissions! [normal-row dest-row]))))
+ (testing "an all-normal-db batch does not throw"
+ (is (nil? (data-perms/assert-no-destination-db-permissions! [normal-row normal-row]))))
+ (testing "an empty seq does not throw"
+ (is (nil? (data-perms/assert-no-destination-db-permissions! [])))))))
+
+(deftest destination-db-permissions-positive-control-test
+ (testing "inserting a perm row for a normal (non-destination) db still succeeds"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}
+ :model/Database {normal-db-id :id} {}]
+ (mt/with-restored-data-perms-for-group! group-id
+ (testing "via raw t2/insert!"
+ (is (t2/insert! :model/DataPermissions {:db_id normal-db-id
+ :group_id group-id
+ :perm_type :perms/view-data
+ :perm_value :unrestricted})))
+ (testing "via batch-insert-permissions!"
+ (t2/delete! :model/DataPermissions :db_id normal-db-id :group_id group-id)
+ (is (nil? (data-perms/batch-insert-permissions!
+ [{:db_id normal-db-id
+ :group_id group-id
+ :perm_type :perms/view-data
+ :perm_value :unrestricted}])))
+ (is (t2/exists? :model/DataPermissions
+ :db_id normal-db-id :group_id group-id
+ :perm_type :perms/view-data)))))))
+
(deftest set-database-permission!-test
(mt/with-temp [:model/PermissionsGroup {group-id :id} {}
:model/Database {database-id :id} {}]
diff --git a/test/metabase/permissions/test_util.clj b/test/metabase/permissions/test_util.clj
index 6e80bf19727..bf714d29518 100644
--- a/test/metabase/permissions/test_util.clj
+++ b/test/metabase/permissions/test_util.clj
@@ -52,13 +52,15 @@
;; TODO -- should this disabled the cache [[data-perms/*use-perms-cache?*]] ??
(thunk)
(finally
- (let [existing-db-ids (t2/select-pks-set :model/Database)
- existing-table-ids (t2/select-pks-set :model/Table)
- still-valid-perms (filter
- (fn [p] (and (contains? existing-db-ids (:db_id p))
- (or (nil? (:table_id p))
- (contains? existing-table-ids (:table_id p)))))
- original-perms)]
+ (let [existing-db-ids (t2/select-pks-set :model/Database)
+ existing-table-ids (t2/select-pks-set :model/Table)
+ destination-db-ids (t2/select-pks-set :model/Database :router_database_id [:not= nil])
+ still-valid-perms (filter
+ (fn [p] (and (contains? existing-db-ids (:db_id p))
+ (not (contains? destination-db-ids (:db_id p)))
+ (or (nil? (:table_id p))
+ (contains? existing-table-ids (:table_id p)))))
+ original-perms)]
(t2/delete! :model/DataPermissions {:where select-condition})
(t2/insert! :model/DataPermissions still-valid-perms))))))
@@ -84,8 +86,9 @@
;; force creation of test-data if it is not already created
(data/db)
(with-restored-data-perms-for-group! (u/the-id (perms-group/all-users))
+ ;; Skip destination databases: they must never carry data_permissions rows (reached only via routing).
(doseq [[perm-type _] permissions.schema/data-permissions
- db-id (t2/select-pks-set :model/Database)]
+ db-id (t2/select-pks-set :model/Database :router_database_id nil)]
(data-perms/set-database-permission! (perms-group/all-users)
db-id
perm-type
@@ -105,8 +108,9 @@
;; make sure app DB is set up and test users are created
(initialize/initialize-if-needed! :db :test-users)
(with-restored-data-perms-for-group! (u/the-id (perms-group/all-users))
+ ;; Skip destination databases: they must never carry data_permissions rows (reached only via routing).
(doseq [[perm-type _] permissions.schema/data-permissions
- db-id (t2/select-pks-set :model/Database)]
+ db-id (t2/select-pks-set :model/Database :router_database_id nil)]
(data-perms/set-database-permission! (perms-group/all-users)
db-id
perm-type
diff --git a/test/metabase/warehouse_schema_rest/api/table_test.clj b/test/metabase/warehouse_schema_rest/api/table_test.clj
index a60d61d9d7b..1a399364fa1 100644
--- a/test/metabase/warehouse_schema_rest/api/table_test.clj
+++ b/test/metabase/warehouse_schema_rest/api/table_test.clj
@@ -1305,10 +1305,19 @@
(mt/with-temp [:model/Database {source-db-id :id} {:engine "h2", :details (:details (mt/db))}
:model/Database {mirror-db-id :id} {:engine "h2"
:details (:details (mt/db))
- :router_database_id source-db-id}
- :model/Table table {:db_id mirror-db-id :schema "PUBLIC"}]
- (is (= "Not found."
- (mt/user-http-request :crowberto :post 404 (format "table/%d/sync_schema" (u/the-id table)))))))))
+ :router_database_id source-db-id}]
+ ;; A table can't exist on a mirror (destination) db in production (destinations aren't synced),
+ ;; so a normal `with-temp :model/Table` trips the destination-permission guard. Insert it
+ ;; directly to fabricate the mirror-db table this 404 test needs.
+ (let [table-id (t2/insert-returning-pk! (t2/table-name :model/Table)
+ {:db_id mirror-db-id
+ :schema "PUBLIC"
+ :name "mirror_table"
+ :active true
+ :created_at :%now
+ :updated_at :%now})]
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :post 404 (format "table/%d/sync_schema" table-id)))))))))
(deftest ^:parallel sync-schema-nonexistent-table-test
(testing "POST /api/table/:id/sync_schema"
diff --git a/test/metabase/warehouses/models/database_test.clj b/test/metabase/warehouses/models/database_test.clj
index f1893bc8d9d..6760ea4ab47 100644
--- a/test/metabase/warehouses/models/database_test.clj
+++ b/test/metabase/warehouses/models/database_test.clj
@@ -1052,3 +1052,16 @@
(data-perms/set-database-permission! pg db-id :perms/manage-database :yes)
(mt/with-test-user :rasta
(is (false? (mi/can-query? :model/Database db-id)))))))
+
+(deftest router-database-id-is-immutable-test
+ (testing "updating a database's router_database_id throws"
+ (mt/with-temp [:model/Database {router-id :id} {}
+ :model/Database {normal-id :id} {}]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"router_database_id"
+ (t2/update! :model/Database normal-id {:router_database_id router-id})))))
+ (testing "a no-op update that does not touch router_database_id is allowed (destination can still be edited)"
+ (mt/with-temp [:model/Database {router-id :id} {}
+ :model/Database {dest-id :id} {:router_database_id router-id}]
+ (is (t2/update! :model/Database dest-id {:name "renamed-destination"})))))