Skip to content

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

32.0 KB
Raw Blame
(ns ^:mb/driver-tests metabase-enterprise.database-routing.e2e-test
  {:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query     {:namespaces [metabase-enterprise.database-routing.e2e-test]}
                                                            metabase.test.data/run-mbql-query {:namespaces [metabase-enterprise.database-routing.e2e-test]}
                                                            metabase.test.data/query          {:namespaces [metabase-enterprise.database-routing.e2e-test]}}}}}}
  (:require
   [clojure.java.jdbc :as jdbc]
   [clojure.set :as set]
   [clojure.string :as str]
   [clojure.test :refer [deftest is testing]]
   [clojurewerkz.quartzite.conversion :as qc]
   [metabase-enterprise.database-routing.common :as common]
   [metabase-enterprise.test :as met]
   [metabase.app-db.core :as mdb]
   [metabase.config.core :as config]
   [metabase.driver :as driver]
   [metabase.driver.settings :as driver.settings]
   [metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
   [metabase.driver.util :as driver.u]
   [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]
   [metabase.test :as mt]
   [metabase.test.data :as data]
   [metabase.test.data.interface :as tx]
   [metabase.test.data.one-off-dbs :as one-off-dbs]
   [metabase.util :as u]
   [toucan2.core :as t2]))

(defmacro with-temp-dbs!
  "Creates databases like `mt/with-temp`, but creating an actual underlying H2 database with a single table,
  `my_database_name`, with a single column, `str`."
  [bindings & body]
  (letfn [(wrap [names body]
            (if (empty? names)
              `(do ~@body)
              `(one-off-dbs/with-blank-db
                 (let [~(first names) (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#]))
                   ~(wrap (rest names) body)))))]
    (wrap bindings body)))

(defn execute-statement! [db statement]
  (sql-jdbc.execute/do-with-connection-with-options
   :h2
   (mdb/spec :h2 (:details db))
   {:write? true}
   (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! (:id ~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]
      (met/with-user-attributes!
        :crowberto
        {"db_name" "__METABASE_ROUTER__"}
        (met/with-user-attributes!
          :rasta
          {"db_name" "destination-db-1"}
          (met/with-user-attributes!
            :lucky
            {"db_name" "destination-db-2"}
            (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"}
                             :model/Card card {:name          "Some Name"
                                               :dataset_query {:database (u/the-id router-db)
                                                               :type     :query
                                                               :query    {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}}}]
                (execute-statement! router-db "INSERT INTO \"my_database_name\" (str) VALUES ('router')")
                (execute-statement! destination-db-1 "INSERT INTO \"my_database_name\" (str) VALUES ('destination-1')")
                (execute-statement! destination-db-2 "INSERT INTO \"my_database_name\" (str) VALUES ('destination-2')")
                (let [response (mt/user-http-request :rasta :post 202 (str "card/" (u/the-id card) "/query"))]
                  (is (= [["destination-1"]] (mt/rows response))))
                (let [response (mt/user-http-request :lucky :post 202 (str "card/" (u/the-id card) "/query"))]
                  (is (= [["destination-2"]] (mt/rows response))))
                (let [response (mt/user-http-request :crowberto :post 202 (str "card/" (u/the-id card) "/query"))]
                  (is (= [["router"]] (mt/rows response))))))))))))

;; The reported exploit, verbatim: POST /api/dataset with a destination's id and a native query.
;; Before the fix this returned the destination's rows (a cross-tenant leak); it must be rejected,
;; in production too. Exercises the real HTTP surface, above the QP-level test below.
(deftest direct-destination-query-via-dataset-endpoint-is-forbidden-test
  (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-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')")
            (let [exploit {:database (u/the-id destination-db)
                           :type     :native
                           :native   {:query "SELECT str FROM \"my_database_name\""}}]
              (doseq [prod? [false true]]
                (testing (str "config/is-prod? = " prod?)
                  (with-redefs [config/is-prod? prod?]
                    ;; :crowberto is a superuser -> permissions never block; the routing guard must.
                    (let [response (mt/user-http-request :crowberto :post 403 "dataset" exploit)]
                      (is (re-find #"(?i)cannot query a destination database directly" (str response)))
                      (is (not (str/includes? (str response) "tenant-b-secret"))
                          "the destination's rows must not appear in the response"))))))))))))

;; Must hold in production too, where the dev-only connection-pool harness is disabled; a query-level
;; guard, not the harness and not permissions, has to reject a directly-submitted destination id.
(deftest direct-destination-database-access-is-forbidden-test
  (testing "a directly-submitted destination id is rejected"
    (mt/with-premium-features #{:database-routing}
      (binding [driver.settings/*allow-testing-h2-connections* true]
        (met/with-user-attributes! :rasta {"db_name" "destination-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')")
              (let [table-id      (t2/select-one-pk :model/Table :db_id (u/the-id router-db))
                    ;; native (the reported exploit) and MBQL. MBQL exercises the setup-layer check:
                    ;; the destination has no synced tables, so without an early reject the query would
                    ;; die later with a confusing "table not found" instead of a clean 403.
                    direct-queries {:native {:database (u/the-id destination-db)
                                             :type     :native
                                             :native   {:query "SELECT str FROM \"my_database_name\""}}
                                    :mbql   {:database (u/the-id destination-db)
                                             :type     :query
                                             :query    {:source-table table-id}}}]
                (doseq [prod?           [false true]
                        [qtype a-query] direct-queries]
                  (testing (str "config/is-prod? = " prod? ", query type = " qtype)
                    (with-redefs [config/is-prod? prod?]
                      ;; :crowberto is a superuser -> resolves to most-permissive perms on every database,
                      ;; so the permission layer never blocks; the routing invariant must.
                      (mt/with-test-user :crowberto
                        (is (thrown-with-msg?
                             clojure.lang.ExceptionInfo
                             #"(?i)cannot query a destination database directly"
                             (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.
(deftest check-allowed-access-blocks-destinations-in-prod-test
  (testing "connection-pool backstop rejects direct destination access"
    (mt/with-premium-features #{:database-routing}
      (binding [driver.settings/*allow-testing-h2-connections* true]
        (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! (driver.u/lib-database dest-id)))))
            (testing "the router database itself is not treated as a forbidden destination"
              (is (nil? (common/check-allowed-access! (driver.u/lib-database router-id)))))))))))

(deftest an-error-is-thrown-if-user-attribute-is-missing-or-no-match
  (mt/with-premium-features #{:database-routing}
    (binding [driver.settings/*allow-testing-h2-connections* true]
      (met/with-user-attributes!
        :crowberto
        {"db_name" "nonexistent_database_name"}
        (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"
              (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Anonymous users cannot access a database with routing enabled."
                                    (qp/process-query {:database (u/the-id router-db)
                                                       :type :query
                                                       :query {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}}))))
            (testing "No destination database matches"
              (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Database Routing error: No Destination Database with slug `nonexistent_database_name` found."
                                    (mt/with-test-user :crowberto
                                      (qp/process-query {:database (u/the-id router-db)
                                                         :type :query
                                                         :query {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}})))))
            (testing "User attribute is missing"
              (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Required user attribute is missing. Cannot route to a Destination Database."
                                    (mt/with-test-user :rasta
                                      (qp/process-query {:database (u/the-id router-db)
                                                         :type :query
                                                         :query {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}})))))))))))

(deftest caching-works
  (mt/with-premium-features #{:database-routing}
    (binding [driver.settings/*allow-testing-h2-connections* true]
      (met/with-user-attributes!
        :crowberto
        {"db_name" "__METABASE_ROUTER__"}
        (met/with-user-attributes!
          :rasta
          {"db_name" "destination database"}
          (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)
                                                    :user_attribute "db_name"}]
              (mt/with-test-user :crowberto
                (is (= [["router"]]
                       (-> (qp/process-query {:database (u/the-id router-db)
                                              :type :query
                                              :query {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}
                                              :cache-strategy {:type             :ttl
                                                               :multiplier       60
                                                               :avg-execution-ms 1000
                                                               :min_duration_ms  1}})
                           :data
                           :rows))))
              (mt/with-test-user :crowberto
                (is (=? {:cache/details {:cached true}
                         :data {:rows [["router"]]}}
                        (qp/process-query {:database (u/the-id router-db)
                                           :type :query
                                           :query {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}
                                           :cache-strategy {:type             :ttl
                                                            :multiplier       60
                                                            :avg-execution-ms 1000
                                                            :min_duration_ms  1}}))))
              (mt/with-test-user :rasta
                (is (=? {:data {:rows [["destination"]]}}
                        (qp/process-query {:database (u/the-id router-db)
                                           :type :query
                                           :query {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}
                                           :cache-strategy {:type             :ttl
                                                            :multiplier       60
                                                            :avg-execution-ms 1000
                                                            :min_duration_ms  1}})))
                (is (=? {:cache/details {:cached true}
                         :data {:rows [["destination"]]}}
                        (qp/process-query {:database (u/the-id router-db)
                                           :type :query
                                           :query {:source-table (t2/select-one-pk :model/Table :db_id (u/the-id router-db))}
                                           :cache-strategy {:type             :ttl
                                                            :multiplier       60
                                                            :avg-execution-ms 1000
                                                            :min_duration_ms  1}})))))))))))

(deftest get-field-values-endpoint-works
  (mt/with-premium-features #{:database-routing}
    (binding [driver.settings/*allow-testing-h2-connections* true]
      (met/with-user-attributes!
        :crowberto
        {"db_name" "__METABASE_ROUTER__"}
        (met/with-user-attributes!
          :rasta
          {"db_name" "destination-db-1"}
          (met/with-user-attributes!
            :lucky
            {"db_name" "destination-db-2"}
            (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"}]
                (let [table-id (t2/select-one-pk :model/Table :db_id (u/the-id router-db))
                      field-id (t2/select-one-pk :model/Field :table_id table-id)]
                  (execute-statement! router-db "INSERT INTO \"my_database_name\" (str) VALUES ('router')")
                  (execute-statement! destination-db-1 "INSERT INTO \"my_database_name\" (str) VALUES ('destination-1')")
                  (execute-statement! destination-db-2 "INSERT INTO \"my_database_name\" (str) VALUES ('destination-2')")
                  (let [response (mt/user-http-request :rasta :get 200 (str "field/" field-id "/values"))]
                    (is (= {:values [["destination-1"]], :field_id field-id, :has_more_values false}
                           response)))
                  (let [response (mt/user-http-request :crowberto :get 200 (str "field/" field-id "/values"))]
                    (is (= {:values [["router"]] :field_id field-id :has_more_values false}
                           response)))
                  (let [response (mt/user-http-request :lucky :get 200 (str "field/" field-id "/values"))]
                    (is (= {:values [["destination-2"]] :field_id field-id :has_more_values false}
                           response)))
                  (testing "a routed user gets no values while database routing is unavailable"
                    (mt/with-premium-features #{}
                      (is (= [] (:values (mt/user-http-request :rasta :get 200
                                                               (str "field/" field-id "/values"))))))))))))))))

(defmulti router-dataset-name
  "Name for router dataset"
  {:arglists '([driver])}
  tx/dispatch-on-driver-with-test-extensions
  :hierarchy #'driver/hierarchy)

(defmethod router-dataset-name :default [_driver] "db-router-data")

(doseq [driver [:redshift :databricks :presto-jdbc :bigquery-cloud-sdk :oracle]]
  (defmethod router-dataset-name driver [_driver] "db-routing-data"))

(defmulti routed-dataset-name
  "Name for routed dataset"
  {:arglists '([driver])}
  tx/dispatch-on-driver-with-test-extensions
  :hierarchy #'driver/hierarchy)

(defmethod routed-dataset-name :default [_driver] "db-routed-data")

(doseq [driver [:redshift :databricks :presto-jdbc :bigquery-cloud-sdk :oracle]]
  (defmethod routed-dataset-name driver [_driver] "db-routing-data"))

(defmulti router-dataset-details
  "Modified details for the router dataset"
  {:arglists '([driver])}
  tx/dispatch-on-driver-with-test-extensions
  :hierarchy #'driver/hierarchy)

(defmethod router-dataset-details :default [_driver] {})

(defmethod router-dataset-details :clickhouse [_driver]
  {:dbname "db_router_data"
   :enable-multiple-db false})

(defmethod router-dataset-details :databricks [driver]
  {:multi-level-schema false
   :schema-filters-patterns (router-dataset-name driver)})

(defmulti routed-dataset-details
  "Modified details for the routed dataset"
  {:arglists '([driver])}
  tx/dispatch-on-driver-with-test-extensions
  :hierarchy #'driver/hierarchy)

(defmethod routed-dataset-details :default [_driver] {})

(defmethod routed-dataset-details :clickhouse [_driver]
  {:dbname "db_routed_data"
   :enable-multiple-db false})

(defmethod routed-dataset-details :bigquery-cloud-sdk [driver]
  {:service-account-json (tx/db-test-env-var-or-throw driver :service-account-json-routing)})

(defmethod routed-dataset-details :redshift [driver]
  {:db (tx/db-test-env-var-or-throw driver :db-routing)})

(defmethod routed-dataset-details :databricks [driver]
  {:catalog (tx/db-test-env-var-or-throw driver :catalog-routing)
   :multi-level-schema false
   :schema-filters-patterns (routed-dataset-name driver)})

;; the test requires both datasets share a hash (for the name qualifier)
;; this is because the qp when routing a db does not map to the routed table (it reuses metadata of original)
;; the end result is the compiled query would retain the routed sha_* qualifier rather than the hash of the original.
;; using :hash-key now forces the hash key used to sha to be shared between the two datasets.

(defn- router-dataset [driver]
  (let [dataset (mt/dataset-definition (router-dataset-name driver)
                                       [["t"
                                         [{:field-name "f", :base-type :type/Text}]
                                         [["original-foo"]
                                          ["original-bar"]]]])]
    (assoc dataset :hash-key dataset)))

(defn- routed-dataset [driver]
  (let [router (router-dataset driver)
        dataset (mt/dataset-definition (routed-dataset-name driver)
                                       [["t"
                                         [{:field-name "f", :base-type :type/Text}]
                                         [["routed-foo"]
                                          ["routed-bar"]]]])]
    (assoc dataset :hash-key (:hash-key router))))

(deftest db-routing-e2e-test
  (mt/test-drivers (mt/normal-driver-select {:+features [:database-routing]})
    (mt/with-premium-features #{:database-routing}
      ;; 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 :id (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! (:id 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}
      ;; 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 :id (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! (:id 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]))))))))))))))