The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
API Keys module cleanup (#62116)
Cam Saulfe43845ee21f
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex a5104ebb04c..59846122c30 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -143,7 +143,8 @@api-keys{:team "UX West":api #{metabase.api-keys.api- metabase.api-keys.core}+ metabase.api-keys.core+ metabase.api-keys.schema}:uses #{apiapp-dbevents@@ -993,7 +994,8 @@request{:team "UX West":api #{metabase.request.core- metabase.request.init}+ metabase.request.init+ metabase.request.schema}:uses #{apiconfigpermissions ; FIXMEdiff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/file/api_keys.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/file/api_keys.cljindex e852275eef5..4d8ce473eeb 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_config/file/api_keys.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/file/api_keys.clj@@ -59,16 +59,16 @@(do(log/info (u/format-color :blue "API key with name %s already exists, skipping" (pr-str name)))existing-api-key)- (let [group-id (case group- "admin" (u/the-id (perms/admin-group))- "all-users" (u/the-id (perms/all-users-group)))+ (let [group-id (case group+ "admin" (u/the-id (perms/admin-group))+ "all-users" (u/the-id (perms/all-users-group)))unhashed-key (u.secret/secret key)- _ (when-not (and (<= 11 (count key) 254)- (re-matches #"mb_[A-Za-z0-9+/=]+" key))- (throw (ex-info (format "Invalid API key format. Key must be between 11-254 characters and start with 'mb_'.")- {:name name})))- prefix (api-key/prefix (u.secret/expose unhashed-key))- creator (get-admin-user-by-email creator)]+ _ (when-not (and (<= 11 (count key) 254)+ (re-matches #"mb_[A-Za-z0-9+/=]+" key))+ (throw (ex-info (format "Invalid API key format. Key must be between 11-254 characters and start with 'mb_'.")+ {:name name})))+ prefix (api-key/prefix (u.secret/expose unhashed-key))+ creator (get-admin-user-by-email creator)];; Check if there's an existing API key with the same prefix(when (t2/exists? :model/ApiKey :key_prefix prefix)@@ -78,22 +78,22 @@(log/info (u/format-color :green "Creating new API key %s" (pr-str name)));; Create a user for the API key(let [email (format "api-key-user-%[email protected]" (random-uuid))- user (first- (t2/insert-returning-instances! :model/User- {:email email- :first_name name- :last_name ""- :type :api-key- :password (str (random-uuid))}))]+ user (first+ (t2/insert-returning-instances! :model/User+ {:email email+ :first_name name+ :last_name ""+ :type :api-key+ :password (str (random-uuid))}))];; Set permissions groups for the user(user/set-permissions-groups! user [(perms/all-users-group) {:id group-id}]);; Create the API key(t2/insert-returning-instance! :model/ApiKey- {:user_id (u/the-id user)- :name name- :unhashed_key unhashed-key- :creator_id (u/the-id creator)- :updated_by_id (u/the-id creator)}))))))+ {:user_id (u/the-id user)+ :name name+ ::api-key/unhashed-key unhashed-key+ :creator_id (u/the-id creator)+ :updated_by_id (u/the-id creator)}))))))(defmethod advanced-config.file.i/initialize-section! :api-keys[_section-name api-keys]diff --git a/enterprise/backend/src/metabase_enterprise/scim/api.clj b/enterprise/backend/src/metabase_enterprise/scim/api.cljindex 1b467090620..e7dc43691f5 100644--- a/enterprise/backend/src/metabase_enterprise/scim/api.clj+++ b/enterprise/backend/src/metabase_enterprise/scim/api.clj@@ -29,12 +29,12 @@(t2/delete! :model/ApiKey :scope :scim)(let [unhashed-key (api-key/generate-key)](->- (t2/insert-returning-instance! :model/ApiKey {:user_id nil- :scope :scim- :name (scim-api-key-name)- :unhashed_key unhashed-key- :creator_id user-id- :updated_by_id user-id})+ (t2/insert-returning-instance! :model/ApiKey {:user_id nil+ :scope :scim+ :name (scim-api-key-name)+ ::api-key/unhashed-key unhashed-key+ :creator_id user-id+ :updated_by_id user-id})(assoc :unmasked_key (u.secret/expose unhashed-key))))))(api.macros/defendpoint :get "/api_key"diff --git a/enterprise/backend/test/metabase_enterprise/scim/api_test.clj b/enterprise/backend/test/metabase_enterprise/scim/api_test.cljindex 512f1808c7a..c8ce657716a 100644--- a/enterprise/backend/test/metabase_enterprise/scim/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/scim/api_test.clj@@ -51,18 +51,19 @@(testing "Can create a new SCIM API key"(let [key1 (mt/user-http-request :crowberto :post 200 "ee/scim/api_key")](is (=? (scim-api-key-shape :crowberto) key1))-(testing "Can refresh an API key"(let [key2 (mt/user-http-request :crowberto :post 200 "ee/scim/api_key")](is (=? (scim-api-key-shape :crowberto) key2))- (is (not= key1 key2))))))+ (is (not= key1 key2)))))))))+(deftest ^:parallel post-api-key-test-2+ (testing "POST /api/ee/scim/api_key"+ (mt/with-premium-features #{:scim}(testing "A non-admin cannot create a SCIM API key"- (mt/user-http-request :rasta :post 403 "ee/scim/api_key"))+ (mt/user-http-request :rasta :post 403 "ee/scim/api_key")))))- (testing "Users and Groups have entity IDs backfilled when a new SCIM key is generated"- (mt/with-temp [:model/User user {:entity_id nil}- :model/PermissionsGroup group {:entity_id nil}]- (mt/user-http-request :crowberto :post 200 "ee/scim/api_key")- (is (not (nil? (t2/select-one-fn :entity_id :model/User :id (:id user)))))- (is (not (nil? (t2/select-one-fn :entity_id :model/PermissionsGroup :id (:id group))))))))))+(deftest ^:parallel post-api-key-test-3+ (testing "POST /api/ee/scim/api_key"+ (mt/with-premium-features #{:scim}+ (testing "A non-admin cannot create a SCIM API key"+ (mt/user-http-request :rasta :post 403 "ee/scim/api_key")))))diff --git a/src/metabase/api_keys/api.clj b/src/metabase/api_keys/api.cljindex f8d1dd34051..d13ee3964c8 100644--- a/src/metabase/api_keys/api.clj+++ b/src/metabase/api_keys/api.clj@@ -1,14 +1,12 @@(ns metabase.api-keys.api"/api/api-key endpoints for CRUD management of API Keys"(:require+ [medley.core :as m]+ [metabase.api-keys.core :as-alias api-keys][metabase.api-keys.models.api-key :as api-key]+ [metabase.api-keys.schema :as api-keys.schema][metabase.api.common :as api][metabase.api.macros :as api.macros]- [metabase.events.core :as events]- [metabase.permissions.core :as perms]- [metabase.users.models.user :as user]- [metabase.util :as u]- [metabase.util.i18n :refer [tru]][metabase.util.malli.schema :as ms][metabase.util.secret :as u.secret][toucan2.core :as t2]))@@ -34,54 +32,16 @@(maybe-expose-key)(update :updated_by #(select-keys % [:common_name :id]))))-(defn- key-with-unique-prefix []- (u/auto-retry 5- (let [api-key (api-key/generate-key)- prefix (api-key/prefix (u.secret/expose api-key))]- ;; we could make this more efficient by generating 5 API keys up front and doing one select to remove any- ;; duplicates. But a duplicate should be rare enough to just do multiple queries for now.- (if-not (t2/exists? :model/ApiKey :key_prefix prefix)- api-key- (throw (ex-info (tru "could not generate key with unique prefix") {}))))))--(defn- with-updated-by [api-key]- (assoc api-key :updated_by_id api/*current-user-id*))--(defn- with-creator [api-key]- (assoc api-key :creator_id api/*current-user-id*))-(api.macros/defendpoint :post "/""Create a new API key (and an associated `User`) with the provided name and group ID."[_route-params_query-params- {:keys [group_id name] :as _body} :- [:map- [:group_id ms/PositiveInt]- [:name ms/NonBlankString]]]+ {group-id :group_id, key-name :name, :as _body} :- [:map+ [:group_id ::api-keys.schema/id]+ [:name ms/NonBlankString]]](api/check-superuser)- (api/checkp (not (t2/exists? :model/ApiKey :name name))- "name" "An API key with this name already exists.")- (let [unhashed-key (key-with-unique-prefix)- email (format "api-key-user-%[email protected]" (random-uuid))]- (t2/with-transaction [_conn]- (let [user (first- (t2/insert-returning-instances! :model/User- {:email email- :first_name name- :last_name ""- :type :api-key- :password (str (random-uuid))}))]- (user/set-permissions-groups! user [(perms/all-users-group) group_id])- (let [api-key (-> (t2/insert-returning-instance! :model/ApiKey- (-> {:user_id (u/the-id user)- :name name- :unhashed_key unhashed-key}- with-creator- with-updated-by))- (t2/hydrate :group :updated_by))]- (events/publish-event! :event/api-key-create- {:object api-key- :user-id api/*current-user-id*})- (present-api-key (assoc api-key :unmasked_key unhashed-key)))))))+ (-> (api-key/create-api-key-with-new-user! {:key-name key-name, :group-id group-id})+ present-api-key))(api.macros/defendpoint :get "/count""Get the count of API keys in the DB with the default scope."@@ -94,51 +54,31 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]_query-params- {:keys [group_id name] :as _body} :- [:map- [:group_id {:optional true} [:maybe ms/PositiveInt]]- [:name {:optional true} [:maybe ms/NonBlankString]]]]+ {group-id :group_id, key-name :name} :- [:map+ [:group_id {:optional true} [:maybe ms/PositiveInt]]+ [:name {:optional true} [:maybe ::api-keys.schema/name]]]](api/check-superuser)- (let [api-key-before (-> (t2/select-one :model/ApiKey :id id)- ;; hydrate the group_name for audit logging- (t2/hydrate :group)- (api/check-404))]- (t2/with-transaction [_conn]- (when group_id- (let [user (-> api-key-before (t2/hydrate :user) :user)]- (user/set-permissions-groups! user [(perms/all-users-group) {:id group_id}])))- (when name- ;; A bit of a pain to keep these in sync, but oh well.- (t2/update! :model/User (:user_id api-key-before) {:first_name name- :last_name ""})- (t2/update! :model/ApiKey id (with-updated-by {:name name}))))- (let [updated-api-key (-> (t2/select-one :model/ApiKey :id id)- (t2/hydrate :group :updated_by))]- (events/publish-event! :event/api-key-update {:object updated-api-key- :previous-object api-key-before- :user-id api/*current-user-id*})- (present-api-key updated-api-key))))+ (api/let-404 [api-key-before (t2/select-one :model/ApiKey id)]+ (-> api-key-before+ (m/assoc-some ::api-keys/group-id group-id, :name key-name)+ t2/save!+ present-api-key)))-(api.macros/defendpoint :put "/:id/regenerate"+(api.macros/defendpoint :put "/:id/regenerate" :- [:map+ [:id ::api-keys.schema/id]+ [:unmasked_key ::api-keys.schema/key.raw]+ [:masked_key ::api-keys.schema/key.masked]+ [:prefix ::api-keys.schema/prefix]]"Regenerate an API Key"[{:keys [id]} :- [:map- [:id ms/PositiveInt]]]+ [:id ::api-keys.schema/id]]](api/check-superuser)- (let [api-key-before (-> (t2/select-one :model/ApiKey id)- (t2/hydrate :group)- (api/check-404))- unhashed-key (key-with-unique-prefix)- api-key-after (assoc api-key-before- :unhashed_key unhashed-key- :key_prefix (api-key/prefix (u.secret/expose unhashed-key)))]- (t2/update! :model/ApiKey :id id (with-updated-by- (select-keys api-key-after [:unhashed_key])))- (events/publish-event! :event/api-key-regenerate- {:object api-key-after- :previous-object api-key-before- :user-id api/*current-user-id*})- (present-api-key (assoc api-key-after- :unmasked_key unhashed-key- :masked_key (api-key/mask unhashed-key)))))+ (api/check-404 (t2/exists? :model/ApiKey id))+ (let [regenerated (api-key/regenerate! id)]+ {:id id+ :unmasked_key (u.secret/expose (:unmasked-key regenerated))+ :masked_key (:masked-key regenerated)+ :prefix (:prefix regenerated)}))(api.macros/defendpoint :get "/""Get a list of API keys with the default scope. Non-paginated."@@ -150,15 +90,13 @@(api.macros/defendpoint :delete "/:id""Delete an ApiKey"[{:keys [id]} :- [:map- [:id ms/PositiveInt]]]+ [:id ::api-keys.schema/id]]](api/check-superuser)- (let [api-key (-> (t2/select-one :model/ApiKey id)- (t2/hydrate :group)- (api/check-404))]- (t2/with-transaction [_tx]- (t2/delete! :model/ApiKey id)- (t2/update! :model/User (:user_id api-key) {:is_active false}))- (events/publish-event! :event/api-key-delete- {:object api-key- :user-id api/*current-user-id*})- api/generic-204-no-content))+ (api/check-404 (t2/exists? :model/ApiKey id))+ (t2/delete! :model/ApiKey id)+ api/generic-204-no-content)++#_:clj-kondo/ignore+(comment+ ;; check the generated docs+ (metabase.api.open-api/open-api-spec (metabase.api.macros/ns-handler) "/api/api-key"))diff --git a/src/metabase/api_keys/models/api_key.clj b/src/metabase/api_keys/models/api_key.cljindex 21a46387aa3..ba7dd749303 100644--- a/src/metabase/api_keys/models/api_key.clj+++ b/src/metabase/api_keys/models/api_key.clj@@ -1,29 +1,37 @@(ns metabase.api-keys.models.api-key+ "`:metabase.api-keys.core/group-id` and `:metabase.api-keys.core/unhashed-key` have special meanings when passed to+ various Toucan CRUD methods for `:model/ApiKey`... see below."(:require[clojure.core.memoize :as memoize][crypto.random :as crypto-random]+ [java-time.api :as t]+ [malli.error :as me]+ [metabase.api-keys.core :as-alias api-keys]+ [metabase.api-keys.schema :as api-keys.schema]+ [metabase.api.common :as api][metabase.app-db.core :as mdb]+ [metabase.events.core :as events][metabase.models.interface :as mi][metabase.permissions.core :as perms]+ [metabase.users.models.user :as user][metabase.util :as u]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr][metabase.util.password :as u.password][metabase.util.secret :as u.secret][methodical.core :as methodical]- [toucan2.core :as t2]))+ [toucan2.core :as t2]+ [toucan2.tools.hydrate :as t2.hydrate]))-;; the prefix length, the length of `mb_1234`-(def ^:private prefix-length 7)--;; the total number of bytes of randomness we generate for API keys-(def ^:private bytes-key-length 32)+(set! *warn-on-reflection* true)(methodical/defmethod t2/table-name :model/ApiKey [_model] :api_key)-(mi/define-batched-hydration-method add-group- :group- "Add to each ApiKey a single group. Assume that each ApiKey is a member of either zero or one groups other than- the 'All Users' group."- [api-keys]+(methodical/defmethod t2.hydrate/batched-hydrate [:model/ApiKey :group]+ "Add to each ApiKey a single group. Assume that each ApiKey is a member of either zero or one groups other than the+ 'All Users' group."+ [_model _k api-keys](when (seq api-keys)(let [api-key-id->permissions-groups(group-by :api-key-id@@ -51,51 +59,113 @@(t2/deftransforms :model/ApiKey{:scope mi/transform-keyword})-(defn prefix- "Given an API key, returns the standardized prefix for that API key."- [key]- (apply str (take prefix-length key)))+(mu/defn- expose :- :string+ ^String [s :- [:or ::u.secret/secret :string]]+ (cond-> s+ (u.secret/secret? s) u.secret/expose))-(defn- add-prefix [{:keys [unhashed_key] :as api-key}]+(mu/defn prefix :- ::api-keys.schema/prefix+ "Given an API key, returns the standardized prefix for that API key."+ ^String [k :- [:or+ ::api-keys.schema/key.unhashed-or-secret+ ::api-keys.schema/prefix]]+ (subs (expose k) 0 api-keys.schema/prefix-length))++(mu/defn- add-prefix :- [:map+ [:key_prefix {:optional true} ::api-keys.schema/prefix]]+ [{unhashed-key ::api-keys/unhashed-key, :as api-key} :- [:map+ [::api-keys/unhashed-key {:optional true} ::api-keys.schema/key.unhashed-or-secret]]](cond-> api-key- (contains? api-key :unhashed_key)- (assoc :key_prefix (some-> unhashed_key u.secret/expose prefix))))+ (contains? api-key ::api-keys/unhashed-key) (assoc :key_prefix (some-> unhashed-key prefix))))-(defn generate-key+(mu/defn generate-key :- ::api-keys.schema/key.secret"Generates a new API key - a random base64 string prefixed with `mb_`"[](u.secret/secret- (str "mb_" (crypto-random/base64 bytes-key-length))))--(def ^:private string-key-length (delay (count (u.secret/expose (generate-key)))))+ (str "mb_" (crypto-random/base64 api-keys.schema/generated-bytes-key-length))))-(defn mask+(mu/defn mask :- ::api-keys.schema/key.masked"Given an API key, returns a string of the same length with all but the prefix masked with `*`s"- [key]- (->> (concat (prefix key) (repeat "*"))- (take @string-key-length)- (apply str)))--(defn- add-key- "Adds the `key` based on the `unhashed_key` passed in."- [{:keys [unhashed_key] :as api-key}]- (cond-> api-key- (contains? api-key :unhashed_key)- (assoc :key (some-> unhashed_key u.secret/expose u.password/hash-bcrypt))+ ^String [k :- [:or+ ::api-keys.schema/key.unhashed-or-secret+ ::api-keys.schema/prefix]]+ (let [sb (StringBuilder.)]+ (.append sb (prefix k))+ (dotimes [_ (- api-keys.schema/generated-string-key-length api-keys.schema/prefix-length)]+ (.append sb \*))+ (str sb)))++(mu/defn- hash-bcrypt :- ::api-keys.schema/key.hashed+ [k :- ::api-keys.schema/key.unhashed-or-secret]+ (-> k expose u.password/hash-bcrypt))++(mu/defn- add-key+ "Adds the `key` based on the `:metabase.api-keys/unhashed-qkey passed in."+ [{unhashed-key ::api-keys/unhashed-key, :as api-key} :- [:map+ [::api-keys/unhashed-key {:optional true} ::api-keys.schema/key.unhashed-or-secret]]]+ (-> api-key+ (cond-> (contains? api-key ::api-keys/unhashed-key) (assoc :key (some-> unhashed-key hash-bcrypt)))+ (dissoc ::api-keys/unhashed-key)))- true (dissoc :unhashed_key)))+(defn- validate-with-schema [api-key schema]+ (when-let [error (mr/explain schema api-key)]+ (let [humanized (me/humanize error)]+ (throw (ex-info (format "Invalid API Key: %s" (pr-str humanized))+ {:error humanized+ :original error}))))+ api-key)(t2/define-before-insert :model/ApiKey[api-key](-> api-keyadd-prefix- add-key))+ add-key+ (validate-with-schema ::api-keys.schema/api-key.insert)))-(t2/define-before-update :model/ApiKey+(t2/define-after-insert :model/ApiKey[api-key]- (-> api-key- add-prefix- add-key))+ (u/prog1 api-key+ (events/publish-event!+ :event/api-key-create+ {:object (t2/hydrate api-key :group :updated_by)+ :user-id api/*current-user-id*})))++(t2/define-before-update :model/ApiKey+ [{user-id :user_id, :as api-key}]+ (t2/with-transaction [_conn]+ ;; need to hydrate user info BEFORE making changes so we record the correct stuff for audit logging+ (let [key-before (t2/hydrate (t2/instance :model/ApiKey (t2/original api-key)) :user :group :updated_by)]+ ;; update the user name associated with this API key if it was created just for this API key.+ (when-let [new-name (:name (t2/changes api-key))]+ (t2/update! :model/User :id user-id, :type :api-key, {:first_name new-name, :last_name ""}))+ ;; update user group as well.+ (when-let [new-group-id (::api-keys/group-id (t2/changes api-key))]+ (assert (= (t2/select-one-fn :type :model/User :id user-id) :api-key)+ "Cannot change the Permissions Group for the user associated with an API key that was not created alongside it")+ (user/set-permissions-groups! user-id [(perms/all-users-group) {:id new-group-id}]))+ (u/prog1 (-> api-key+ add-prefix+ add-key+ ;; force a no-op update so the T2 code doesn't optimize this whole update out+ (cond-> (::api-keys/group-id (t2/changes api-key)) (-> (dissoc ::api-keys/group-id)+ (assoc :updated_at (t/offset-date-time))))+ (validate-with-schema ::api-keys.schema/api-key.update))+ (events/publish-event!+ :event/api-key-update+ {:object (t2/hydrate (t2/instance :model/ApiKey (t2/current <>)) :user :group :updated_by)+ :previous-object key-before+ :user-id api/*current-user-id*})))))++(t2/define-before-delete :model/ApiKey+ [{user-id :user_id, :as api-key}]+ (u/prog1 api-key+ (events/publish-event!+ :event/api-key-delete+ {:object (-> api-key+ (t2/hydrate :group))+ :user-id api/*current-user-id*})+ ;; if we created a user along with the key (type = :api-key), mark it inactive.+ (t2/update! :model/User user-id, :type :api-key, {:is_active false})))(defn- add-masked-key [api-key](if-let [prefix (:key_prefix api-key)]@@ -115,7 +185,68 @@(fn is-api-key-user?*[user-id](= :api-key (t2/select-one-fn :type :model/User user-id)))-;; cache the results for 60 minutes; TTL is here only to eventually clear out old entries/keep it from growing too;; large:ttl/threshold (* 60 60 1000)))++(mu/defn key-with-unique-prefix :- ::api-keys.schema/key.secret+ "Generate an unique API key with a unique prefix."+ []+ (u/auto-retry 5+ (let [api-key (generate-key)+ prefix (prefix (u.secret/expose api-key))]+ ;; we could make this more efficient by generating 5 API keys up front and doing one select to remove any+ ;; duplicates. But a duplicate should be rare enough to just do multiple queries for now.+ (if-not (t2/exists? :model/ApiKey :key_prefix prefix)+ api-key+ (throw (ex-info (tru "could not generate key with unique prefix") {}))))))++(mu/defn create-api-key-with-new-user!+ "Create a new API key and a new user for that key at the same time."+ [{:keys [key-name group-id]} :- [:map+ {:closed true}+ [:key-name ::api-keys.schema/name]+ [:group-id {:optional true} pos-int?]]]+ (api/checkp (not (t2/exists? :model/ApiKey :name key-name))+ "name" "An API key with this name already exists.")+ (let [unhashed-key (key-with-unique-prefix)+ email (format "api-key-user-%[email protected]" (random-uuid))]+ (t2/with-transaction [_conn]+ (let [user-id (t2/insert-returning-pk! :model/User+ {:email email+ :first_name key-name+ :last_name ""+ :type :api-key+ :password (str (random-uuid))})]+ (user/set-permissions-groups! user-id [(perms/all-users-group) group-id])+ (-> (t2/insert-returning-instance! :model/ApiKey+ {:user_id user-id+ :name key-name+ ::api-keys/unhashed-key unhashed-key+ :updated_by_id api/*current-user-id*+ :creator_id api/*current-user-id*})+ (assoc :unmasked_key unhashed-key))))))++(mu/defn regenerate! :- [:map+ [:unmasked-key ::api-keys.schema/key.secret]+ [:masked-key ::api-keys.schema/key.masked]+ [:prefix ::api-keys.schema/prefix]]+ "Generate a new API key for an existing key with `id`."+ [id :- ::api-keys.schema/id]+ (let [api-key-before (t2/select-one :model/ApiKey id)+ new-key (key-with-unique-prefix)+ new-prefix (prefix new-key)]+ (t2/with-transaction [_conn]+ (t2/update! :model/ApiKey :id id {:key (hash-bcrypt new-key)+ :key_prefix new-prefix+ :updated_by_id api/*current-user-id*})+ (events/publish-event! :event/api-key-regenerate+ (let [key-before (-> api-key-before+ (t2/hydrate :group))]+ {:object (-> key-before+ (assoc :key_prefix new-prefix))+ :previous-object key-before+ :user-id api/*current-user-id*})))+ {:unmasked-key new-key+ :masked-key (mask new-key)+ :prefix new-prefix}))diff --git a/src/metabase/api_keys/schema.clj b/src/metabase/api_keys/schema.cljnew file mode 100644index 00000000000..908ca9bd345--- /dev/null+++ b/src/metabase/api_keys/schema.clj@@ -0,0 +1,130 @@+(ns metabase.api-keys.schema+ (:require+ [clojure.math :as math]+ [clojure.string :as str]+ [malli.core :as mc]+ [metabase.util.malli.registry :as mr]+ [metabase.util.malli.schema :as ms]+ [metabase.util.secret]))++(def prefix-length+ "The prefix length, the length of `mb_1234`"+ 7)++(def generated-bytes-key-length+ "The total number of bytes of randomness we generate for API keys."+ 32)++(def generated-string-key-length+ "Total length of an unhashed API key `key` string, including the `mb_` prefix."+ (let [num-bits (* generated-bytes-key-length 8)+ num-unpadded-chars (/ num-bits 6) ; base-64 uses one character for every 6 bits+ num-blocks (math/ceil (/ num-unpadded-chars 4)) ; base-64 adds padding so the number of chars is divisible by 4+ num-chars (* num-blocks 4)]+ (long (+ num-chars 3)))) ; add 3 characters for the `mb_` prefix++;;; these numbers are taken from the documentation. If you let us make you a key it will+;;; be [[generated-string-key-length]] long, but if you're supplying your own e.g. with EE config files then it has to+;;; fall in this range.+(def ^:private minimum-string-key-length 12)+(def ^:private maximum-string-key-length 254)++(mr/def ::key.raw+ "Unhashed string of the form 'mb_<base-64-bytes>'."+ [:and+ [:string {:min minimum-string-key-length, :max maximum-string-key-length}]+ ;; TODO (cam 8/13/25) -- we could also enforce that this string only uses valid base-64 characters since that is+ ;; technically the rule+ [:fn+ {:error/message "An API token key must start with 'mb_'"}+ (fn [s]+ (and (string? s)+ (str/starts-with? s "mb_")))]])++(mr/def ::key.masked+ "Masked string like 'mb_1234**********'."+ [:and+ [:ref ::key.raw]+ [:re+ {:error/message "Masked key like 'mb_1234**********'"}+ (re-pattern (format "^mb_.*{%d}\\*+$" (- prefix-length 3)))]])++(mr/def ::key.secret+ [:ref :metabase.util.secret/secret])++(mr/def ::key.unhashed-or-secret+ [:or+ [:ref ::key.raw]+ [:ref ::key.secret]])++(mr/def ::key.hashed+ "BCrypt-hashed API key string."+ [:and+ [:string {:min 60, :max 60}] ; bcrypt hashes are 60 characters, at least ours always are.+ [:fn+ {:error/message "A hashed API token key should NOT start with `mb_` (this means it is unhashed)."}+ (fn [s]+ (and (string? s)+ (not (str/starts-with? s "mb_"))))]])++(mr/def ::id+ "An ID of a `:model/ApiKey`."+ ms/PositiveInt)++(mr/def ::prefix+ "Prefix string of an API Key, suitable for passing around unmasked. This must be unique."+ [:string {:min prefix-length, :max prefix-length}])++(mr/def ::name+ [:string {:min 1, :max 254}]) ; min/max are from the app DB being varchar(254)++(mr/def ::scope+ [:enum :scim])++(mr/def ::timestamp+ [:or+ (ms/InstanceOfClass java.time.OffsetDateTime)+ (ms/InstanceOfClass java.time.ZonedDateTime)])++(mr/def ::api-key+ "Schema for a `:model/ApiKey`; this is based on the `api_key` table as defined in the application database.++ This schema corresponds to a row as you would get with `SELECT`."+ [:map+ {:closed true}+ [:id {::insert.optional true} ::id]+ [:user_id {:optional true} [:maybe pos-int?]]+ [:key [:ref ::key.hashed]]+ [:key_prefix [:ref ::prefix]]+ [:creator_id pos-int?]+ [:created_at {::insert.optional true} [:ref ::timestamp]]+ [:updated_at {::insert.optional true} [:ref ::timestamp]]+ [:name [:ref ::name]]+ [:updated_by_id pos-int?]+ [:scope {:optional true} [:maybe [:ref ::scope]]]+ [:single_collection_id {:optional true} [:maybe pos-int?]]])++(defn- insert-schema [map-schema]+ (into [:map]+ (map (fn [[k properties schema]]+ (if properties+ [k+ (cond-> properties+ (::insert.optional properties) (assoc :optional true))+ schema]+ [k schema])))+ (mc/children (mr/resolve-schema map-schema))))++(mr/def ::api-key.insert+ (insert-schema ::api-key))++(defn- update-schema [map-schema]+ (into [:map]+ (map (fn [[k properties schema]]+ [k+ (assoc properties :optional true)+ schema]))+ (mc/children (mr/resolve-schema map-schema))))++(mr/def ::api-key.update+ (update-schema ::api-key))diff --git a/src/metabase/lib/schema/id.cljc b/src/metabase/lib/schema/id.cljcindex 6992240bdd2..397c9ad1667 100644--- a/src/metabase/lib/schema/id.cljc+++ b/src/metabase/lib/schema/id.cljc@@ -66,3 +66,6 @@(mr/def ::native-query-snippet[:schema {:doc/title "Valid Native Query Snippet ID"} pos-int?])++(mr/def ::collection+ [:schema {:doc/title "Valid Collection ID"} pos-int?])diff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.cljindex 6e644a13408..3f1adde17e0 100644--- a/src/metabase/permissions/core.clj+++ b/src/metabase/permissions/core.clj@@ -89,7 +89,8 @@[metabase.permissions.pathapplication-perms-pathcollection-read-path- collection-readwrite-path]+ collection-readwrite-path+ collection-path?][metabase.permissions.useruser-permissions-set][metabase.permissions.utildiff --git a/src/metabase/permissions/models/permissions.clj b/src/metabase/permissions/models/permissions.cljindex 557ef1e2d33..f69cf94486f 100644--- a/src/metabase/permissions/models/permissions.clj+++ b/src/metabase/permissions/models/permissions.clj@@ -141,7 +141,7 @@### Known Permissions Paths- See [[path-regex-v1]] for an always-up-to-date list of permissions paths.+ See [[metabase.permissions.util/path-regex-v1]] for an always-up-to-date list of permissions paths./collection/:id/ ; read-write perms for a Coll and its non-Coll children/collection/:id/read/ ; read-only perms for a Coll and its non-Coll childrendiff --git a/src/metabase/permissions/path.clj b/src/metabase/permissions/path.cljindex f795f8e3e4e..98e973d47ef 100644--- a/src/metabase/permissions/path.clj+++ b/src/metabase/permissions/path.clj@@ -1,5 +1,6 @@(ns metabase.permissions.path(:require+ [clojure.string :as str][metabase.permissions.util :as perms.u][metabase.util :as u][metabase.util.malli :as mu]@@ -18,6 +19,16 @@(format "/collection/namespace/%s/root/" (perms.u/escape-path-component (u/qualified-name collection-namespace)))"/collection/root/")))+(mu/defn collection-path?+ "Whether permissions `path` is any type of path for any Collection (1-arity) or for the Collection with+ `collection-id` (2-arity)."+ ([path :- [:maybe perms.u/PathSchema]]+ (str/starts-with? path "/collection/"))++ ([path :- [:maybe perms.u/PathSchema]+ collection-id :- pos-int?]+ (str/starts-with? path (format "/collection/%d/" collection-id))))+(mu/defn collection-read-path :- perms.u/PathSchema"Return the permissions path for *read* access for a `collection-or-id`."[collection-or-id :- MapOrID]diff --git a/src/metabase/request/schema.clj b/src/metabase/request/schema.cljnew file mode 100644index 00000000000..271639faa29--- /dev/null+++ b/src/metabase/request/schema.clj@@ -0,0 +1,13 @@+(ns metabase.request.schema+ (:require+ [metabase.util.malli.registry :as mr]))++;;; TODO (Cam 8/13/25) -- should this map be closed, that way we can make sure all the keys we might be using are+;;; enumerated here?+(mr/def ::current-user-info+ [:map+ [:metabase-user-id {:optional true} pos-int?]+ [:is-superuser? {:optional true} :boolean]+ [:user-locale {:optional true} [:maybe string?]]+ [:is-group-manager? {:optional true} :boolean]+ [:permissions-set {:optional true} [:set :string]]])diff --git a/src/metabase/request/session.clj b/src/metabase/request/session.cljindex 742bdc1efb9..dabb253f9fb 100644--- a/src/metabase/request/session.clj+++ b/src/metabase/request/session.clj@@ -4,9 +4,11 @@:as api:refer [*current-user* *current-user-id* *current-user-permissions-set* *is-group-manager?* *is-superuser?*]][metabase.permissions.core :as perms]+ [metabase.request.schema :as request.schema][metabase.settings.core :as setting][metabase.users.models.user :as user][metabase.util.i18n :as i18n]+ [metabase.util.malli :as mu][toucan2.core :as t2]))(def ^:private current-user-fields@@ -28,15 +30,21 @@;;::none)-(defn do-with-current-user+(mu/defn- current-user-info->permissions-set :- [:maybe [:set :string]]+ [{:keys [permissions-set metabase-user-id]} :- ::request.schema/current-user-info]+ (or permissions-set+ (some-> metabase-user-id perms/user-permissions-set)))++(mu/defn do-with-current-user"Impl for [[with-current-user]]."- [{:keys [metabase-user-id is-superuser? permissions-set user-locale settings is-group-manager?]} thunk]+ [{:keys [metabase-user-id is-superuser? user-locale settings is-group-manager?], :as current-user-info} :- [:maybe ::request.schema/current-user-info]+ thunk](binding [*current-user-id* metabase-user-idi18n/*user-locale* user-locale*is-group-manager?* (boolean is-group-manager?)*is-superuser?* (boolean is-superuser?)*current-user* (delay (find-user metabase-user-id))- *current-user-permissions-set* (delay (or permissions-set (some-> metabase-user-id perms/user-permissions-set)))]+ *current-user-permissions-set* (delay (current-user-info->permissions-set current-user-info))];; As mentioned above, do not rebind user-local values to something new, because changes to its value will not be;; propagated to frames further up the stack.(letfn [(do-with-user-local-values [thunk]diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex ad48bb15746..b880f2cdfe1 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -14,18 +14,25 @@The second main path to authentication is an API key. For this, we look at the `X-Api-Key` header. If that matchesan ApiKey in our database, you'll be authenticated as that ApiKey's associated User."(:require+ [clojure.string :as str][honey.sql.helpers :as sql.helpers][java-time.api :as t]+ [malli.error :as me]+ [medley.core :as m][metabase.api-keys.core :as api-key]+ [metabase.api-keys.schema :as api-keys.schema][metabase.app-db.core :as mdb][metabase.config.core :as config][metabase.core.initialization-status :as init-status][metabase.premium-features.core :as premium-features][metabase.request.core :as request]+ [metabase.request.schema :as request.schema][metabase.session.core :as session][metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :as i18n][metabase.util.log :as log]+ [metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr][metabase.util.password :as u.password][metabase.util.string :as string][toucan2.core :as t2]@@ -160,7 +167,7 @@[session-key](or (not session-key) (string/valid-uuid? session-key)))-(defn- current-user-info-for-session+(mu/defn- current-user-info-for-session :- [:maybe ::request.schema/current-user-info]"Return User ID and superuser status for Session with `session-key` if it is valid and not expired."[session-key anti-csrf-token](when (and session-key (valid-session-key? session-key) (init-status/complete?))@@ -191,16 +198,29 @@(u.password/verify-password passed-api-key "" api-key)(do-useless-hash)))-(defn- current-user-info-for-api-key+(mu/defn- current-user-info-for-api-key :- [:maybe ::request.schema/current-user-info]"Return User ID and superuser status for an API Key with `api-key-id"- [api-key]- (when (and api-key (init-status/complete?))- (let [user-data (some-> (t2/query-one (cons (user-data-for-api-key-prefix-query- (premium-features/enable-advanced-permissions?))- [(api-key/prefix api-key)]))- (update :is-group-manager? boolean))]- (when (matching-api-key? user-data api-key)- (dissoc user-data :api-key)))))+ [api-key :- [:maybe :string]]+ (when (and api-key+ (init-status/complete?))+ ;; make sure the API key is valid before we entertain the idea of allowing it.+ (if-let [error (some-> (mr/explain ::api-keys.schema/key.raw api-key)+ me/humanize+ pr-str)]+ (do+ ;; 99% sure the error message is not going to include the API key but just to be extra super safe let's not log+ ;; it if the error message includes the key itself.+ (if (str/includes? error api-key)+ (log/error "Ignoring invalid API Key")+ (log/errorf "Ignoring invalid API Key: %s" error))+ nil)+ (let [user-info (-> (t2/query-one (cons (user-data-for-api-key-prefix-query+ (premium-features/enable-advanced-permissions?))+ [(api-key/prefix api-key)]))+ (m/update-existing :is-group-manager? boolean))]+ (when (matching-api-key? user-info api-key)+ (-> user-info+ (dissoc :api-key)))))))(defn- merge-current-user-info[{:keys [metabase-session-key anti-csrf-token], {:strs [x-metabase-locale x-api-key]} :headers, :as request}]diff --git a/src/metabase/util/malli/describe.cljc b/src/metabase/util/malli/describe.cljcindex f8713d57253..171b2e00586 100644--- a/src/metabase/util/malli/describe.cljc+++ b/src/metabase/util/malli/describe.cljc@@ -1,5 +1,6 @@(ns metabase.util.malli.describe- "This is exactly the same as [[malli.experimental.describe]], but handles our deferred i18n forms."+ "This is exactly the same as [[malli.experimental.describe]], but handles our deferred i18n forms, and uses our+ registry."(:require[clojure.string :as str][malli.core :as mc]diff --git a/src/metabase/util/secret.clj b/src/metabase/util/secret.cljindex bddca494f5e..cde059798ab 100644--- a/src/metabase/util/secret.clj+++ b/src/metabase/util/secret.clj@@ -1,29 +1,43 @@(ns metabase.util.secret(:require- [metabase.util.i18n :refer [trs]])- (:import (java.io Writer)))+ [metabase.util.i18n :refer [trs]]+ [metabase.util.malli.registry :as mr]+ [potemkin :as p]+ [pretty.core :as pretty]))(set! *warn-on-reflection* true)-;; Define a protocol for secrets to make things harder to accidentally expose.-(defprotocol ISecret+;; Define an interface for secrets to make things harder to accidentally expose.+;;+;; This uses `definterface` rather than `defprotocol` because [[secret?]] below only works correctly for classes that+;; implement it at definition time; making it an interface discourages people from thinking an object that you+;; `extend-protocol`-ed would work+(p/definterface+ ISecret(expose [this] "Expose the secret"))-(defrecord Secret [value-fn]+(p/deftype+ Secret [value-fn]ISecret(expose [_this] (value-fn))- Object- (toString [_this] (trs "<< REDACTED SECRET >>")))-(defmethod print-method Secret- [^Secret secret ^Writer writer]- (.write writer (.toString secret)))+ Object+ (toString [_this] (trs "<< REDACTED SECRET >>"))-(defmethod print-dup Secret- [^Secret secret ^Writer w]- (.write w (.toString secret)))+ pretty/PrettyPrintable+ (pretty [this]+ (.toString this)))(defn secret"Create a `Secret` that can't be accidentally read without calling the `expose` method on it."[value](->Secret (constantly value)))++(defn secret?+ "Whether `x` is an instance of a `Secret`."+ [x]+ (instance? metabase.util.secret.ISecret x))++(mr/def ::secret+ "An instance of a metabase.util.secret.ISecret."+ [:fn+ {:error/message "An instance of a metabase.util.secret.ISecret."}+ #'secret?])diff --git a/test/metabase/api_keys/api_test.clj b/test/metabase/api_keys/api_test.cljindex b6071f359c1..641e0e45f74 100644--- a/test/metabase/api_keys/api_test.clj+++ b/test/metabase/api_keys/api_test.clj@@ -1,13 +1,17 @@(ns metabase.api-keys.api-test"Tests for /api/api-key endpoints"(:require- [clojure.test :refer [deftest testing is]]+ [clojure.test :refer :all]+ [metabase.api-keys.core :as-alias api-keys][metabase.api-keys.models.api-key :as api-key][metabase.permissions.models.permissions-group :as perms-group][metabase.test :as mt]+ [metabase.test.fixtures :as fixtures][metabase.test.http-client :as client][toucan2.core :as t2]))+(use-fixtures :once (fixtures/initialize :db :test-users :web-server))+(deftest api-key-creation-test(mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}](testing "POST /api/api-key works"@@ -20,7 +24,10 @@(is (= (select-keys (mt/fetch-user :crowberto) [:id :common_name])(:updated_by resp)))(is (= {:name "Cool Friends" :id group-id} (:group resp)))- (is (= name (:name resp)))))+ (is (= name (:name resp)))))))++(deftest api-key-creation-test-2+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}](testing "Trying to create another API key with the same name fails"(let [key-name (str (random-uuid))];; works once...@@ -31,7 +38,10 @@(is (= {:errors {:name "An API key with this name already exists."}}(mt/user-http-request :crowberto :post 400 "api-key"{:group_id group-id- :name key-name})))))+ :name key-name})))))))++(deftest api-key-creation-test-3+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}](testing "API key generation is retried if a prefix collision occurs";; mock out the `api-key/generate-key` function to generate the same key (with the same prefix) repeatedly(let [generated-key (api-key/generate-key)@@ -44,35 +54,44 @@(swap! generated-keys next)next-val))];; put an API Key in the database with that key.- (mt/with-temp [:model/ApiKey _ {:unhashed_key generated-key- :name "my cool name"- :user_id (mt/user->id :crowberto)- :creator_id (mt/user->id :crowberto)- :updated_by_id (mt/user->id :crowberto)}]+ (mt/with-temp [:model/ApiKey _ {::api-keys/unhashed-key generated-key+ :name "my cool name"+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)}];; this will try to generate a new API key(mt/user-http-request :crowberto :post 200 "api-key"{:group_id group-id:name (str (random-uuid))});; we've exhausted the `generated-keys` we mocked- (is (empty? @generated-keys))))))+ (is (empty? @generated-keys))))))))++(deftest api-key-creation-test-4+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}](testing "We don't retry forever if prefix collision keeps happening"(let [generated-key (api-key/generate-key)](with-redefs [api-key/generate-key (constantly generated-key)]- (mt/with-temp [:model/ApiKey _ {:unhashed_key generated-key- :name "my cool name"- :user_id (mt/user->id :crowberto)- :creator_id (mt/user->id :crowberto)- :updated_by_id (mt/user->id :crowberto)}]+ (mt/with-temp [:model/ApiKey _ {::api-keys/unhashed-key generated-key+ :name "my cool name"+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)}](is (= "could not generate key with unique prefix"(:message (mt/user-http-request :crowberto :post 500 "api-key"{:group_id group-id- :name (str (random-uuid))}))))))))+ :name (str (random-uuid))}))))))))))++(deftest api-key-creation-test-5+ (testing "POST /api/api-key"(testing "A group is required"(is (= {:errors {:group_id "value must be an integer greater than zero."}:specific-errors {:group_id ["value must be an integer greater than zero., received: nil"]}}(mt/user-http-request :crowberto :post 400 "api-key"{:group_id nil- :name (str (random-uuid))}))))+ :name (str (random-uuid))}))))))++(deftest api-key-creation-test-6+ (testing "POST /api/api-key"(testing "The group can be 'All Users'"(is (mt/user-http-request :crowberto :post 200 "api-key"{:group_id (:id (perms-group/all-users))@@ -81,13 +100,19 @@(get-in (mt/user-http-request :crowberto :post 200 "api-key"{:group_id (:id (perms-group/all-users)):name (str (random-uuid))})- [:group :name]))))+ [:group :name]))))))++(deftest api-key-creation-test-7+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}](testing "A non-empty name is required"(is (= {:errors {:name "value must be a non-blank string."}:specific-errors {:name ["should be at least 1 character, received: \"\"" "non-blank string, received: \"\""]}}(mt/user-http-request :crowberto :post 400 "api-key"{:group_id group-id- :name ""}))))+ :name ""}))))))++(deftest api-key-creation-test-8+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}](testing "A non-blank name is required"(is (= {:errors {:name "value must be a non-blank string."}:specific-errors {:name ["non-blank string, received: \" \""]}}@@ -98,26 +123,25 @@(deftest api-count-works(mt/with-empty-h2-app-db!(is (zero? (mt/user-http-request :crowberto :get 200 "api-key/count")))- (mt/with-temp [:model/ApiKey _ {:unhashed_key (api-key/generate-key)- :name "my cool name"- :user_id (mt/user->id :crowberto)- :creator_id (mt/user->id :crowberto)- :updated_by_id (mt/user->id :crowberto)}]+ (mt/with-temp [:model/ApiKey _ {::api-keys/unhashed-key (api-key/generate-key)+ :name "my cool name"+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)}](is (= 1 (mt/user-http-request :crowberto :get 200 "api-key/count")))- (mt/with-temp [:model/ApiKey _ {:unhashed_key (api-key/generate-key)- :name "my cool OTHER name"- :user_id (mt/user->id :crowberto)- :creator_id (mt/user->id :crowberto)- :updated_by_id (mt/user->id :crowberto)}]+ (mt/with-temp [:model/ApiKey _ {::api-keys/unhashed-key (api-key/generate-key)+ :name "my cool OTHER name"+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)}](is (= 2 (mt/user-http-request :crowberto :get 200 "api-key/count"))))-(testing "API keys with non-default scopes, like SCIM, are excluded"- (mt/with-temp [:model/ApiKey _ {:unhashed_key (api-key/generate-key)- :name "my cool OTHER name"- :user_id (mt/user->id :crowberto)- :creator_id (mt/user->id :crowberto)- :updated_by_id (mt/user->id :crowberto)- :scope "scim"}]+ (mt/with-temp [:model/ApiKey _ {::api-keys/unhashed-key (api-key/generate-key)+ :name "my cool OTHER name"+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)+ :scope :scim}](is (= 1 (mt/user-http-request :crowberto :get 200 "api-key/count"))))))))(deftest api-keys-work-e2e@@ -146,8 +170,9 @@:post 200 "api-key"{:group_id group-id-1:name (str (random-uuid))})+ _ (assert (t2/exists? :model/ApiKey id))_ (is (= "Cool Friends" (-> create-resp :group :name)))- api-user-id (:id (:user (t2/hydrate (t2/select-one :model/ApiKey :id id) :user)))+ api-user-id (t2/select-one-fn :user_id :model/ApiKey :id id)member-of-group? (fn [group-id](t2/exists? :model/PermissionsGroupMembership:user_id api-user-id@@ -155,12 +180,15 @@(is (member-of-group? group-id-1))(is (not (member-of-group? group-id-2)))(testing "You can change the group of an API key"+ (is (=? {:group {:id group-id-2, :name "Uncool Friends"}}+ (mt/user-http-request :crowberto :put 200 (format "api-key/%s" id) {:group_id group-id-2})))(is (= "Uncool Friends"- (-> (mt/user-http-request :crowberto :put 200 (format "api-key/%s" id) {:group_id group-id-2})- :group- :name)))+ (t2/select-one-fn :name :model/PermissionsGroup group-id-2)))(is (not (member-of-group? group-id-1)))- (is (member-of-group? group-id-2))))+ (is (member-of-group? group-id-2))))))++(deftest api-keys-can-be-updated-2+ (mt/with-temp [:model/PermissionsGroup {group-id-1 :id} {:name "Cool Friends"}](testing "You can change the name of an API key"(let [name-1 (str "My First Name" (random-uuid))name-2 (str "My Second Name" (random-uuid))@@ -169,7 +197,6 @@{:group_id group-id-1:name name-1})api-user-id (-> (t2/select-one :model/ApiKey :id id) (t2/hydrate :user) :user :id)]-(testing "before the change..."(is (= name-1 (:common_name (t2/select-one :model/User api-user-id)))))(testing "after the change..."@@ -179,27 +206,37 @@(testing "the shape of the response is correct"(is (= #{:created_at :updated_at :updated_by :id :group :name :masked_key}(set (keys (mt/user-http-request :crowberto :put 200 (str "api-key/" id)- {:name name-1}))))))))- (testing "A nonexistent API Key can't be updated"- (mt/user-http-request :crowberto- :put 404 (format "api-key/%s/regenerate" (+ 13371337 (rand-int 100)))))))+ {:name name-1}))))))))))++(deftest api-keys-can-be-updated-3+ (testing "A nonexistent API Key can't be updated"+ (mt/user-http-request :crowberto :put 404 (format "api-key/%s/regenerate" (+ 13371337 (rand-int 100))))))(deftest api-keys-can-be-regenerated(testing "You can regenerate an API key"(mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}]- (let [{id :id old-key :unmasked_key}+ (let [{id :id old-key :unmasked_key, :as response}(mt/user-http-request :crowberto:post 200 "api-key"{:group_id group-id:name (str (random-uuid))})++ _ (is (=? {:id pos-int?}+ response))_ (is (client/client :get 200 "user/current" {:request-options {:headers {"x-api-key" old-key}}}))- {:as resp new-key :unmasked_key}++ {new-key :unmasked_key, :as response}(mt/user-http-request :crowberto:put 200 (format "api-key/%s/regenerate" id))]- (is (= #{:created_at :updated_at :id :name :unmasked_key :masked_key :group :updated_by}- (set (keys resp))))- (is (client/client :get 401 "user/current" {:request-options {:headers {"x-api-key" old-key}}}))- (is (client/client :get 200 "user/current" {:request-options {:headers {"x-api-key" new-key}}})))))+ (is (= #{:id :unmasked_key :masked_key :prefix}+ (cond-> response+ (map? response) (-> keys set))))+ (is (= "Unauthenticated"+ (client/client :get 401 "user/current" {:request-options {:headers {"x-api-key" old-key}}})))+ (is (=? {}+ (client/client :get 200 "user/current" {:request-options {:headers {"x-api-key" new-key}}})))))))++(deftest api-keys-can-be-regenerated-2(testing "A nonexistent API Key can't be regenerated"(mt/user-http-request :crowberto:put 404 (format "api-key/%s/regenerate" (+ 13371337 (rand-int 100))))))@@ -208,39 +245,35 @@(mt/with-empty-h2-app-db!(mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Cool Friends"}](is (= [] (mt/user-http-request :crowberto :get 200 "api-key")))-(mt/user-http-request :crowberto:post 200 "api-key"{:group_id group-id:name "My First API Key"})(is (= [{:name "My First API Key"- :group {:name "Cool Friends"- :id group-id}+ :group {:name "Cool Friends"+ :id group-id}:updated_by (select-keys (mt/fetch-user :crowberto) [:common_name :id])}](map #(select-keys % [:name :group :updated_by])(mt/user-http-request :crowberto :get 200 "api-key"))))-(mt/user-http-request :crowberto:post 200 "api-key"{:group_id (:id (perms-group/all-users))- :name "My Second API Key"})-- (is (= [{:name "My First API Key"+ :name "My Second API Key"})+ (is (= [{:name "My First API Key":group {:name "Cool Friends"- :id group-id}}- {:name "My Second API Key"+ :id group-id}}+ {:name "My Second API Key":group {:name "All Users"- :id (:id (perms-group/all-users))}}]+ :id (:id (perms-group/all-users))}}](map #(select-keys % [:name :group])(mt/user-http-request :crowberto :get 200 "api-key"))))-(testing "API keys with non-default scopes, like SCIM, are excluded"- (mt/with-temp [:model/ApiKey _ {:unhashed_key (api-key/generate-key)- :name "SCIM API key"- :user_id (mt/user->id :crowberto)- :creator_id (mt/user->id :crowberto)- :updated_by_id (mt/user->id :crowberto)- :scope "scim"}]+ (mt/with-temp [:model/ApiKey _ {::api-keys/unhashed-key (api-key/generate-key)+ :name "SCIM API key"+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)+ :scope :scim}](is (= 2 (count (mt/user-http-request :crowberto :get 200 "api-key")))))))))(deftest api-keys-can-be-deleted@@ -251,6 +284,7 @@:post 200 "api-key"{:group_id (:id (perms-group/all-users)):name "My First API Key"})]+ (assert (pos-int? id))(is (= 1 (count (mt/user-http-request :crowberto :get 200 "api-key"))))(is (= 1 (mt/user-http-request :crowberto :get 200 "api-key/count")))(mt/user-http-request :crowberto :delete 204 (format "api-key/%s" id))@@ -262,56 +296,97 @@(deftest api-key-operations-are-audit-logged(mt/with-premium-features #{:audit-app}(mt/with-empty-h2-app-db!- (mt/with-temp [:model/PermissionsGroup {group-id-1 :id} {:name "Cool Friends"}- :model/PermissionsGroup {group-id-2 :id} {:name "Less Cool Friends"}]+ (mt/with-temp [:model/PermissionsGroup {group-id-1 :id} {:name "Cool Friends"}];; create the API key- (let [{id :id- unmasked-key :unmasked_key} (mt/user-http-request :crowberto- :post 200 "api-key"- {:group_id group-id-1- :name "My API Key"})- old-prefix (api-key/prefix unmasked-key)- url (fn [url] (format url id))]+ (let [{id :id} (mt/user-http-request :crowberto+ :post 200 "api-key"+ {:group_id group-id-1+ :name "My API Key"})](testing "Creation was audit logged"- (is (=? {:details {:name "My API Key"- :group {:name "Cool Friends"}- :user_id (t2/select-one-fn :user_id :model/ApiKey id)}+ (is (=? {:details {:name "My API Key"+ :group {:name "Cool Friends"}+ :user_id (t2/select-one-fn :user_id :model/ApiKey id)}:model "ApiKey":model_id id:user_id (mt/user->id :crowberto)}(mt/latest-audit-log-entry :api-key-create id)))(is (= #{:name :group :key_prefix :user_id}- (-> (mt/latest-audit-log-entry :api-key-create id) :details keys set))))+ (-> (mt/latest-audit-log-entry :api-key-create id) :details keys set)))))))))++(deftest api-key-operations-are-audit-logged-2+ (mt/with-premium-features #{:audit-app}+ (mt/with-empty-h2-app-db!+ (mt/with-temp [:model/PermissionsGroup {group-id-1 :id} {:name "Cool Friends"}+ :model/PermissionsGroup {group-id-2 :id} {:name "Less Cool Friends"}]+ ;; create the API key+ (let [{id :id} (mt/user-http-request :crowberto+ :post 200 "api-key"+ {:group_id group-id-1+ :name "My API Key"})+ url (fn [url] (format url id))](testing "Update is audit logged"- (mt/user-http-request :crowberto- :put 200 (url "api-key/%s")- {:group_id group-id-2- :name "A New Name"})- (is (=? {:details {:previous {:name "My API Key"+ (is (=? {:id pos-int?}+ (mt/user-http-request :crowberto+ :put 200 (url "api-key/%s")+ {:group_id group-id-2+ :name "A New Name"})))+ (is (=? {:details {:previous {:name "My API Key":group {:name "Cool Friends"}}- :new {:name "A New Name"+ :new {:name "A New Name":group {:name "Less Cool Friends"}}}:model "ApiKey":model_id id:user_id (mt/user->id :crowberto)}- (mt/latest-audit-log-entry :api-key-update id))))+ (mt/latest-audit-log-entry :api-key-update id)))))))))++(deftest api-key-operations-are-audit-logged-3+ (mt/with-premium-features #{:audit-app}+ (mt/with-empty-h2-app-db!+ (mt/with-temp [:model/PermissionsGroup {group-id-1 :id} {:name "Cool Friends"}]+ ;; create the API key+ (let [{id :id+ unmasked-key :unmasked_key} (mt/user-http-request :crowberto+ :post 200 "api-key"+ {:group_id group-id-1+ :name "My API Key"})+ old-prefix (api-key/prefix unmasked-key)+ url (fn [url] (format url id))](testing "Regeneration is audit logged"- (let [{:keys [unmasked_key]}- (mt/user-http-request :crowberto- :put 200 (url "api-key/%s/regenerate"))- new-prefix (api-key/prefix unmasked_key)]+ (let [{unmasked-key :unmasked_key} (mt/user-http-request :crowberto :put 200 (url "api-key/%s/regenerate"))+ _ (assert (string? unmasked-key))+ new-prefix (api-key/prefix unmasked-key)](is (=? {:details {:previous {:key_prefix old-prefix}:new {:key_prefix new-prefix}}:model "ApiKey":model_id id:user_id (mt/user->id :crowberto)}- (mt/latest-audit-log-entry :api-key-regenerate id)))))+ (mt/latest-audit-log-entry :api-key-regenerate id))))))))))++(deftest api-key-operations-are-audit-logged-4+ (mt/with-premium-features #{:audit-app}+ (mt/with-empty-h2-app-db!+ (mt/with-temp [:model/PermissionsGroup {group-id-1 :id} {:name "Cool Friends"}]+ ;; create the API key+ (let [{id :id} (mt/user-http-request :crowberto+ :post 200 "api-key"+ {:group_id group-id-1+ :name "My API Key"})+ url (fn [url] (format url id))](testing "Deletion is audit logged"- (mt/user-http-request :crowberto- :delete 204 (url "api-key/%s"))- (is (=? {:details {:name "A New Name"- :group {:name "Less Cool Friends"}}+ (is (nil? (mt/user-http-request :crowberto+ :delete 204 (url "api-key/%s"))))+ (is (=? {:details {:name "My API Key"+ :group {:name "Cool Friends"}}:model "ApiKey":model_id id:user_id (mt/user->id :crowberto)}(mt/latest-audit-log-entry :api-key-delete id)))))))))++(deftest do-not-mark-user-inactive-when-deleting-api-key-for-normal-user-test+ (mt/with-temp [:model/ApiKey {api-key-id :id} {::api-keys/unhashed-key "mb_1234567890"+ :name (mt/random-name)+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)}]+ (is (nil? (mt/user-http-request :crowberto :delete 204 (format "api-key/%d" api-key-id))))+ (is (true? (t2/select-one-fn :is_active :model/User :id (mt/user->id :crowberto))))))diff --git a/test/metabase/api_keys/models/api_key_test.clj b/test/metabase/api_keys/models/api_key_test.cljnew file mode 100644index 00000000000..27a4bfa2bfc--- /dev/null+++ b/test/metabase/api_keys/models/api_key_test.clj@@ -0,0 +1,16 @@+(ns metabase.api-keys.models.api-key-test+ (:require+ [clojure.test :refer :all]+ [metabase.api-keys.core :as api-key]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(deftest do-not-mark-user-inactive-when-deleting-api-key-for-normal-user-test+ (mt/with-temp [:model/ApiKey {api-key-id :id} {::api-key/unhashed-key "mb_1234567890"+ :name (mt/random-name)+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)}]+ (is (= 1+ (t2/delete! :model/ApiKey api-key-id)))+ (is (true? (t2/select-one-fn :is_active :model/User :id (mt/user->id :crowberto))))))diff --git a/test/metabase/api_keys/schema_test.clj b/test/metabase/api_keys/schema_test.cljnew file mode 100644index 00000000000..e69de29bb2ddiff --git a/test/metabase/api_keys/schemas_test.clj b/test/metabase/api_keys/schemas_test.cljnew file mode 100644index 00000000000..e69de29bb2ddiff --git a/test/metabase/channel/email/messages_test.clj b/test/metabase/channel/email/messages_test.cljindex 059646dd739..91747183e07 100644--- a/test/metabase/channel/email/messages_test.clj+++ b/test/metabase/channel/email/messages_test.clj@@ -121,11 +121,11 @@(is (= 1 (count @mt/inbox))))))))(deftest all-admin-recipients- (mt/with-temp [:model/ApiKey _ {:unhashed_key (api-key/generate-key)- :name "Test API key"- :user_id (mt/user->id :crowberto)- :creator_id (mt/user->id :crowberto)- :updated_by_id (mt/user->id :crowberto)}]+ (mt/with-temp [:model/ApiKey _ {::api-key/unhashed-key (api-key/generate-key)+ :name "Test API key"+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :crowberto)+ :updated_by_id (mt/user->id :crowberto)}](testing "all-admin-recipients returns all admin emails"(let [emails (#'messages/all-admin-recipients)](is (some #(= % "[email protected]") emails))diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.cljindex b987154b54f..974c14399ce 100644--- a/test/metabase/server/middleware/session_test.clj+++ b/test/metabase/server/middleware/session_test.clj@@ -4,8 +4,10 @@[clojure.test :refer :all][environ.core :as env][java-time.api :as t]+ [metabase.api-keys.core :as api-key][metabase.api.common :refer [*current-user* *current-user-id* *is-group-manager?* *is-superuser?*]][metabase.app-db.core :as mdb]+ [metabase.config.core :as config][metabase.core.initialization-status :as init-status][metabase.driver.sql.query-processor :as sql.qp][metabase.premium-features.core :as premium-features]@@ -13,6 +15,7 @@[metabase.server.middleware.session :as mw.session][metabase.session.core :as session][metabase.test :as mt]+ [metabase.test.fixtures :as fixtures][metabase.util.i18n :as i18n][metabase.util.secret :as u.secret][ring.mock.request :as ring.mock]@@ -20,6 +23,8 @@(set! *warn-on-reflection* true)+(use-fixtures :once (fixtures/initialize :db :test-users :web-server))+(def ^:private session-cookie request/metabase-session-cookie)(def ^:private session-timeout-cookie request/metabase-session-timeout-cookie)@@ -103,36 +108,68 @@(select-keys (wrapped-handler request) [:anti-csrf-token :cookies :metabase-session-key :uri]))))))(deftest current-user-info-for-api-key-test- (mt/with-temp [:model/ApiKey _ {:name "An API Key"- :user_id (mt/user->id :lucky)- :creator_id (mt/user->id :lucky)- :updated_by_id (mt/user->id :lucky)- :unhashed_key (u.secret/secret "mb_foobar")}]+ (mt/with-temp [:model/ApiKey _ {:name "An API Key"+ :user_id (mt/user->id :lucky)+ :creator_id (mt/user->id :lucky)+ :updated_by_id (mt/user->id :lucky)+ ::api-key/unhashed-key (u.secret/secret "mb_foobar123")}](testing "A valid API key works, and user info is added to the request"- (let [req {:headers {"x-api-key" "mb_foobar"}}]- (is (= (merge req {:metabase-user-id (mt/user->id :lucky)- :is-superuser? false- :is-group-manager? false- :user-locale nil})- (#'mw.session/merge-current-user-info req)))))- (testing "Various invalid API keys do not modify the request"- (are [req] (= req (#'mw.session/merge-current-user-info req))- ;; a matching prefix, invalid key- {:headers {"x-api-key" "mb_fooby"}}-- ;; no matching prefix, invalid key- {:headers {"x-api-key" "abcde"}}-- ;; no key at all- {:headers {}})))-- (mt/with-temp [:model/ApiKey _ {:name "An API Key without an internal user"- :user_id nil- :creator_id (mt/user->id :lucky)- :updated_by_id (mt/user->id :lucky)- :unhashed_key (u.secret/secret "mb_foobar")}]+ (let [req {:headers {"x-api-key" "mb_foobar123"}}]+ (testing "No premium features, do not include :is-group-manager?"+ (mt/with-premium-features #{}+ (is (= (merge req {:metabase-user-id (mt/user->id :lucky)+ :is-superuser? false+ :user-locale nil})+ (#'mw.session/merge-current-user-info req)))))+ (testing "Include :is-group-manager? if we have EE + :advanced-permissions "+ (when config/ee-available?+ (mt/with-premium-features #{:advanced-permissions}+ (is (= (merge req {:metabase-user-id (mt/user->id :lucky)+ :is-superuser? false+ :is-group-manager? false+ :user-locale nil})+ (#'mw.session/merge-current-user-info req))))))))))++(deftest ^:parallel current-user-info-for-api-key-test-1b+ (testing "Various invalid API keys do not modify the request"+ (are [req] (= req (#'mw.session/merge-current-user-info req))+ ;; a matching prefix, invalid key+ {:headers {"x-api-key" "mb_fooby"}}++ ;; no matching prefix, invalid key+ {:headers {"x-api-key" "abcde"}}++ ;; no key at all+ {:headers {}})))++(deftest ^:parallel current-user-info-for-api-key-log-errors-test+ (testing "Log an error about invalid API keys"+ (mt/with-log-messages-for-level [messages [metabase.server.middleware.session :error]]+ (#'mw.session/merge-current-user-info {:headers {"x-api-key" "mb_fooby"}})+ (is (= [{:namespace 'metabase.server.middleware.session+ :level :error+ :e nil+ :message "Ignoring invalid API Key: [\"should be at least 12 characters\"]"}]+ (messages))))))++(deftest ^:parallel current-user-info-for-api-key-log-errors-test-2+ (testing "Do not include the key itself in the error message -- fall back to a generic error message"+ (mt/with-log-messages-for-level [messages [metabase.server.middleware.session :error]]+ (#'mw.session/merge-current-user-info {:headers {"x-api-key" "characters"}})+ (is (= [{:namespace 'metabase.server.middleware.session+ :level :error+ :e nil+ :message "Ignoring invalid API Key"}]+ (messages))))))++(deftest ^:parallel current-user-info-for-api-key-test-2+ (mt/with-temp [:model/ApiKey _ {:name "An API Key without an internal user"+ :user_id nil+ :creator_id (mt/user->id :lucky)+ :updated_by_id (mt/user->id :lucky)+ ::api-key/unhashed-key (u.secret/secret "mb_foobar123")}](testing "An API key without an internal user (e.g. a SCIM key) should not modify the request"- (let [req {:headers {"x-api-key" "mb_foobar"}}]+ (let [req {:headers {"x-api-key" "mb_foobar123"}}](is (= req (#'mw.session/merge-current-user-info req)))))))(defn- simple-auth-handler@@ -151,24 +188,24 @@identity(fn [e] (throw e)))))-(deftest user-data-is-correctly-bound-for-api-keys- (mt/with-temp [:model/ApiKey _ {:name "An API Key"- :user_id (mt/user->id :lucky)- :creator_id (mt/user->id :lucky)- :updated_by_id (mt/user->id :lucky)- :unhashed_key (u.secret/secret "mb_foobar")}- :model/ApiKey _ {:name "A superuser API Key"- :user_id (mt/user->id :crowberto)- :creator_id (mt/user->id :lucky)- :updated_by_id (mt/user->id :lucky)- :unhashed_key (u.secret/secret "mb_superuser")}]+(deftest ^:parallel user-data-is-correctly-bound-for-api-keys+ (mt/with-temp [:model/ApiKey _ {:name "An API Key"+ :user_id (mt/user->id :lucky)+ :creator_id (mt/user->id :lucky)+ :updated_by_id (mt/user->id :lucky)+ ::api-key/unhashed-key (u.secret/secret "mb_foobar123")}+ :model/ApiKey _ {:name "A superuser API Key"+ :user_id (mt/user->id :crowberto)+ :creator_id (mt/user->id :lucky)+ :updated_by_id (mt/user->id :lucky)+ ::api-key/unhashed-key (u.secret/secret "mb_superuser")}](testing "A valid API key works, and user info is added to the request"(is (= {:is-superuser? false:is-group-manager? false:user-id (mt/user->id :lucky):user {:id (mt/user->id :lucky):email (:email (mt/fetch-user :lucky))}}- (simple-auth-handler {:headers {"x-api-key" "mb_foobar"}}))))+ (simple-auth-handler {:headers {"x-api-key" "mb_foobar123"}}))))(testing "A superuser API key has `*is-superuser?*` bound correctly"(is (= {:is-superuser? true:is-group-manager? false@@ -326,13 +363,14 @@:user {:id (mt/user->id :rasta):email (:email (mt/fetch-user :rasta))}}(user-bound-handler- (request-with-user-id (mt/user->id :rasta))))))+ (request-with-user-id (mt/user->id :rasta)))))))+(deftest ^:parallel add-user-id-key-test-2(testing "with invalid user-id (not sure how this could ever happen, but lets test it anyways)"- (is (= {:user-id 0+ (is (= {:user-id Integer/MAX_VALUE:user {}}(user-bound-handler- (request-with-user-id 0))))))+ (request-with-user-id Integer/MAX_VALUE))))));;; ---------------------------------------------- with-current-user -------------------------------------------------