Skip to content

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

16.3 KB
Raw Blame
(ns metabase-enterprise.sandbox.api.permissions-test
  {:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase-enterprise.sandbox.api.permissions-test]}}}}}}
  (:require
   [clojure.string :as str]
   [clojure.test :refer :all]
   [metabase-enterprise.test :as met]
   [metabase.model-persistence.models.persisted-info :as persisted-info]
   [metabase.permissions-rest.data-permissions.graph :as data-perms.graph]
   [metabase.permissions.core :as perms]
   [metabase.permissions.models.permissions-group :as perms-group]
   [metabase.query-processor.compile :as qp.compile]
   [metabase.test :as mt]
   [metabase.util :as u]
   [metabase.util.json :as json]
   [metabase.util.malli.schema :as ms]
   [toucan2.core :as t2]))

(defn- db-graph-keypath [group]
  [:groups (u/the-id group) (mt/id) :view-data])

(defn- venues-perms-graph-keypath [group]
  (concat
   (db-graph-keypath group)
   [:PUBLIC (mt/id :venues)]))

(deftest revoke-perms-delete-gtaps-test
  (testing "PUT /api/permissions/graph"
    (testing "removing sandboxed permissions for a group should delete the associated GTAP (#16190)"
      (doseq [[message {:keys [updated-db-perms expected-perms]}]
              {"when changing permissions for DB to unrestricted access"
               {:updated-db-perms (constantly :unrestricted)
                :expected-perms   (constantly "unrestricted")}

               "when changing permissions for schema to unrestricted access"
               {:updated-db-perms (constantly {:PUBLIC :unrestricted})
                :expected-perms   (constantly "unrestricted")}

               "when changing permissions for table to unrestricted access"
               {:updated-db-perms (fn [] {:PUBLIC {(mt/id :venues) :unrestricted}})
                :expected-perms   (fn [] "unrestricted")}}]
        (met/with-gtaps! {:gtaps {:venues {}}}
          (testing message
            (testing "sanity check"
              (testing "perms graph endpoint should return segmented perms for Venues table"
                (is (= "sandboxed"
                       (get-in (mt/user-http-request :crowberto :get 200 "permissions/graph")
                               (venues-perms-graph-keypath &group)))))
              (testing "GTAP should exist in application DB"
                (is (malli= [:tuple
                             [:map
                              [:id                   ms/PositiveInt]
                              [:group_id             [:= (u/the-id &group)]]
                              [:table_id             [:= (mt/id :venues)]]
                              [:card_id              nil?]
                              [:attribute_remappings nil?]]]
                            (t2/select :model/Sandbox :group_id (u/the-id &group))))))
            (let [graph    (mt/user-http-request :crowberto :get 200 "permissions/graph")
                  graph'   (assoc-in graph (db-graph-keypath &group) (updated-db-perms))
                  response (mt/user-http-request :crowberto :put 200 "permissions/graph" graph')]
              (mt/with-temp [:model/Database               db-2 {}
                             :model/Table                  db-2-table {:db_id (u/the-id db-2)}
                             :model/Sandbox _ {:group_id (u/the-id &group)
                                               :table_id (u/the-id db-2-table)}
                             :model/PermissionsGroup       other-group {}
                             :model/Sandbox _ {:group_id (u/the-id other-group)
                                               :table_id (mt/id :venues)}]
                (testing "perms graph should be updated"
                  (testing "in API request response"
                    (is (= (expected-perms)
                           (get-in response (db-graph-keypath &group)))))
                  (testing "on subsequent fetch of the graph"
                    (is (= (expected-perms)
                           (get-in (mt/user-http-request :crowberto :get 200 "permissions/graph")
                                   (db-graph-keypath &group))))))
                (testing "GTAP should be deleted from application DB"
                  (is (= []
                         (t2/select :model/Sandbox
                                    :group_id (u/the-id &group)
                                    :table_id (mt/id :venues)))))
                (testing "GTAP for same group, other database should not be affected"
                  (is (malli= [:tuple
                               [:map
                                [:id                   ms/PositiveInt]
                                [:group_id             [:= (u/the-id &group)]]
                                [:table_id             [:= (u/the-id db-2-table)]]
                                [:card_id              nil?]
                                [:attribute_remappings nil?]]]
                              (t2/select :model/Sandbox
                                         :group_id (u/the-id &group)
                                         :table_id (u/the-id db-2-table)))))
                (testing "GTAP for same table, other group should not be affected"
                  (is (malli= [:tuple
                               [:map
                                [:id                   ms/PositiveInt]
                                [:group_id             [:= (u/the-id other-group)]]
                                [:table_id             [:= (mt/id :venues)]]
                                [:card_id              nil?]
                                [:attribute_remappings nil?]]]
                              (t2/select :model/Sandbox :group_id (u/the-id other-group)))))))))))))

(deftest grant-sandbox-perms-dont-delete-gtaps-test
  (testing "PUT /api/permissions/graph"
    (testing "granting sandboxed permissions for a group should *not* delete an associated GTAP (#16190)"
      (mt/with-temp-copy-of-db
        (mt/with-temp [:model/Sandbox _ {:group_id (u/the-id (perms-group/all-users))
                                         :table_id (mt/id :venues)}]
          (let [graph  (mt/user-http-request :crowberto :get 200 "permissions/graph")
                graph' (assoc-in graph (db-graph-keypath (perms-group/all-users))
                                 {"PUBLIC" {(mt/id :venues) "sandboxed"}})]
            (mt/user-http-request :crowberto :put 200 "permissions/graph" graph')
            (testing "GTAP should not have been deleted"
              (is (t2/exists? :model/Sandbox :group_id (u/the-id (perms-group/all-users)), :table_id (mt/id :venues))))))))))

(deftest collapsed-sandboxed-perms-dont-delete-gtaps-test
  (testing "PUT /api/permissions/graph"
    (testing (str "sandboxing the last unsandboxed table makes the frontend collapse the schema (or DB) to `sandboxed`, "
                  "which should keep the existing sandboxes rather than delete them")
      (doseq [[message updated-db-perms] {"schema-level sandboxed" {"PUBLIC" "sandboxed"}
                                          "DB-level sandboxed"     "sandboxed"}]
        (testing message
          (met/with-gtaps! {:gtaps {:venues {}}}
            (mt/with-model-cleanup [:model/Sandbox]
              (let [graph (-> (mt/user-http-request :crowberto :get 200 "permissions/graph")
                              (assoc-in (db-graph-keypath &group) updated-db-perms)
                              (assoc :sandboxes [{:group_id (u/the-id &group)
                                                  :table_id (mt/id :checkins)}]))]
                (mt/user-http-request :crowberto :put 200 "permissions/graph" graph)
                (testing "the existing sandbox is kept"
                  (is (t2/exists? :model/Sandbox :group_id (u/the-id &group) :table_id (mt/id :venues))))
                (testing "the newly added sandbox is saved"
                  (is (t2/exists? :model/Sandbox :group_id (u/the-id &group) :table_id (mt/id :checkins))))
                (testing "the graph reports both tables as sandboxed"
                  (is (=? {(mt/id :venues)   :sandboxed
                           (mt/id :checkins) :sandboxed}
                          (get-in (data-perms.graph/api-graph)
                                  [:groups (u/the-id &group) (mt/id) :view-data "PUBLIC"]))))))))))))

(defn- fake-persist-card! [card]
  (let [persisted-info (persisted-info/turn-on-model! (mt/user->id :rasta) card)]
    (t2/update! :model/PersistedInfo {:card_id (u/the-id card)}
                {:definition (json/encode
                              (persisted-info/metadata->definition
                               (:result_metadata card)
                               (:table_name persisted-info)))
                 :active true
                 :state "persisted"
                 :query_hash (persisted-info/query-hash (:dataset_query card))})))

(deftest persistence-and-permissions
  (mt/with-model-cleanup [:model/PersistedInfo]
    (testing "Queries from cache if not sandboxed"
      (mt/with-current-user (mt/user->id :rasta)
        (mt/with-temp [:model/Card card {:dataset_query (mt/mbql-query venues)
                                         :type :model
                                         :database_id (mt/id)}]
          (fake-persist-card! card)
          (is (str/includes?
               (:query (qp.compile/compile
                        {:database (mt/id)
                         :query {:source-table (str "card__" (u/the-id card))}
                         :type :query}))
               "metabase_cache")))))))

(deftest persistence-and-permissions-2
  (mt/with-model-cleanup [:model/PersistedInfo]
    (testing "Queries from source if sandboxed"
      (met/with-gtaps!
        {:gtaps {:venues {:query (mt/mbql-query venues)
                          :remappings {:cat ["variable" [:field (mt/id :venues :category_id) nil]]}}}
         :attributes {"cat" 50}}
        (mt/with-temp [:model/Card card {:dataset_query (mt/mbql-query venues)
                                         :type :model
                                         :database_id (mt/id)}]
          (fake-persist-card! card)
          (is (not (str/includes?
                    (:query (qp.compile/compile
                             {:database (mt/id)
                              :query {:source-table (str "card__" (u/the-id card))}
                              :type :query}))
                    "metabase_cache"))))))))

(deftest oss-preserves-sandboxed-view-data-test
  (testing "PUT /api/permissions/graph in OSS preserves stored EE sandbox config on rows it never surfaces"
    (mt/with-model-cleanup [:model/Sandbox]
      (mt/with-temp [:model/PermissionsGroup {gid :id} {}
                     :model/Card {cid1 :id} {}
                     :model/Card {cid2 :id} {}]
        (mt/with-premium-features #{:advanced-permissions :sandboxes}
          (mt/user-http-request
           :crowberto :put 200 "permissions/graph"
           (-> (data-perms.graph/api-graph)
               (assoc-in [:groups gid (mt/id) :view-data]
                         {"PUBLIC" {(mt/id :orders) :sandboxed (mt/id :people) :sandboxed}})
               (assoc :sandboxes [{:table_id (mt/id :orders) :group_id gid :card_id cid1 :attribute_remappings {"foo" 1}}
                                  {:table_id (mt/id :people) :group_id gid :card_id cid2 :attribute_remappings {"foo" 1}}]))))
        (mt/with-premium-features #{}
          (mt/user-http-request
           :crowberto :put 200 "permissions/graph"
           (assoc-in (data-perms.graph/api-graph)
                     [:groups gid (mt/id) :create-queries]
                     {"PUBLIC" {(mt/id :orders) :query-builder}})))
        (testing "both sandbox rows survive the OSS create-queries edit"
          (is (t2/exists? :model/Sandbox :table_id (mt/id :orders) :group_id gid))
          (is (t2/exists? :model/Sandbox :table_id (mt/id :people) :group_id gid)))
        (testing "the graph still surfaces :sandboxed view-data under EE"
          (mt/with-premium-features #{:advanced-permissions :sandboxes}
            (is (=? {(mt/id :orders) :sandboxed
                     (mt/id :people) :sandboxed}
                    (get-in (data-perms.graph/api-graph)
                            [:groups gid (mt/id) :view-data "PUBLIC"])))))))))

(defn- venues-sandboxed-view-data
  "API-graph `:view-data` for the test DB with VENUES sandboxed and every other PUBLIC Table unrestricted."
  []
  {"PUBLIC" (into {}
                  (for [table-id (t2/select-pks-set :model/Table :db_id (mt/id) :schema "PUBLIC" :active true)]
                    [table-id (if (= table-id (mt/id :venues)) :sandboxed :unrestricted)]))})

(def ^:private native-with-sandbox-error
  "A group with row and column security on a database cannot also have native query access to it.")

(deftest graph-rejects-native-access-with-sandboxes-test
  (testing "PUT /api/permissions/graph rejects granting native query access to a group with a sandbox on the database"
    (mt/with-premium-features #{:advanced-permissions :sandboxes}
      (mt/with-model-cleanup [:model/Sandbox]
        (mt/with-temp [:model/PermissionsGroup {gid :id} {}
                       :model/Card             {cid :id} {:dataset_query (mt/mbql-query venues {:filter [:= $category_id 50]})}]
          (let [create-queries (fn []
                                 (get-in (data-perms.graph/api-graph) [:groups gid (mt/id) :create-queries]))
                sandbox-ids    (fn []
                                 (t2/select-pks-set :model/Sandbox :group_id gid))
                sandbox-venues (fn [graph]
                                 (-> graph
                                     (assoc-in [:groups gid (mt/id) :view-data] (venues-sandboxed-view-data))
                                     (assoc :sandboxes [{:table_id (mt/id :venues) :group_id gid :card_id cid}])))]
            (perms/set-database-permission! gid (mt/id) :perms/create-queries :query-builder)
            (testing "when the sandbox and native access are granted in the same request"
              (is (= native-with-sandbox-error
                     (mt/user-http-request :crowberto :put 400 "permissions/graph"
                                           (-> (data-perms.graph/api-graph)
                                               sandbox-venues
                                               (assoc-in [:groups gid (mt/id) :create-queries] :query-builder-and-native)))))
              (is (empty? (sandbox-ids)))
              (is (= :query-builder (create-queries))))
            (testing "sandboxing a Table for a group with native access still revokes native access"
              (perms/set-database-permission! gid (mt/id) :perms/create-queries :query-builder-and-native)
              (mt/user-http-request :crowberto :put 200 "permissions/graph" (sandbox-venues (data-perms.graph/api-graph)))
              (is (= 1 (count (sandbox-ids))))
              (is (not= :query-builder-and-native (create-queries))))
            (testing "when native access is granted to a group that already has a sandbox"
              (is (= native-with-sandbox-error
                     (mt/user-http-request :crowberto :put 400 "permissions/graph"
                                           (assoc-in (data-perms.graph/api-graph)
                                                     [:groups gid (mt/id) :create-queries]
                                                     :query-builder-and-native))))
              (is (not= :query-builder-and-native (create-queries)))
              (is (= 1 (count (sandbox-ids)))))
            (testing "unrelated changes to a sandboxed group are still allowed"
              (mt/user-http-request :crowberto :put 200 "permissions/graph"
                                    (assoc-in (data-perms.graph/api-graph)
                                              [:groups gid (mt/id) :download]
                                              {:schemas :limited}))
              (is (= 1 (count (sandbox-ids)))))
            (testing "granting native access along with unrestricted access removes the sandbox, as the UI does"
              (mt/user-http-request :crowberto :put 200 "permissions/graph"
                                    (update-in (data-perms.graph/api-graph) [:groups gid (mt/id)] assoc
                                               :view-data      :unrestricted
                                               :create-queries :query-builder-and-native))
              (is (= :query-builder-and-native (create-queries)))
              (is (empty? (sandbox-ids))))))))))