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
Treat API-key users consistently across user endpoints and attributes (#78976)
John Swanson418fbf1bf9b0
diff --git a/.clj-kondo/ratchets.edn b/.clj-kondo/ratchets.ednindex 06a0b7df6d6..65073e53d19 100644--- a/.clj-kondo/ratchets.edn+++ b/.clj-kondo/ratchets.edn@@ -15,7 +15,7 @@:deprecated-var 86:discouraged-java-method 4:discouraged-namespace 81- :discouraged-var 130+ :discouraged-var 131:duplicate-require 1:equals-true 1:main-without-gen-class 1@@ -27,7 +27,7 @@:metabase/namespace-name 4:metabase/prefer-with-dynamic-fn-redefs 28:metabase/test-helpers-use-non-thread-safe-functions 18- :metabase/validate-defendpoint-has-response-schema 440+ :metabase/validate-defendpoint-has-response-schema 439:metabase/validate-defendpoint-query-params-use-kebab-case 50:metabase/validate-defendpoint-route-uses-kebab-case 44:metabase/validate-deftest 10diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/user.cljindex a875d9f6aaa..08966ef65a8 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj@@ -24,13 +24,13 @@;;#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :put "/:id/attributes"- "Update the `login_attributes` for a User."+ "Update the `login_attributes` for a User. Only personal users can have attributes."[{:keys [id]} :- [:map[:id ms/PositiveInt]]_query-params{:keys [login_attributes]} :- [:map[:login_attributes {:optional true} [:maybe UserAttributes]]]]- (api/check-404 (t2/select-one :model/User :id id))+ (api/check-404 (t2/select-one :model/User :id id :type :personal))(pos? (t2/update! :model/User id {:login_attributes login_attributes})))(def ^:private max-login-attributes 5000)diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/user_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/user_test.cljindex 0f63446b534..eb934f10bb4 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/user_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/user_test.clj@@ -103,7 +103,12 @@[:model/User {id :id} {}](mt/user-http-request :crowberto :put 200 (format "mt/user/%d/attributes" id) {:login_attributes {"foo" "bar"}})(is (= {"foo" "bar"}- (t2/select-one-fn :login_attributes :model/User :id id)))))))+ (t2/select-one-fn :login_attributes :model/User :id id)))))+ (testing "404 for API-key pseudo-users; attributes cannot be set on them (UXW-4240)"+ (mt/with-temp [:model/User {id :id} {:type :api-key}]+ (is (= "Not found."+ (mt/user-http-request :crowberto :put 404 (format "mt/user/%d/attributes" id) {:login_attributes {"foo" "bar"}})))+ (is (nil? (t2/select-one-fn :login_attributes :model/User :id id)))))))(deftest attributes-endpoint-includes-jwt-attributes-test(testing "GET /api/mt/user/attributes includes keys from jwt_attributes"diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.cljindex ab54bded7f2..597a5a13d8f 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj@@ -323,6 +323,23 @@(run-venues-count-query)))(fails-without-token (run-venues-count-query))))))+(deftest e2e-api-key-user-attributes-ignored-test+ (testing (str "login_attributes stored on an API-key pseudo-user are not used for sandboxing (UXW-4240); the "+ "query should fail with a missing-attribute error rather than using the stored attributes")+ #_{:clj-kondo/ignore [:discouraged-var]}+ (mt/with-temp [:model/User {api-key-user-id :id} {:type :api-key}]+ ;; `:attributes` writes `login_attributes` straight to the app DB; attributes on API-key users can't be set+ ;; via the API but may exist in the wild+ (met/with-gtaps-for-user! api-key-user-id {:gtaps {:venues (venues-category-mbql-gtap-def)}+ :attributes {"cat" 50}}+ (is (= {"cat" "50"}+ (t2/select-one-fn :login_attributes :model/User :id api-key-user-id))+ "sanity check: the attributes really are stored on the API-key user's row")+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Query requires user attribute `cat`"+ (run-venues-count-query)))))))+(deftest e2e-test-3(mt/test-drivers (e2e-test-drivers)(testing (str "When processing a query that requires a user attribute and that user attribute isn't there, throw an "diff --git a/src/metabase/request/session.clj b/src/metabase/request/session.cljindex 06875441874..136228a4040 100644--- a/src/metabase/request/session.clj+++ b/src/metabase/request/session.clj@@ -10,12 +10,13 @@[toucan2.core :as t2]))(def ^:private current-user-fields- (into [:model/User] user/admin-or-self-visible-columns))+ ;; `:type` is needed so [[user/add-attributes]] can refuse to add attributes to non-personal (API-key/internal) users+ (into [:model/User :type] user/admin-or-self-visible-columns))(defn- find-user [user-id](when user-id- (-> (t2/select-one current-user-fields, :id user-id)- user/add-attributes)))+ (some-> (t2/select-one current-user-fields, :id user-id)+ user/add-attributes)))(def ^:private ^:dynamic *user-local-values-user-id*"User ID that we've previous bound [[*user-local-values*]] for. This exists so we can avoid rebinding it in recursivediff --git a/src/metabase/users/models/user.clj b/src/metabase/users/models/user.cljindex be16a8fd1b3..1c1a3c06464 100644--- a/src/metabase/users/models/user.clj+++ b/src/metabase/users/models/user.clj@@ -414,10 +414,14 @@(perms/add-user-to-groups! user-id to-add)))true))-(defn add-attributes- "Adds the `:attributes` key to a user."- [{:keys [login_attributes jwt_attributes] :as user}]- (assoc user :attributes (merge {} (tenants/login-attributes user) jwt_attributes login_attributes)))+(mu/defn add-attributes+ "Adds the `:attributes` key to a user. Only personal users carry attributes; for other user types (API-key, internal)+ this is always `{}`, so e.g. sandboxed queries made with an API key report a missing user attribute instead of+ reading attributes stored on the user row."+ [{:keys [login_attributes jwt_attributes] :as user} :- [:map [:type (into [:enum] allowed-user-types)]]]+ (assoc user :attributes (if (= (:type user) :personal)+ (merge {} (tenants/login-attributes user) jwt_attributes login_attributes)+ {})));;; Filtering usersdiff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.cljindex 52808aa3804..179eccf2f72 100644--- a/src/metabase/users_rest/api.clj+++ b/src/metabase/users_rest/api.clj@@ -25,6 +25,7 @@[metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms][throttle.core :as throttle][toucan2.core :as t2]))@@ -356,14 +357,62 @@:include-archived-items :exclude:permission-level :write})}))))-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to-;; use our API + we will need it when we make auto-TypeScript-signature generation happen-;;-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}-(api.macros/defendpoint :get "/current"+(mr/def ::user-permissions+ "Permission flags for the current user, used by the FE to decide which UI elements to show. The `can_access_*`,+ `is_data_analyst`, and `is_group_manager` flags are only included when `advanced-permissions` is enabled."+ [:map+ [:can_create_queries :boolean]+ [:can_create_native_queries :boolean]+ [:can_access_setting {:optional true} :boolean]+ [:can_access_subscription {:optional true} :boolean]+ [:can_access_monitoring {:optional true} :boolean]+ [:can_access_data_model {:optional true} :boolean]+ [:can_access_db_details {:optional true} :boolean]+ [:can_access_transforms {:optional true} :boolean]+ [:is_data_analyst {:optional true} :boolean]+ [:is_group_manager {:optional true} :boolean]])++(mr/def ::current-user-response+ "Response for `GET /api/user/current`."+ [:map+ [:id ms/PositiveInt]+ [:email ms/NonBlankString]+ [:first_name [:maybe :string]]+ [:last_name [:maybe :string]]+ [:common_name [:maybe :string]]+ [:date_joined :any]+ [:last_login [:maybe :any]]+ [:updated_at [:maybe :any]]+ [:first_login :any]+ [:is_superuser :boolean]+ [:is_data_analyst :boolean]+ [:is_qbnewb :boolean]+ [:is_active :boolean]+ [:is_installer :boolean]+ [:has_invited_second_user :boolean]+ [:has_question_and_dashboard :boolean]+ [:has_model :boolean]+ [:can_write_any_collection :boolean]+ [:sso_source [:maybe :keyword]]+ [:locale [:maybe :string]]+ [:tenant_id [:maybe ms/PositiveInt]]+ [:tenant_collection_id [:maybe ms/PositiveInt]]+ ;; nil for API-key users, who have no personal collection+ [:personal_collection_id [:maybe ms/PositiveInt]]+ [:group_ids [:set ms/PositiveInt]]+ [:login_attributes [:maybe [:map-of :string :any]]]+ [:jwt_attributes [:maybe [:map-of :string :any]]]+ [:attributes [:map-of :string :any]]+ [:permissions ::user-permissions]+ [:custom_homepage [:maybe [:map [:dashboard_id ms/PositiveInt]]]]])++(api.macros/defendpoint :get "/current" :- ::current-user-response"Fetch the current `User`."[](-> (api/check-404 @api/*current-user*)+ ;; `:type` is selected for the current user so attribute resolution can check it, but isn't part of this+ ;; endpoint's response+ (dissoc :type)(t2/hydrate :personal_collection_id :group_ids :is_installer :has_invited_second_user :tenant_collection_id)add-has-question-and-dashboardadd-first-login@@ -378,14 +427,15 @@;;#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :get "/:id"- "Fetch a `User`. You must be fetching yourself *or* be a superuser *or* a Group Manager."+ "Fetch a `User`. You must be fetching yourself *or* be a superuser *or* a Group Manager.+ Only personal users can be fetched this way; API-key users and the internal user 404."[{:keys [id]} :- [:map[:id ms/PositiveInt]]](try(users/check-self-or-superuser id)(catch clojure.lang.ExceptionInfo _e(perms/check-group-manager)))- (-> (api/check-404 (users/fetch-user :id id))+ (-> (api/check-404 (users/fetch-user :id id, :type :personal))(t2/hydrate :user_group_memberships)add-structured-attributes))@@ -463,7 +513,8 @@(api.macros/defendpoint :put "/:id""Update an existing, active `User`.Self or superusers can update user info and groups.- Group Managers can only add/remove users from groups they are manager of."+ Group Managers can only add/remove users from groups they are manager of.+ Only personal users can be updated this way; API-key users 404 (manage them via `/api/api-key` instead)."[{:keys [id]} :- [:map[:id ms/PositiveInt]]_query-params@@ -485,7 +536,7 @@(perms/check-group-manager)))(check-not-internal-user id);; only allow updates if the specified account is active- (api/let-404 [user-before-update (users/fetch-user :id id, :is_active true)]+ (api/let-404 [user-before-update (users/fetch-user :id id, :is_active true, :type :personal)];; Google/LDAP non-admin users can't change their email to prevent account hijacking(when (contains? body :email)(api/check-403 (valid-email-update? user-before-update email)))diff --git a/test/metabase/request/session_test.clj b/test/metabase/request/session_test.cljindex b03d60b99d0..231d652f23e 100644--- a/test/metabase/request/session_test.clj+++ b/test/metabase/request/session_test.clj@@ -40,3 +40,15 @@(is (= original i18n/*user-locale*))(is (= "French"(.getDisplayLanguage (i18n/user-locale)))))))))++(deftest ^:parallel current-user-attributes-test+ (testing "with-current-user resolves attributes for personal users"+ (mt/with-temp [:model/User {user-id :id} {:login_attributes {"cat" "50"}}]+ (request/with-current-user user-id+ (is (= {"cat" "50"}+ (:attributes @*current-user*))))))+ (testing "API-key pseudo-users get NO attributes, even if login_attributes are stored on their row (UXW-4240)"+ (mt/with-temp [:model/User {user-id :id} {:type :api-key+ :login_attributes {"cat" "50"}}]+ (request/with-current-user user-id+ (is (= {} (:attributes @*current-user*)))))))diff --git a/test/metabase/users/models/user_test.clj b/test/metabase/users/models/user_test.cljindex b7a8370e69b..0236e82bad6 100644--- a/test/metabase/users/models/user_test.clj+++ b/test/metabase/users/models/user_test.clj@@ -479,7 +479,7 @@(testing "add-attributes should add :attributes key with merged login attributes"(let [user {:login_attributes {"user_attr" "user_value"}:jwt_attributes {"jwt_attr" "jwt_value"}- :email "[email protected]"}+ :email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {"jwt_attr" "jwt_value""user_attr" "user_value"}@@ -488,7 +488,7 @@(deftest add-attributes-handles-nil-login-attributes-test(testing "add-attributes should handle nil login_attributes"- (let [user {:email "[email protected]"+ (let [user {:email "[email protected]", :type :personal:jwt_attributes {"jwt_attr" "jwt_value"}}result (user/add-attributes user)](is (= {"jwt_attr" "jwt_value"}@@ -498,7 +498,7 @@(testing "add-attributes should handle empty login_attributes"(let [user {:login_attributes {}:jwt_attributes {"jwt_attr" "jwt_value"}- :email "[email protected]"}+ :email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {"jwt_attr" "jwt_value"}(:attributes result))))))@@ -509,7 +509,7 @@"user_only" "user_val"}:jwt_attributes {"shared_key" "jwt_value""jwt_only" "jwt_val"}- :email "[email protected]"}+ :email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {"shared_key" "user_value""jwt_only" "jwt_val"@@ -519,7 +519,7 @@(deftest add-attributes-preserves-user-fields-test(testing "add-attributes should preserve all other user fields"(let [user {:id 123- :email "[email protected]"+ :email "[email protected]", :type :personal:first_name "John":last_name "Doe":jwt_attributes {"jwt_attr" "jwt_value"}@@ -538,7 +538,7 @@(testing "add-attributes should merge tenant attributes"(mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:login_attributes {"user_attr" "user_value"}- :email "[email protected]"}+ :email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {"tenant_attr" "tenant_value""user_attr" "user_value"}@@ -548,7 +548,7 @@(deftest add-attributes-tenant-handles-nil-login-attributes-test(testing "add-attributes with tenant attributes should handle nil login_attributes"(mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})]- (let [user {:email "[email protected]"}+ (let [user {:email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {"tenant_attr" "tenant_value"}(:attributes result)))))))@@ -557,7 +557,7 @@(testing "add-attributes with tenant attributes should handle empty login_attributes"(mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:login_attributes {}- :email "[email protected]"}+ :email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {"tenant_attr" "tenant_value"}(:attributes result)))))))@@ -566,7 +566,7 @@(testing "add-attributes should handle nil tenant attributes"(mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly nil)](let [user {:login_attributes {"user_attr" "user_value"}- :email "[email protected]"}+ :email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {"user_attr" "user_value"}(:attributes result)))))))@@ -574,18 +574,34 @@(deftest add-attributes-handles-both-nil-tenant-and-user-attributes-test(testing "add-attributes should handle both nil tenant and user attributes"(mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly nil)]- (let [user {:email "[email protected]"}+ (let [user {:email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {}(:attributes result)))))))+(deftest add-attributes-only-personal-users-test+ (testing "add-attributes gives non-personal users NO attributes, even with stored login_attributes (UXW-4240)"+ (mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})]+ (doseq [user-type [:api-key :internal]]+ (testing user-type+ (is (= {}+ (:attributes (user/add-attributes {:email "[email protected]"+ :type user-type+ :login_attributes {"user_attr" "user_value"}+ :jwt_attributes {"jwt_attr" "jwt_value"}}))))))+ (testing "throws (in dev) when :type is missing from the user map, so callers can't forget to select it"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo+ #"Invalid input"+ (user/add-attributes {:email "[email protected]"+ :login_attributes {"user_attr" "user_value"}})))))))+(deftest add-attributes-user-overrides-tenant-test(testing "add-attributes: user attributes should override tenant attributes with same keys"(mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"shared_key" "tenant_value""tenant_only" "tenant_val"})](let [user {:login_attributes {"shared_key" "user_value""user_only" "user_val"}- :email "[email protected]"}+ :email "[email protected]", :type :personal}result (user/add-attributes user)](is (= {"shared_key" "user_value""tenant_only" "tenant_val"@@ -596,7 +612,7 @@(testing "add-attributes with tenant attributes should preserve all other user fields"(mt/with-dynamic-fn-redefs [tenants/login-attributes (constantly {"tenant_attr" "tenant_value"})](let [user {:id 123- :email "[email protected]"+ :email "[email protected]", :type :personal:first_name "John":last_name "Doe":login_attributes {"user_attr" "user_value"}}diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.cljindex 8fcd3648077..3bb0255dcad 100644--- a/test/metabase/users_rest/api_test.clj+++ b/test/metabase/users_rest/api_test.clj@@ -620,6 +620,16 @@:common_name "Rasta Toucan"}resp)))))))+(deftest ^:parallel get-user-non-personal-users-test+ (testing "GET /api/user/:id"+ (testing "returns 404 for API-key pseudo-users, even for admins (UXW-4240)"+ (mt/with-temp [:model/User {api-key-user-id :id} {:type :api-key}]+ (is (= "Not found."+ (mt/user-http-request :crowberto :get 404 (str "user/" api-key-user-id))))))+ (testing "returns 404 for the internal user"+ (is (= "Not found."+ (mt/user-http-request :crowberto :get 404 (str "user/" config/internal-mb-user-id)))))))+(deftest get-user-structured-attributes-test(testing "GET /api/user/:id"(testing "includes structured_attributes that tracks attribute provenance"@@ -724,6 +734,19 @@(is (= {:role {:source "user" :frozen false :value "user"}}(:structured_attributes get-response))))))))))+(deftest ^:parallel update-api-key-user-test+ (testing "PUT /api/user/:id"+ (testing "returns 404 for API-key pseudo-users, so login_attributes etc. cannot be set on them (UXW-4240)"+ (mt/with-temp [:model/User {api-key-user-id :id} {:type :api-key}]+ (is (= "Not found."+ (mt/user-http-request :crowberto :put 404 (str "user/" api-key-user-id)+ {:login_attributes {"cat" 50}+ :first_name "Updated"})))+ (testing "nothing was updated"+ (is (=? {:login_attributes nil+ :first_name (comp not #{"Updated"})}+ (t2/select-one [:model/User :login_attributes :first_name] :id api-key-user-id))))))))+(deftest combine-function-test(testing "combine function merges attributes correctly"(testing "basic merging"