Skip to content

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

Store passwords and reset tokens in auth_identity (#80718)

Alexander Polyankin4a7f73029a6f
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index a6c59259871..f20005709e4 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -2264,7 +2264,7 @@
setup
system
util}
- :model-imports #{:model/AuthIdentity :model/User}}
+ :model-imports #{:model/User}}
slackbot
{:team "Metabot"
@@ -2696,6 +2696,7 @@
metabase.users.settings}
:uses #{analytics
api
+ auth-identity
batch-processing
channel
config
@@ -2711,11 +2712,9 @@
util
enterprise/advanced-permissions}
:model-exports #{:model/User :model/UserParameterValue}
- :model-imports #{:model/AuthIdentity
- :model/Dashboard
+ :model-imports #{:model/Dashboard
:model/Database
:model/PermissionsGroupMembership
- :model/Session
:model/Tenant}}
users-rest
@@ -2737,8 +2736,7 @@
users
util
enterprise/advanced-permissions}
- :model-imports #{:model/AuthIdentity
- :model/Card
+ :model-imports #{:model/Card
:model/Collection
:model/Dashboard
:model/LoginHistory
@@ -2972,6 +2970,7 @@
:uses #{api
api-keys
app-db
+ auth-identity
driver
lib
permissions
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/file/users.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/file/users.clj
index 60170de64dc..70e9771116c 100644
--- a/enterprise/backend/src/metabase_enterprise/advanced_config/file/users.clj
+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/file/users.clj
@@ -3,6 +3,7 @@
[clojure.spec.alpha :as s]
[metabase-enterprise.advanced-config.file.interface
:as advanced-config.file.i]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.setup.core :as setup]
[metabase.users.models.user :as user]
[metabase.util :as u]
@@ -37,18 +38,26 @@
(defn- init-from-config-file!
[user]
- (if-let [existing-user (select-user (:email user))]
- (do
- (log/info (u/format-color :blue "Updating User %d" (:id existing-user)))
- (let [new-user (update user :login_attributes
- #(merge % (:login_attributes existing-user)))]
- (t2/update! :model/User (:id existing-user) new-user)))
- ;; create a new user. If they are the first non-internal User, force them to be an admin.
- (let [user (cond-> user
- (not (setup/has-user-setup)) (assoc :is_superuser true))]
- (log/info (u/colorize :green "Creating the first User for this instance. The first user is always created as an admin."))
- (log/info (u/colorize :green "Creating new User"))
- (t2/insert! :model/User user))))
+ ;; the profile write and the password write must land together — initialize! runs no transaction of its own
+ (t2/with-transaction [_]
+ (let [password (:password user)
+ ;; the password is stored only via set-password!; never hand it to the User model
+ user (dissoc user :password)
+ user-id (if-let [existing-user (select-user (:email user))]
+ (do
+ (log/info (u/format-color :blue "Updating User %d" (:id existing-user)))
+ (let [new-user (update user :login_attributes
+ #(merge % (:login_attributes existing-user)))]
+ (t2/update! :model/User (:id existing-user) new-user))
+ (:id existing-user))
+ ;; create a new user. If they are the first non-internal User, force them to be an admin.
+ (let [user (cond-> user
+ (not (setup/has-user-setup)) (assoc :is_superuser true))]
+ (log/info (u/colorize :green "Creating the first User for this instance. The first user is always created as an admin."))
+ (log/info (u/colorize :green "Creating new User"))
+ (u/the-id (t2/insert-returning-instance! :model/User user))))]
+ ;; passwords live in the AuthIdentity, not on the User row
+ (auth-identity/set-password! user-id password))))
(defmethod advanced-config.file.i/initialize-section! :users
[_section-name users]
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj
index 1b97cea3e57..61eb79dd276 100644
--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj
@@ -32,7 +32,6 @@
{:email (sag.settings/support-access-grant-email)
:first_name (sag.settings/support-access-grant-first-name)
:last_name (sag.settings/support-access-grant-last-name)
- :password (str (random-uuid))
:is_superuser true})))
(methodical/defmethod t2/batched-hydrate [:model/SupportAccessGrantLog :user_info]
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj
index 6d0effc2296..ac359190da6 100644
--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj
@@ -105,7 +105,5 @@
(:id user) grant-ends-at)
(t2/with-transaction [_]
(t2/update! :model/AuthIdentity (:id auth-identity) (auth-identity/mark-token-consumed auth-identity))
- (t2/update! :model/AuthIdentity :user_id (:id user) :provider "password"
- {:expires_at grant-ends-at
- :credentials {:plaintext_password password}}))))
+ (auth-identity/set-password! (:id user) password {:expires-at grant-ends-at}))))
result)
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj
index 488c4dd7d4b..2d74ebaff63 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/users_test.clj
@@ -34,8 +34,11 @@
(is (= 1
(t2/count :model/User :email "[email protected]"))))
(testing "upsert if User already exists, with merged login attributes"
- (let [hashed-password (fn [] (t2/select-one-fn :password :model/User :email "[email protected]"))
- salt (fn [] (t2/select-one-fn :password_salt :model/User :email "[email protected]"))
+ (let [pw-credentials (fn [] (t2/select-one-fn :credentials :model/AuthIdentity
+ :user_id (t2/select-one-pk :model/User :email "[email protected]")
+ :provider "password"))
+ hashed-password (fn [] (:password_hash (pw-credentials)))
+ salt (fn [] (:password_salt (pw-credentials)))
original-hashed-password (hashed-password)]
(is (= :ok
(advanced-config.file/initialize!
@@ -117,13 +120,15 @@
:password "{{env USER_PASSWORD}}"}]}}
{:expand-templates? true})))
- (let [user (t2/select-one [:model/User :first_name :last_name :email :password_salt :password]
- :email "[email protected]")]
+ (let [user (t2/select-one [:model/User :id :first_name :last_name :email]
+ :email "[email protected]")
+ {:keys [password_hash password_salt]} (t2/select-one-fn :credentials :model/AuthIdentity
+ :user_id (:id user) :provider "password")]
(is (partial= {:first_name "Cam"
:last_name "Era"
user))
- (is (u.password/verify-password "1234cans" (:password_salt user) (:password user))))))
+ (is (u.password/verify-password "1234cans" password_salt password_hash)))))
(finally
(t2/delete! :model/User :email "[email protected]")))))
diff --git a/enterprise/backend/test/metabase_enterprise/mfa/enrollment_flow_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/enrollment_flow_test.clj
index 6a62878bff8..fdf17ea8558 100644
--- a/enterprise/backend/test/metabase_enterprise/mfa/enrollment_flow_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/mfa/enrollment_flow_test.clj
@@ -4,6 +4,7 @@
[clojure.test :refer :all]
[metabase-enterprise.mfa.management :as mfa.management]
[metabase-enterprise.mfa.totp :as totp]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.sso.core :as sso]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -25,7 +26,8 @@
"Temp password user + a real session from a normal (not-yet-enrolled) login."
[[session-binding email-binding password-binding] & body]
`(let [~password-binding (str "Pw-" (random-uuid))]
- (mt/with-temp [:model/User {~'_user-id :id, ~email-binding :email} {:password ~password-binding}]
+ (mt/with-temp [:model/User {user-id# :id, ~email-binding :email} {}]
+ (auth-identity/set-password! user-id# ~password-binding)
(let [~session-binding (:id (mt/client :post 200 "session" {:username ~email-binding
:password ~password-binding}))]
~@body))))
diff --git a/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj
index 4a17d0bbef6..a2acbdfc008 100644
--- a/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/mfa/login_flow_test.clj
@@ -217,7 +217,7 @@
(deftest password-reset-issues-no-session-test
(mt/with-premium-features #{:multi-factor-auth}
(mt/with-temporary-setting-values [mfa-enforcement :optional]
- (mt/with-temp [:model/User {user-id :id, email :email} {:password (str "Old-" (random-uuid))}]
+ (mt/with-temp [:model/User {user-id :id, email :email} {}]
(try
(t2/insert! :model/AuthIdentity {:user_id user-id
:provider "totp"
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj
index e88776c8189..656f1bf0133 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj
@@ -5,6 +5,7 @@
[clojure.test :refer :all]
[metabase-enterprise.sandbox.test-util :as mt.tu]
[metabase-enterprise.test :as met]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.test :as mt]
[metabase.warehouse-schema.models.field-values :as field-values]
[toucan2.core :as t2]))
@@ -83,7 +84,8 @@
(fetch-values :rasta :name))))
(testing "A User with a *different* sandbox should see their own values"
(let [password (mt/random-name)]
- (mt/with-temp [:model/User another-user {:password password}]
+ (mt/with-temp [:model/User another-user]
+ (auth-identity/set-password! (:id another-user) password)
(met/with-gtaps-for-user! another-user {:gtaps {:venues
{:remappings
{:cat
@@ -155,7 +157,8 @@
:type :advanced)))))
(testing "Do different users has different sandbox FieldValues"
(let [password (mt/random-name)]
- (mt/with-temp [:model/User another-user {:password password}]
+ (mt/with-temp [:model/User another-user]
+ (auth-identity/set-password! (:id another-user) password)
(met/with-gtaps-for-user! another-user {:gtaps {:venues
{:remappings {:cat [:variable [:field (mt/id :venues :category_id) nil]]}
:query (mt.tu/restricted-column-query (mt/id))}}
diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj
index a749c4ae731..b0c51773f5f 100644
--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj
@@ -4,6 +4,7 @@
[clojure.test :refer :all]
[java-time.api :as t]
[metabase-enterprise.support-access-grants.models.support-access-grant-log :as sag-log]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.test :as mt]
[toucan2.core :as t2]))
@@ -15,6 +16,7 @@
(mt/with-temp-env-var-value! [:mb-support-access-grant-email "[email protected]"]
(let [support-user (sag-log/fetch-or-create-support-user!)
support-user-id (:id support-user)]
+ (auth-identity/set-password! support-user-id "test-password")
(mt/with-temp [:model/User {grant-creator-id :id} {}
:model/SupportAccessGrantLog {grant-id :id}
{:user_id grant-creator-id
@@ -40,6 +42,7 @@
(mt/with-model-cleanup [:model/User]
(let [support-user (sag-log/fetch-or-create-support-user!)
support-user-id (:id support-user)]
+ (auth-identity/set-password! support-user-id "test-password")
(mt/with-temp [:model/User {grant-creator-id :id} {}
:model/User {other-user-id :id} {}
:model/SupportAccessGrantLog {grant-id :id}
@@ -48,24 +51,30 @@
:notes "Test grant"
:grant_start_timestamp (t/offset-date-time)
:grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
- :revoked_at nil}
- :model/Session {support-session-id :id}
- {:id "test-id-0"
- :user_id support-user-id
- :session_key "test1"
- :auth_identity_id (t2/select-one-pk :model/AuthIdentity :user_id support-user-id)}
- :model/Session {other-session-id :id}
- {:id "test-id-1"
- :user_id other-user-id
- :session_key "test2"
- :auth_identity_id (t2/select-one-pk :model/AuthIdentity :user_id other-user-id)}]
- (let [revoked-timestamp (t/offset-date-time)]
- (t2/update! :model/SupportAccessGrantLog grant-id {:revoked_at revoked-timestamp})
- (is (nil? (t2/select-one :model/Session :id support-session-id))
- "Support user session should be deleted")
- (is (some? (t2/select-one :model/Session :id other-session-id))
- "Other user session should remain")
- (is (some? (:expires_at (t2/select-one :model/AuthIdentity :user_id support-user-id)))
- "Support user auth identity should have expires_at set")
- (is (nil? (:expires_at (t2/select-one :model/AuthIdentity :user_id other-user-id)))
- "Other user auth identity should remain unchanged"))))))))
+ :revoked_at nil}]
+ (auth-identity/set-password! other-user-id "test-password")
+ (mt/with-temp [:model/Session {support-session-id :id}
+ {:id "test-id-0"
+ :user_id support-user-id
+ :session_key "test1"
+ :auth_identity_id (t2/select-one-pk :model/AuthIdentity
+ :user_id support-user-id
+ :provider "password")}
+ :model/Session {other-session-id :id}
+ {:id "test-id-1"
+ :user_id other-user-id
+ :session_key "test2"
+ :auth_identity_id (t2/select-one-pk :model/AuthIdentity
+ :user_id other-user-id
+ :provider "password")}]
+ (let [revoked-timestamp (t/offset-date-time)]
+ (t2/update! :model/SupportAccessGrantLog grant-id {:revoked_at revoked-timestamp})
+ (is (nil? (t2/select-one :model/Session :id support-session-id))
+ "Support user session should be deleted")
+ (is (some? (t2/select-one :model/Session :id other-session-id))
+ "Other user session should remain")
+ (is (some? (:expires_at (t2/select-one :model/AuthIdentity
+ :user_id support-user-id :provider "password")))
+ "Support user auth identity should have expires_at set")
+ (is (nil? (:expires_at (t2/select-one :model/AuthIdentity :user_id other-user-id :provider "password")))
+ "Other user auth identity should remain unchanged")))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/provider_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/provider_test.clj
index e22e98ae6f0..35f6aed000e 100644
--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/provider_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/provider_test.clj
@@ -6,6 +6,7 @@
[metabase-enterprise.support-access-grants.provider :as sag.provider]
[metabase.auth-identity.provider :as provider]
[metabase.test :as mt]
+ [metabase.util.password :as u.password]
[toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -103,13 +104,15 @@
new-password "new-secure-password-123"]
(provider/login! :provider/support-access-grant {:token token
:password new-password})
- (let [updated-user (t2/select-one [:model/User :password] :id user-id)
- updated-pw-auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
+ (let [updated-pw-auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
updated-auth-identity (t2/select-one :model/AuthIdentity :id (:id auth-identity) :provider "support-access-grant")
session (t2/select-one :model/Session :auth_identity_id (:id updated-auth-identity))]
(is (some? (:expires_at session)))
(is (= grant-end (:expires_at updated-pw-auth-identity)))
- (is (= (get-in updated-pw-auth-identity [:credentials :password_hash]) (:password updated-user)))
+ (is (u.password/verify-password new-password
+ (get-in updated-pw-auth-identity [:credentials :password_salt])
+ (get-in updated-pw-auth-identity [:credentials :password_hash]))
+ "the new password is stored on the password AuthIdentity and verifies")
(is (some? (get-in updated-auth-identity [:credentials :consumed_at]))))))))
(deftest support-access-authenticate-inherits-from-emailed-secret-test
diff --git a/src/metabase/api_keys/models/api_key.clj b/src/metabase/api_keys/models/api_key.clj
index a364fafce19..5e48b254493 100644
--- a/src/metabase/api_keys/models/api_key.clj
+++ b/src/metabase/api_keys/models/api_key.clj
@@ -216,8 +216,7 @@
{:email email
:first_name key-name
:last_name ""
- :type :api-key
- :password (str (random-uuid))})]
+ :type :api-key})]
(when group-id
(user/set-permissions-groups! user-id [(perms/all-users-group) group-id]))
(-> (t2/insert-returning-instance! :model/ApiKey
diff --git a/src/metabase/auth_identity/core.clj b/src/metabase/auth_identity/core.clj
index 8a6c7f8e32a..2633be0472d 100644
--- a/src/metabase/auth_identity/core.clj
+++ b/src/metabase/auth_identity/core.clj
@@ -11,7 +11,9 @@
;; Import model query functions
(p/import-vars
[auth-identity
- hash-password-credentials])
+ hash-password-credentials
+ set-password!
+ reset-token-hash])
;; ==============================================================================
;; Provider Multimethod System
diff --git a/src/metabase/auth_identity/models/auth_identity.clj b/src/metabase/auth_identity/models/auth_identity.clj
index b684a5f10f3..5acb2c55330 100644
--- a/src/metabase/auth_identity/models/auth_identity.clj
+++ b/src/metabase/auth_identity/models/auth_identity.clj
@@ -6,7 +6,8 @@
[metabase.auth-identity.provider :as provider]
[metabase.models.interface :as mi]
[metabase.util :as u]
- [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.schema :as ms]
[metabase.util.password :as u.password]
[methodical.core :as methodical]
[toucan2.core :as t2]))
@@ -75,8 +76,11 @@
(t2/define-before-insert :model/AuthIdentity
[{:keys [provider] :as auth-identity}]
- (provider/validate (provider/provider-string->keyword provider) auth-identity)
- auth-identity)
+ (u/prog1 (cond-> auth-identity
+ (and (= provider "password")
+ (contains? auth-identity :credentials))
+ (update :credentials hash-password-credentials))
+ (provider/validate (provider/provider-string->keyword provider) <>)))
(t2/define-before-update :model/AuthIdentity
[{:keys [provider] :as auth-identity}]
@@ -86,50 +90,46 @@
(update :credentials hash-password-credentials))
(provider/validate (provider/provider-string->keyword provider) <>)))
-(t2/define-after-insert :model/AuthIdentity
- [{:keys [user_id provider credentials] :as auth-identity}]
- (when (= provider "emailed-secret-password-reset")
- (let [{:keys [token_hash expires_at consumed_at]} credentials]
- ;; Only sync to User if token is not consumed
- (when-not consumed_at
- (log/debugf "Syncing emailed-secret-password-reset AuthIdentity insert to User %s" user_id)
- ;; Calculate reset_triggered from expires_at (work backward from expiration)
- (let [ttl-ms (* 48 60 60 1000) ; 48 hours in milliseconds
- reset-triggered (-> (t/instant expires_at)
- (t/minus (t/millis ttl-ms))
- t/to-millis-from-epoch)]
- (t2/update! :model/User user_id
- {:reset_token token_hash
- :reset_triggered reset-triggered})))))
- auth-identity)
-
-(t2/define-after-update :model/AuthIdentity
- [{:keys [user_id provider credentials] :as auth-identity}]
- (cond
- ;; Handle password provider - sync to User table
- (= provider "password")
- (let [{:keys [password_hash password_salt]} credentials]
- (when (and password_hash password_salt)
- (t2/update! :model/User user_id
- {:password password_hash
- :password_salt password_salt})))
-
- ;; Handle emailed-secret-password-reset provider - sync reset tokens to User table
- (= provider "emailed-secret-password-reset")
- (let [{:keys [token_hash expires_at consumed_at]} credentials]
- (log/debugf "Syncing emailed-secret-password-reset AuthIdentity update to User %s" user_id)
- (if consumed_at
- ;; Token consumed - clear User table
- (t2/update! :model/User
- {:id user_id
- :reset_token [:not= nil]}
- {:reset_token nil
- :reset_triggered nil})
- ;; Token updated - sync to User table
- (let [ttl-ms (* 48 60 60 1000)
- reset-triggered (t/to-millis-from-epoch (t/minus expires_at (t/millis ttl-ms)))]
- (t2/update! :model/User
- {:id user_id}
- {:reset_token token_hash
- :reset_triggered reset-triggered})))))
- auth-identity)
+(mu/defn set-password!
+ "Set `user-id`'s login password to plaintext `password`, creating or replacing their `password` AuthIdentity — the
+ authoritative credential store. This is the only supported way to set a user's password; the User model itself no
+ longer stores, hashes, or mirrors passwords.
+
+ Always deletes the user's existing sessions: changing a password must invalidate every session authenticated with the
+ old one. A caller that wants the acting user to stay logged in should create a fresh session afterward.
+
+ Also deletes the user's `emailed-secret-password-reset` AuthIdentity: this is called by the password-reset flow, so
+ once the password has been set the reset token must stop working — otherwise it could be replayed to reset the
+ password again until it expires.
+
+ `opts` may contain `:expires-at`, an instant after which the credential is no longer valid (used by time-limited
+ support-access grants)."
+ ([user-id :- ms/PositiveInt
+ password :- ms/NonBlankString]
+ (set-password! user-id password nil))
+
+ ([user-id :- ms/PositiveInt
+ password :- ms/NonBlankString
+ opts :- [:maybe
+ [:map
+ [:expires-at {:optional true} [:maybe (ms/InstanceOfClass java.time.temporal.Temporal)]]]]]
+ ;; always write :expires_at (nil unless an expiry was requested) so setting a password clears any stale expiry a
+ ;; prior support-access grant left behind — otherwise `authenticate` would reject the new password as expired
+ ;; the credential write and the session delete must be atomic: if either fails the password must not change while
+ ;; sessions authenticated with the old one survive
+ (t2/with-transaction [_]
+ (let [attrs {:credentials {:plaintext_password password}
+ :expires_at (:expires-at opts)}]
+ (if-let [pw-auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")]
+ (t2/update! :model/AuthIdentity (u/the-id pw-auth-identity) attrs)
+ (t2/insert! :model/AuthIdentity (merge {:user_id user-id, :provider "password"} attrs))))
+ (t2/delete! :model/AuthIdentity :user_id user-id :provider "emailed-secret-password-reset")
+ (t2/delete! :model/Session :user_id user-id))))
+
+(mu/defn reset-token-hash :- [:maybe :string]
+ "The bcrypt hash of `user-id`'s current password-reset token, taken from their `emailed-secret-password-reset`
+ AuthIdentity (the authoritative store), or nil if they have none. Lets callers include the token in audit events
+ without reading the legacy `core_user.reset_token` column."
+ [user-id :- ms/PositiveInt]
+ (get-in (t2/select-one :model/AuthIdentity :user_id user-id :provider "emailed-secret-password-reset")
+ [:credentials :token_hash]))
diff --git a/src/metabase/auth_identity/providers/emailed_secret.clj b/src/metabase/auth_identity/providers/emailed_secret.clj
index 78b5622350d..39676ae040d 100644
--- a/src/metabase/auth_identity/providers/emailed_secret.clj
+++ b/src/metabase/auth_identity/providers/emailed_secret.clj
@@ -2,6 +2,7 @@
"Provider for emailed secret tokens (password reset, email verification, magic links)."
(:require
[java-time.api :as t]
+ [metabase.auth-identity.models.auth-identity :as auth-identity]
[metabase.auth-identity.provider :as provider]
[metabase.channel.email.messages :as messages]
[metabase.events.core :as events]
@@ -182,16 +183,12 @@
After a successful password reset authentication, this method:
- Publishes a password reset event or sends admin notification (for new users)
- - Marks the reset token as consumed in the [[AuthIdentity]]
- - Updates the user's password
-
- All operations are performed within a transaction to ensure consistency."
- [_provider {:keys [user password auth-identity] :as result}]
+ - Updates the user's password, which also removes the now-used reset token (see
+ [[metabase.auth-identity.core/set-password!]])."
+ [_provider {:keys [user password] :as result}]
(when (:success? result)
(if (:last_login user)
- (events/publish-event! :event/password-reset-successful {:object (assoc user :token (t2/select-one-fn :reset_token :model/User (:id user)))})
+ (events/publish-event! :event/password-reset-successful {:object (assoc user :token (auth-identity/reset-token-hash (:id user)))})
(messages/send-user-joined-admin-notification-email! (t2/select-one :model/User (:id user))))
- (t2/with-transaction [_]
- (t2/update! :model/AuthIdentity (:id auth-identity) (mark-token-consumed auth-identity))
- (t2/update! :model/User (:id user) {:password password})))
+ (auth-identity/set-password! (:id user) password))
result)
diff --git a/src/metabase/auth_identity/session.clj b/src/metabase/auth_identity/session.clj
index 7d711c39460..3653da6abce 100644
--- a/src/metabase/auth_identity/session.clj
+++ b/src/metabase/auth_identity/session.clj
@@ -13,7 +13,11 @@
(set! *warn-on-reflection* true)
(mu/defn create-session-with-auth-tracking!
- "Create a new Session for a User and update the last_used_at timestamp on the corresponding AuthIdentity."
+ "Create a new Session for a User and update the last_used_at timestamp on the corresponding AuthIdentity.
+
+ The session row and its `login_history` row are written in one transaction: `login_history.session_id` has a foreign
+ key to `core_session`, so a concurrent session delete (e.g. a password change, which invalidates the user's sessions)
+ must not be able to remove the freshly-created session between the two inserts and break that reference."
[user device-info provider]
(let [user-id (u/the-id user)
provider-str (name provider)
@@ -23,19 +27,20 @@
auth-identity-id (:id auth-identity)
session-key (str (random-uuid))
session-id (string/random-string 12)
- session (t2/insert-returning-instance! :model/Session
- ;; Without setting the ID here we can't return an instance
- ;; on MySQL
- :id session-id
- :user_id user-id
- :auth_identity_id auth-identity-id
- :session_key session-key
- :expires_at (:expires_at auth-identity))]
- (when provider-str
- (log/debugf "Updating last_used_at for user %s with provider %s" user-id provider-str)
- (t2/update! :model/AuthIdentity auth-identity-id {:last_used_at :%now}))
- (when device-info
- (login-history/record-login-history! session-id user device-info))
+ session (t2/with-transaction [_]
+ (u/prog1 (t2/insert-returning-instance! :model/Session
+ ;; Without setting the ID here we can't return an instance
+ ;; on MySQL
+ :id session-id
+ :user_id user-id
+ :auth_identity_id auth-identity-id
+ :session_key session-key
+ :expires_at (:expires_at auth-identity))
+ (when provider-str
+ (log/debugf "Updating last_used_at for user %s with provider %s" user-id provider-str)
+ (t2/update! :model/AuthIdentity auth-identity-id {:last_used_at :%now}))
+ (when device-info
+ (login-history/record-login-history! session-id user device-info))))]
(assoc session
:key session-key
:type (if (some-> (request/current-request) request/embedded?) :full-app-embed :normal))))
diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.clj
index eda21051c09..5b3309b5276 100644
--- a/src/metabase/session/api.clj
+++ b/src/metabase/session/api.clj
@@ -292,7 +292,7 @@
password-reset-url (str (system/site-url) "/auth/reset_password/" reset-token)]
(messages/send-password-reset-email! email nil password-reset-url is-active?)))
(events/publish-event! :event/password-reset-initiated
- {:object (assoc user :token (t2/select-one-fn :reset_token :model/User :id user-id))}))))
+ {:object (assoc user :token (auth-identity/reset-token-hash user-id))}))))
;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API
;;
diff --git a/src/metabase/setup_rest/api.clj b/src/metabase/setup_rest/api.clj
index efaaa247518..d72e51687fd 100644
--- a/src/metabase/setup_rest/api.clj
+++ b/src/metabase/setup_rest/api.clj
@@ -45,11 +45,9 @@
:email email
:first_name first-name
:last_name last-name
- :password (str (random-uuid))
:is_superuser true))
user-id (u/the-id new-user)]
- ;; this results in a second db call, but it avoids redundant password code so figure it's worth it
- (t2/update! :model/AuthIdentity :provider "password" :user_id user-id {:credentials {:plaintext_password password}})
+ (auth-identity/set-password! user-id password)
(let [session (auth-identity/create-session-with-auth-tracking! new-user device-info :provider/password)]
{:session-key (:key session), :user-id user-id, :session session})))
diff --git a/src/metabase/users/models/user.clj b/src/metabase/users/models/user.clj
index 7b8ef047649..be16a8fd1b3 100644
--- a/src/metabase/users/models/user.clj
+++ b/src/metabase/users/models/user.clj
@@ -3,7 +3,6 @@
[clojure.data :as data]
[clojure.string :as str]
[honey.sql.helpers :as sql.helpers]
- [java-time.api :as t]
[metabase.api.common :as api]
[metabase.config.core :as config]
[metabase.events.core :as events]
@@ -21,10 +20,8 @@
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
- [metabase.util.password :as u.password]
[methodical.core :as methodical]
[toucan2.core :as t2]
- [toucan2.pipeline :as t2.pipeline]
[toucan2.tools.default-fields :as t2.default-fields]))
(set! *warn-on-reflection* true)
@@ -125,48 +122,13 @@
;;; -------------------------------------------------- Password Management --------------------------------------------------
-(defn- prepare-password-for-insert
- "Hash password and prepare password fields for insertion.
- Throws an exception if password_salt is already present (passwords should not be pre-hashed)."
+(defn- without-credential-fields
+ "Remove password and reset-token fields from a User map. Login passwords live in the user's `password` AuthIdentity
+ (via [[metabase.auth-identity.core/set-password!]]) and reset tokens in their `emailed-secret-password-reset`
+ AuthIdentity; the legacy `core_user.password` / `.password_salt` / `.reset_token` / `.reset_triggered` columns are no
+ longer read or written by this codebase, so we drop any incoming values rather than persisting them."
[user]
- (when (contains? user :password_salt)
- (throw (ex-info "Don't try to hash passwords yourself" {})))
- (let [pw (or (:password user) (random-uuid))
- salt (str (random-uuid))
- hash (u.password/hash-bcrypt (str salt pw))]
- {:password hash
- :password_salt salt}))
-
-(defn- prepare-password-for-update
- "Conditionally hash password for updates. Returns password fields or nil.
- Only hashes if password is present and password_salt is not (indicating a plaintext password)."
- [{:keys [password password_salt]}]
- (when (and password (not password_salt))
- (prepare-password-for-insert {:password password})))
-
-(defn- sync-password-to-auth-identity!
- "Synchronize password changes to AuthIdentity model and invalidate sessions."
- [user-id]
- (let [{salt :password_salt password :password} (t2/select-one [:model/User :email :password :password_salt] user-id)
- pw-auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")]
- (when (and password salt)
- (cond
- (nil? pw-auth-identity)
- (t2/with-transaction [_]
- (t2/insert! :model/AuthIdentity {:user_id user-id
- :provider "password"
- :credentials {:password_hash password
- :password_salt salt}})
- (t2/delete! (t2/table-name :model/Session) :user_id user-id))
-
- (or (not= password (get-in pw-auth-identity [:credentials :password_hash]))
- (not= salt (get-in pw-auth-identity [:credentials :password_salt])))
- (t2/with-transaction [_]
- (t2/update! :model/AuthIdentity (u/the-id pw-auth-identity) {:credentials {:password_hash password
- :password_salt salt}})
- (t2/delete! (t2/table-name :model/Session) :user_id user-id))
-
- :else nil))))
+ (dissoc user :password :password_salt :reset_token :reset_triggered))
;;; -------------------------------------------------- Admin Group Management --------------------------------------------------
@@ -210,38 +172,18 @@
;;; -------------------------------------------------- Field Normalization --------------------------------------------------
(defn- normalize-user-fields
- "Normalize email, locale, and reset token for database storage."
+ "Normalize email and locale for database storage."
[user]
(cond-> user
(:email user) (update :email u/lower-case-en)
- (:locale user) (update :locale i18n/normalized-locale-string)
- ;; Only hash reset_token if it's not already a bcrypt hash (starts with $2a$ or $2b$)
- (and (:reset_token user)
- (not (re-matches #"^\$2[ab]\$.*" (:reset_token user))))
- (update :reset_token u.password/hash-bcrypt)))
-
-(methodical/defmethod t2.pipeline/results-transform [#_query-type :toucan.query-type/insert.instances
- #_model :model/User]
- "Create the initial :model/AuthIdenity from the results of saving a user. We have to do it here rather than in
- define-after-insert because we need to get the hashed password and salt to save to the auth-identity model, and
- those fields are removed by the default-files transformer before after-insert is called."
- [query-type model]
- (comp (map (fn [{:keys [password password_salt id] :as user}]
- (u/prog1 user
- (when (and password password_salt)
- (t2/insert! :model/AuthIdentity {:user_id id
- :provider "password"
- :credentials {:password_hash password
- :password_salt password_salt}})))))
- (binding [t2.default-fields/*skip-default-fields* false]
- (next-method query-type model))))
+ (:locale user) (update :locale i18n/normalized-locale-string)))
(t2/define-before-insert :model/User
[user]
(validate-user-insert! user)
(-> (merge insert-default-values user)
normalize-user-fields
- (merge (prepare-password-for-insert user))))
+ without-credential-fields))
(t2/define-after-insert :model/User
[{user-id :id, superuser? :is_superuser, :as user}]
@@ -262,8 +204,7 @@
(perms/allow-changing-all-users-group-members
(perms/allow-changing-all-external-users-group-members
(perms/without-is-superuser-sync-on-add-to-admin-group
- (perms/add-user-to-groups! user-id (map u/the-id groups))))))
- (sync-password-to-auth-identity! user-id)))
+ (perms/add-user-to-groups! user-id (map u/the-id groups))))))))
(t2/define-before-update :model/User
[{:keys [id] :as user}]
@@ -273,57 +214,16 @@
active? :is_active} changes
in-admin-group? (t2/exists? :model/PermissionsGroupMembership
:group_id (:id (perms/admin-group))
- :user_id id)
- hashed-pw (prepare-password-for-update changes)]
+ :user_id id)]
(validate-last-admin-not-archived! id in-admin-group? active?)
(when email (validate-user-email! email))
(when locale (validate-user-locale! locale))
(handle-superuser-toggle! id superuser? in-admin-group?)
(handle-user-archival! id active?)
- (merge user
- (normalize-user-fields (t2/changes user))
- hashed-pw
- (when (or hashed-pw (and (contains? changes :password) (contains? changes :password_salt)))
- {:reset_token nil :reset_triggered nil})
- (prepare-archival-timestamp active?))))
-
-(t2/define-after-update :model/User
- [{:keys [id] :as user}]
- ;; Query the database to check if we need to sync reset token changes
- ;; We can't rely on t2/changes in after-update hooks, so we compare current state
- (let [{:keys [email reset_token reset_triggered]} (t2/select-one [:model/User :email :reset_token :reset_triggered] :id id)
- current-auth-identity (t2/select-one :model/AuthIdentity
- :user_id id
- :provider "emailed-secret-password-reset")]
- (sync-password-to-auth-identity! id)
- (cond
- ;; Token being cleared - mark as consumed in AuthIdentity
- (and (nil? reset_token) current-auth-identity)
- (do
- (log/debugf "Syncing User %s reset_token clear to AuthIdentity - marking token consumed" id)
- (t2/update! :model/AuthIdentity (:id current-auth-identity)
- {:credentials (assoc (:credentials current-auth-identity) :consumed_at (t/instant))}))
-
- ;; Token being set - create or update AuthIdentity
- (and reset_token reset_triggered)
- (let [ttl-ms (* 48 60 60 1000)
- expires-at (t/plus (t/instant reset_triggered) (t/millis ttl-ms))
- credentials {:token_hash reset_token
- :expires_at expires-at
- :consumed_at nil}]
- (if current-auth-identity
- (do
- (log/debugf "Syncing User %s reset_token update to existing AuthIdentity %s" id (:id current-auth-identity))
- (t2/update! :model/AuthIdentity (:id current-auth-identity)
- {:credentials credentials}))
- (do
- (log/debugf "Syncing User %s reset_token insert to new AuthIdentity" id)
- (t2/insert! :model/AuthIdentity
- {:user_id id
- :provider "emailed-secret-password-reset"
- :credentials credentials
- :metadata {:email email}}))))))
- user)
+ (-> user
+ (merge (normalize-user-fields (t2/changes user))
+ (prepare-archival-timestamp active?))
+ without-credential-fields)))
(defn add-common-name
"Conditionally add a `:common_name` key to `user` by combining their first and last names, or using their email if names are `nil`.
diff --git a/src/metabase/users/util.clj b/src/metabase/users/util.clj
index 50861180038..1a3b94fd6fd 100644
--- a/src/metabase/users/util.clj
+++ b/src/metabase/users/util.clj
@@ -3,6 +3,7 @@
[clojure.set :as set]
[metabase.analytics.core :as analytics]
[metabase.api.common :as api]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.config.core :as config]
[metabase.notification.core :as notification]
[metabase.permissions.core :as perms]
@@ -85,6 +86,8 @@
@api/*current-user*
(= source :setup)
invite-target)))]
+ (when-let [password (:password attributes)]
+ (auth-identity/set-password! new-user-id password))
(maybe-set-user-group-memberships! new-user-id user-group-memberships)
(when (= source :setup)
(maybe-set-user-permissions-groups! new-user-id [(perms/all-users-group) (perms/admin-group)]))
diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.clj
index 2fa6f87f90d..44c101e1813 100644
--- a/src/metabase/users_rest/api.clj
+++ b/src/metabase/users_rest/api.clj
@@ -26,7 +26,6 @@
[metabase.util.i18n :refer [tru]]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
- [metabase.util.password :as u.password]
[toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -585,17 +584,19 @@
[:old_password {:optional true} [:maybe :string]]]
request]
(users/check-self-or-superuser id)
- (api/let-404 [user (t2/select-one [:model/User :id :last_login :password_salt :password],
+ (api/let-404 [user (t2/select-one [:model/User :id :email :last_login],
:id id,
:type :personal,
:is_active true)]
;; admins are allowed to reset anyone's password (in the admin people list) so no need to check the value of
;; `old_password` for them regular users have to know their password, however
(when-not api/*is-superuser?*
- (api/checkp (u.password/bcrypt-verify (str (:password_salt user) old_password) (:password user))
+ (api/checkp (true? (:success? (auth-identity/authenticate :provider/password {:email (:email user)
+ :password old_password})))
"old_password"
(tru "Invalid password")))
- (t2/update! :model/AuthIdentity :provider "password" :user_id id {:credentials {:plaintext_password password}})
+ ;; set-password! invalidates the user's existing sessions; a self-change gets a fresh one below
+ (auth-identity/set-password! id password)
;; after a successful password update go ahead and offer the client a new session that they can use
(when (= id api/*current-user-id*)
(let [{session-key :key, :as session} (auth-identity/create-session-with-auth-tracking! user (request/device-info request) :provider/password)
@@ -619,7 +620,7 @@
(let [reset-token (auth-identity/create-password-reset! id)
password-reset-url (str (system/site-url) "/auth/reset_password/" reset-token)]
(events/publish-event! :event/password-reset-initiated
- {:object (assoc user :token (t2/select-one-fn :reset_token :model/User :id id))})
+ {:object (assoc user :token (auth-identity/reset-token-hash id))})
{:password_reset_url password-reset-url})))
;;; +----------------------------------------------------------------------------------------------------------------+
diff --git a/test/metabase/auth_identity/core_test.clj b/test/metabase/auth_identity/core_test.clj
index 833003bb066..8fed05da343 100644
--- a/test/metabase/auth_identity/core_test.clj
+++ b/test/metabase/auth_identity/core_test.clj
@@ -2,6 +2,7 @@
"Integration tests for the AuthIdentity system."
(:require
[clojure.test :refer :all]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.test :as mt]
[toucan2.core :as t2]))
@@ -12,6 +13,7 @@
(deftest auth-identity-model-test
(testing "AuthIdentity model basic operations"
(mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
(testing "can create an AuthIdentity"
(mt/with-model-cleanup [:model/AuthIdentity]
;; Use google provider to avoid conflict with auto-created password AuthIdentity
@@ -25,7 +27,6 @@
(is (= {:email "[email protected]"}
(:metadata auth-identity))))))
(testing "can update an AuthIdentity"
- ;; Use the auto-created password AuthIdentity
(let [auth-identity (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")]
(t2/update! :model/AuthIdentity (:id auth-identity)
{:credentials {:password_hash "new_hash"
@@ -56,6 +57,7 @@
(testing "Cannot create duplicate AuthIdentity for same user and provider"
(mt/with-model-cleanup [:model/AuthIdentity :model/User]
(let [user-id (t2/insert-returning-pk! :model/User (mt/with-temp-defaults :model/User))]
+ (auth-identity/set-password! user-id "some-password")
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"duplicate|Duplicate|Unique"
@@ -69,7 +71,7 @@
(deftest multiple-providers-per-user-test
(testing "A user can have multiple authentication providers"
(mt/with-temp [:model/User user {}]
- ;; User already has password AuthIdentity from creation
+ (auth-identity/set-password! (:id user) "test-password")
(let [password-auth (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")
google-auth (t2/insert-returning-instance! :model/AuthIdentity
{:user_id (:id user)
diff --git a/test/metabase/auth_identity/models/auth_identity_test.clj b/test/metabase/auth_identity/models/auth_identity_test.clj
index 4eb047b0026..f0884e68662 100644
--- a/test/metabase/auth_identity/models/auth_identity_test.clj
+++ b/test/metabase/auth_identity/models/auth_identity_test.clj
@@ -1,28 +1,50 @@
(ns metabase.auth-identity.models.auth-identity-test
(:require
[clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.test :as mt]
[metabase.util.encryption :as encryption]
[metabase.util.encryption-test :as encryption-test]
[metabase.util.password :as u.password]
[toucan2.core :as t2]))
-(deftest user-creation-creates-password-auth-identity-test
- (testing "User creation automatically creates password AuthIdentity with hashed password"
+(deftest set-password!-creates-password-auth-identity-test
+ (testing "set-password! creates a password AuthIdentity with a hashed password, and User creation does not"
(mt/with-temp [:model/User {user-id :id}]
+ (is (nil? (t2/select-one :model/AuthIdentity :user_id user-id :provider "password"))
+ "creating a User does not create a password AuthIdentity")
+ (auth-identity/set-password! user-id "test-password-123")
(let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")]
- (is (some? auth-identity)
- "AuthIdentity should be created automatically")
- (is (some? (get-in auth-identity [:credentials :password_hash]))
- "Credentials should contain password_hash")
- (is (some? (get-in auth-identity [:credentials :password_salt]))
- "Credentials should contain password_salt")
- (is (nil? (get-in auth-identity [:credentials :plaintext_password]))
- "Plaintext password should not be stored")))))
+ (is (some? auth-identity))
+ (is (some? (get-in auth-identity [:credentials :password_hash])))
+ (is (some? (get-in auth-identity [:credentials :password_salt])))
+ (is (nil? (get-in auth-identity [:credentials :plaintext_password])))))))
+
+(deftest set-password!-invalidates-reset-token-test
+ (testing "set-password! deletes the user's password-reset token, so a reset link can't be replayed once the password is set"
+ (mt/with-temp [:model/User {user-id :id}]
+ (auth-identity/create-password-reset! user-id)
+ (is (some? (t2/select-one :model/AuthIdentity :user_id user-id :provider "emailed-secret-password-reset"))
+ "sanity: a pending reset token exists")
+ (auth-identity/set-password! user-id "new-password")
+ (is (nil? (t2/select-one :model/AuthIdentity :user_id user-id :provider "emailed-secret-password-reset"))
+ "setting a password removes the pending reset token"))))
+
+(deftest set-password!-clears-stale-expiry-test
+ (testing "a plain set-password! clears any :expires_at a prior support-access grant left on the credential"
+ (mt/with-temp [:model/User {user-id :id}]
+ (auth-identity/set-password! user-id "granted" {:expires-at (t/instant "2000-01-01T00:00:00Z")})
+ (is (some? (t2/select-one-fn :expires_at :model/AuthIdentity :user_id user-id :provider "password"))
+ "sanity: the grant set an expiry")
+ (auth-identity/set-password! user-id "new-password")
+ (is (nil? (t2/select-one-fn :expires_at :model/AuthIdentity :user_id user-id :provider "password"))
+ "setting a password without an expiry clears the stale one"))))
(deftest plaintext-password-hashed-on-update-test
(testing "Plaintext password is hashed on update"
(mt/with-temp [:model/User {user-id :id}]
+ (auth-identity/set-password! user-id "initial-password")
(let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
auth-identity-id (:id auth-identity)
new-password "new-password-456"]
@@ -42,6 +64,7 @@
(deftest non-credential-updates-dont-trigger-hashing-test
(testing "Non-credential updates don't trigger password hashing"
(mt/with-temp [:model/User {user-id :id}]
+ (auth-identity/set-password! user-id "initial-password")
(let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
auth-identity-id (:id auth-identity)
original-hash (get-in auth-identity [:credentials :password_hash])
@@ -84,6 +107,8 @@
(testing "Each password hash uses a unique salt"
(mt/with-temp [:model/User user-1 {}
:model/User user-2 {}]
+ (auth-identity/set-password! (:id user-1) "same-password")
+ (auth-identity/set-password! (:id user-2) "same-password")
(let [auth-1 (t2/select-one :model/AuthIdentity :user_id (:id user-1) :provider "password")
auth-2 (t2/select-one :model/AuthIdentity :user_id (:id user-2) :provider "password")]
(is (not= (get-in auth-1 [:credentials :password_salt])
@@ -93,97 +118,6 @@
(get-in auth-2 [:credentials :password_hash]))
"Hashes should be different due to different salts")))))
-(deftest password-auth-identity-syncs-to-user-table-test
- (testing "Password AuthIdentity automatically syncs to User table on creation"
- (mt/with-temp [:model/User {user-id :id}]
- (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
- {:keys [password_hash password_salt]} (:credentials auth-identity)
- user (t2/select-one [:model/User :password :password_salt] :id user-id)]
- (is (= password_hash (:password user))
- "User table should contain matching password hash")
- (is (= password_salt (:password_salt user))
- "User table should contain matching password salt")))))
-
-(deftest non-password-providers-dont-sync-to-user-table-test
- (testing "Non-password providers don't sync to User table"
- (mt/with-temp [:model/User {user-id :id}]
- (let [password-auth (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
- original-password (get-in password-auth [:credentials :password_hash])
- original-salt (get-in password-auth [:credentials :password_salt])]
- (t2/insert-returning-instance!
- :model/AuthIdentity
- {:user_id user-id
- :provider "google"
- :metadata {:email "[email protected]"}})
- (let [user (t2/select-one [:model/User :password :password_salt] :id user-id)]
- (is (= original-password (:password user))
- "User password should remain unchanged after SSO AuthIdentity creation")
- (is (= original-salt (:password_salt user))
- "User password salt should remain unchanged after SSO AuthIdentity creation"))))))
-
-(deftest password-update-syncs-to-user-table-test
- (testing "Password update syncs to User table"
- (mt/with-temp [:model/User {user-id :id}]
- (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
- auth-identity-id (:id auth-identity)
- new-password "new-password-456"]
- (t2/update! :model/AuthIdentity auth-identity-id
- {:credentials {:plaintext_password new-password}})
- (let [updated-auth (t2/select-one :model/AuthIdentity :id auth-identity-id)
- {:keys [password_hash password_salt]} (:credentials updated-auth)
- user (t2/select-one [:model/User :password :password_salt] :id user-id)]
- (is (= password_hash (:password user))
- "User table should be updated with new password hash")
- (is (= password_salt (:password_salt user))
- "User table should be updated with new password salt")
- (is (true? (u.password/verify-password new-password (:password_salt user) (:password user)))
- "New password in User table should be verifiable"))))))
-
-(deftest non-credential-updates-dont-trigger-sync-test
- (testing "Non-credential updates don't trigger sync to User table"
- (mt/with-temp [:model/User {user-id :id}]
- (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
- auth-identity-id (:id auth-identity)
- original-user (t2/select-one [:model/User :password :password_salt] :id user-id)]
- (t2/update! :model/AuthIdentity auth-identity-id
- {:metadata {:last_login "2024-01-01"}})
- (let [user (t2/select-one [:model/User :password :password_salt] :id user-id)]
- (is (= (:password original-user) (:password user))
- "User password should remain unchanged after metadata update")
- (is (= (:password_salt original-user) (:password_salt user))
- "User password salt should remain unchanged after metadata update"))))))
-
-(deftest sso-provider-updates-dont-sync-to-user-table-test
- (testing "SSO provider updates don't sync to User table"
- (mt/with-temp [:model/User {user-id :id}]
- (let [password-auth (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
- original-password (get-in password-auth [:credentials :password_hash])
- original-salt (get-in password-auth [:credentials :password_salt])
- sso-auth-identity (t2/insert-returning-instance!
- :model/AuthIdentity
- {:user_id user-id
- :provider "google"
- :metadata {:email "[email protected]"}})
- sso-auth-identity-id (:id sso-auth-identity)]
- (t2/update! :model/AuthIdentity sso-auth-identity-id
- {:metadata {:email "[email protected]"}})
- (let [user (t2/select-one [:model/User :password :password_salt] :id user-id)]
- (is (= original-password (:password user))
- "User password should remain unchanged after SSO metadata update")
- (is (= original-salt (:password_salt user))
- "User password salt should remain unchanged after SSO metadata update"))))))
-
-(deftest auth-identity-user-consistency-test
- (testing "AuthIdentity and User table remain consistent"
- (mt/with-temp [:model/User {user-id :id}]
- (let [auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
- auth-creds (:credentials auth-identity)
- user (t2/select-one [:model/User :password :password_salt] :id user-id)]
- (is (= (:password_hash auth-creds) (:password user))
- "Password hash should match between AuthIdentity and User")
- (is (= (:password_salt auth-creds) (:password_salt user))
- "Password salt should match between AuthIdentity and User")))))
-
(deftest credentials-encrypted-at-rest-test
(testing "with a secret key set, the raw credentials column is ciphertext, not JSON"
(encryption-test/with-secret-key "key-for-auth-identity-test-1"
diff --git a/test/metabase/auth_identity/providers/emailed_secret_test.clj b/test/metabase/auth_identity/providers/emailed_secret_test.clj
index f01e069175e..3eb9051dcb6 100644
--- a/test/metabase/auth_identity/providers/emailed_secret_test.clj
+++ b/test/metabase/auth_identity/providers/emailed_secret_test.clj
@@ -1,5 +1,5 @@
(ns metabase.auth-identity.providers.emailed-secret-test
- "Tests for emailed_secret provider functionality and AuthIdentity to User sync."
+ "Tests for emailed_secret provider functionality."
(:require
[clojure.test :refer :all]
[java-time.api :as t]
@@ -9,52 +9,6 @@
(set! *warn-on-reflection* true)
-(deftest auth-identity-to-user-sync-test
- (testing "When reset token is created in AuthIdentity, it syncs to User model"
- (mt/with-temp [:model/User {user-id :id} {}]
- (emailed-secret/create-password-reset! user-id)
- (let [auth-identity (t2/select-one :model/AuthIdentity
- :user_id user-id
- :provider "emailed-secret-password-reset")
- user (t2/select-one [:model/User :reset_token :reset_triggered] :id user-id)]
- (is (some? auth-identity))
- (is (= (get-in auth-identity [:credentials :token_hash]) (:reset_token user)))
- (is (int? (:reset_triggered user)))
- (is (pos? (:reset_triggered user)))))))
-
-(deftest auth-identity-token-update-sync-test
- (testing "When reset token is updated in AuthIdentity, it syncs to User model"
- (mt/with-temp [:model/User {user-id :id} {}]
- (emailed-secret/create-password-reset! user-id)
- (let [first-auth-identity (t2/select-one :model/AuthIdentity
- :user_id user-id
- :provider "emailed-secret-password-reset")
- first-token-hash (get-in first-auth-identity [:credentials :token_hash])]
- (Thread/sleep 10)
- (emailed-secret/create-password-reset! user-id)
- (let [updated-auth-identity (t2/select-one :model/AuthIdentity
- :user_id user-id
- :provider "emailed-secret-password-reset")
- updated-token-hash (get-in updated-auth-identity [:credentials :token_hash])
- user (t2/select-one [:model/User :reset_token :reset_triggered] :id user-id)]
- (is (not= first-token-hash updated-token-hash))
- (is (= updated-token-hash (:reset_token user)))
- (is (int? (:reset_triggered user))))))))
-
-(deftest auth-identity-token-consumed-sync-test
- (testing "When token is marked consumed in AuthIdentity, User model is cleared"
- (mt/with-temp [:model/User {user-id :id} {}]
- (emailed-secret/create-password-reset! user-id)
- (let [auth-identity (t2/select-one :model/AuthIdentity
- :user_id user-id
- :provider "emailed-secret-password-reset")]
- (is (some? (:reset_token (t2/select-one [:model/User :reset_token] :id user-id))))
- (t2/update! :model/AuthIdentity (:id auth-identity)
- {:credentials (assoc (:credentials auth-identity) :consumed_at (t/instant))})
- (let [user (t2/select-one [:model/User :reset_token :reset_triggered] :id user-id)]
- (is (nil? (:reset_token user)))
- (is (nil? (:reset_triggered user))))))))
-
(deftest create-password-reset-creates-auth-identity-test
(testing "create-password-reset! creates AuthIdentity with correct structure"
(mt/with-temp [:model/User {user-id :id email :email} {}]
diff --git a/test/metabase/auth_identity/session_test.clj b/test/metabase/auth_identity/session_test.clj
index fa05e95c3c4..b23c2583fb9 100644
--- a/test/metabase/auth_identity/session_test.clj
+++ b/test/metabase/auth_identity/session_test.clj
@@ -15,6 +15,7 @@
(deftest create-session-with-password-auth-tracking-test
(testing "Creating a session with password authentication tracks the auth_identity_id"
(mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
(let [password-auth (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")
device-info {:device_id "test-device-123"
:embedded false
@@ -66,6 +67,7 @@
(deftest create-session-updates-last-used-at-test
(testing "Creating a session updates the last_used_at timestamp on the AuthIdentity"
(mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
(let [password-auth (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")
device-info {:device_id "test-device-last-used"
:embedded false
@@ -81,6 +83,7 @@
(deftest multiple-sessions-same-auth-identity-test
(testing "Multiple sessions can reference the same AuthIdentity"
(mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
(let [password-auth (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")
device-info-1 {:device_id "device-1"
:embedded false
@@ -105,6 +108,7 @@
(deftest session-cascade-delete-on-auth-identity-deletion-test
(testing "Deleting an AuthIdentity cascades to delete associated Sessions"
(mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
(let [password-auth (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")
device-info {:device_id "test-device-cascade"
:embedded false
@@ -123,6 +127,7 @@
(mt/with-temp [:model/User user {}
:model/AuthIdentity google-auth {:user_id (:id user)
:provider "google"}]
+ (auth-identity/set-password! (:id user) "test-password")
(let [password-auth (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")
device-info {:device_id "test-device-multi"
:embedded false
@@ -168,6 +173,7 @@
(deftest session-inherits-expires-at-test
(testing "Session inherits expires_at from auth-identity"
(mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
(let [expires-at (t/plus (t/offset-date-time) (t/days 7))
password-auth (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")]
(t2/update! :model/AuthIdentity (:id password-auth) {:expires_at expires-at})
@@ -187,6 +193,7 @@
(deftest session-no-expires-at-when-auth-identity-has-none-test
(testing "Session has no expires_at when auth-identity doesn't have one"
(mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
(let [password-auth (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "password")
device-info {:device_id "test-device-no-expires"
:embedded false
diff --git a/test/metabase/session/api_test.clj b/test/metabase/session/api_test.clj
index 2c52055f1e2..ab64b486e8b 100644
--- a/test/metabase/session/api_test.clj
+++ b/test/metabase/session/api_test.clj
@@ -4,6 +4,7 @@
[clj-http.client :as http]
[clojure.test :refer :all]
[medley.core :as m]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.driver.h2 :as h2]
[metabase.request.core :as request]
[metabase.request.settings :as request.settings]
@@ -258,10 +259,9 @@
(fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
(mt/with-fake-inbox
(letfn [(reset-fields-set? []
- (let [{:keys [reset_token reset_triggered]} (t2/select-one [:model/User :reset_token :reset_triggered]
- :id (mt/user->id :rasta))]
- (boolean (and reset_token reset_triggered))))]
- (t2/update! :model/User (mt/user->id :rasta) {:reset_token nil, :reset_triggered nil})
+ (boolean (t2/select-one :model/AuthIdentity :user_id (mt/user->id :rasta)
+ :provider "emailed-secret-password-reset")))]
+ (t2/delete! :model/AuthIdentity :user_id (mt/user->id :rasta) :provider "emailed-secret-password-reset")
(assert (not (reset-fields-set?)))
(is (= nil
(mt/user-http-request :rasta :post 204 "session/forgot_password"
@@ -269,7 +269,7 @@
"Request should return no content")
(is (true?
(reset-fields-set?))
- "User `:reset_token` and `:reset_triggered` should be updated")
+ "the password-reset AuthIdentity should be created")
(is (mt/received-email-subject? :rasta #"Password Reset")))))))
(deftest forgot-password-uses-site-url-test
@@ -389,7 +389,7 @@
(is (=? {:topic :password-reset-initiated
:model_id rasta-id
:model "User"
- :details {:token (t2/select-one-fn :reset_token :model/User :id rasta-id)}}
+ :details {:token (auth-identity/reset-token-hash rasta-id)}}
(mt/latest-audit-log-entry :password-reset-initiated rasta-id)))))))))
(deftest forgot-password-throttling-test
@@ -415,9 +415,9 @@
(mt/with-fake-inbox
(let [password {:old "password"
:new "whateverUP12!!"}]
- (mt/with-temp [:model/User {:keys [email id]} {:password (:old password), :reset_triggered (System/currentTimeMillis)}]
- (let [token (u/prog1 (str id "_" (random-uuid))
- (t2/update! :model/User id {:reset_token <>}))
+ (mt/with-temp [:model/User {:keys [email id]} {}]
+ (auth-identity/set-password! id (:old password))
+ (let [token (auth-identity/create-password-reset! id)
creds {:old {:password (:old password)
:username email}
:new {:password (:new password)
@@ -431,9 +431,9 @@
(mt/client :post 401 "session" (:old creds))))
(is (malli= SessionResponse
(mt/client :post 200 "session" (:new creds))))
- (is (= {:reset_token nil
- :reset_triggered nil}
- (mt/derecordize (t2/select-one [:model/User :reset_token :reset_triggered], :id id))))))))))
+ (is (nil? (t2/select-one :model/AuthIdentity
+ :user_id id :provider "emailed-secret-password-reset"))
+ "the reset token is removed once the password has been set")))))))
(deftest reset-password-throttling-test
(testing "POST /api/session/reset_password - endpoint is throttled"
@@ -460,10 +460,10 @@
(mt/with-fake-inbox
(let [password {:old "password"
:new "whateverUP12!!"}]
- (mt/with-temp [:model/User {:keys [id]} {:password (:old password), :reset_triggered (System/currentTimeMillis)}]
- (let [token (u/prog1 (str id "_" (random-uuid))
- (t2/update! :model/User id {:reset_token <> :last_login :%now}))
- reset-token (t2/select-one-fn :reset_token :model/User :id id)]
+ (mt/with-temp [:model/User {:keys [id]} {}]
+ (t2/update! :model/User id {:last_login :%now})
+ (let [token (auth-identity/create-password-reset! id)
+ reset-token (auth-identity/reset-token-hash id)]
(mt/client :post 200 "session/reset_password" {:token token
:password (:new password)})
(is (= {:topic :password-reset-successful
@@ -489,25 +489,46 @@
(mt/client :post 400 "session/reset_password" {:token "1_not-found"
:password "whateverUP12!!"}))))
(testing "Test that an expired token doesn't work"
- (let [token (str (mt/user->id :rasta) "_" (random-uuid))]
- (t2/update! :model/User (mt/user->id :rasta) {:reset_token token, :reset_triggered 0})
+ (let [uid (mt/user->id :rasta)
+ token (auth-identity/create-password-reset! uid)
+ ai (t2/select-one :model/AuthIdentity :user_id uid :provider "emailed-secret-password-reset")]
+ (t2/update! :model/AuthIdentity (:id ai)
+ {:credentials (assoc (:credentials ai) :expires_at (java.time.Instant/ofEpochMilli 0))})
(is (=? {:errors {:password "Invalid reset token"}}
(mt/client :post 400 "session/reset_password" {:token token
:password "whateverUP12!!"})))))))
+(deftest reset-password-from-token-invalidates-sessions-test
+ (testing "POST /api/session/reset_password deletes the user's existing sessions"
+ (mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "password")
+ (let [session (auth-identity/create-session-with-auth-tracking!
+ user
+ {:device_id "reset-test-device" :embedded false :token_exchange false
+ :device_description "Test" :ip_address "127.0.0.1"}
+ :provider/password)
+ token (auth-identity/create-password-reset! (:id user))]
+ (is (some? (t2/select-one :model/Session :id (:id session)))
+ "sanity check: the session exists before the reset")
+ (mt/client :post 200 "session/reset_password" {:token token :password "whateverUP12!!"})
+ (is (nil? (t2/select-one :model/Session :id (:id session)))
+ "the pre-existing session should be deleted after resetting the password via token")))))
+
(deftest check-reset-token-valid-test
(testing "GET /session/password_reset_token_valid"
(testing "Check that a valid, unexpired token returns true"
- (let [token (str (mt/user->id :rasta) "_" (random-uuid))]
- (t2/update! :model/User (mt/user->id :rasta) {:reset_token token, :reset_triggered (dec (System/currentTimeMillis))})
+ (let [token (auth-identity/create-password-reset! (mt/user->id :rasta))]
(is (= {:valid true}
(mt/client :get 200 "session/password_reset_token_valid", :token token)))))
(testing "Check than an made-up token returns false"
(is (= {:valid false}
(mt/client :get 200 "session/password_reset_token_valid", :token "ABCDEFG"))))
(testing "Check that an expired but valid token returns false"
- (let [token (str (mt/user->id :rasta) "_" (random-uuid))]
- (t2/update! :model/User (mt/user->id :rasta) {:reset_token token, :reset_triggered 0})
+ (let [uid (mt/user->id :rasta)
+ token (auth-identity/create-password-reset! uid)
+ ai (t2/select-one :model/AuthIdentity :user_id uid :provider "emailed-secret-password-reset")]
+ (t2/update! :model/AuthIdentity (:id ai)
+ {:credentials (assoc (:credentials ai) :expires_at (java.time.Instant/ofEpochMilli 0))})
(is (= {:valid false}
(mt/client :get 200 "session/password_reset_token_valid", :token token)))))))
@@ -703,8 +724,8 @@
(testing "LDAP login - fallback to local for broken LDAP settings"
(ldap.test/with-ldap-server!
(mt/with-temporary-setting-values [ldap-user-base "cn=wrong,cn=com"]
- (mt/with-temp [:model/User _ {:email "[email protected]"
- :password "1234"}]
+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}]
+ (auth-identity/set-password! user-id "1234")
(is (malli= SessionResponse
(mt/client :post 200 "session" {:username "[email protected]"
:password "1234"}))))))))
@@ -715,8 +736,8 @@
(mt/with-temporary-setting-values [ldap-timeout-seconds 0.01]
(mt/with-dynamic-fn-redefs [metabase.sso.ldap.default-implementation/search (fn [& _args]
(Thread/sleep 500))]
- (mt/with-temp [:model/User _ {:email "[email protected]"
- :password "1234"}]
+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}]
+ (auth-identity/set-password! user-id "1234")
(is (malli= SessionResponse
(mt/client :post 200 "session" {:username "[email protected]"
:password "1234"})))))))))
diff --git a/test/metabase/test/data/users.clj b/test/metabase/test/data/users.clj
index 227601965e3..f89906c5aa3 100644
--- a/test/metabase/test/data/users.clj
+++ b/test/metabase/test/data/users.clj
@@ -4,6 +4,7 @@
[clojure.test :as t]
[medley.core :as m]
[metabase.app-db.core :as mdb]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.request.core :as request]
[metabase.session.core :as session]
[metabase.test.http-client :as client]
@@ -69,14 +70,14 @@
(or (t2/select-one :model/User :email email)
(locking create-user-lock
(or (t2/select-one :model/User :email email)
- (t2/insert-returning-instance! :model/User
- {:email email
- :first_name first-name
- :last_name last-name
- :password password
- :is_superuser superuser
- :is_qbnewb true
- :is_active active})))))
+ (u/prog1 (t2/insert-returning-instance! :model/User
+ {:email email
+ :first_name first-name
+ :last_name last-name
+ :is_superuser superuser
+ :is_qbnewb true
+ :is_active active})
+ (auth-identity/set-password! (u/the-id <>) password))))))
(mu/defn fetch-user :- (ms/InstanceOf :model/User)
"Fetch the User object associated with `username`. Creates user if needed.
diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.clj
index 61e0f0254d2..4ac44939cee 100644
--- a/test/metabase/test/util.clj
+++ b/test/metabase/test/util.clj
@@ -425,7 +425,6 @@
:last_name (u.random/random-name)
:email (u.random/random-email)
:entity_id (u/generate-nano-id)
- :password (u.random/random-name)
:date_joined (t/zoned-date-time)
:updated_at (t/zoned-date-time)})})
diff --git a/test/metabase/users/models/user_test.clj b/test/metabase/users/models/user_test.clj
index 502c8e3a9ad..b7a8370e69b 100644
--- a/test/metabase/users/models/user_test.clj
+++ b/test/metabase/users/models/user_test.clj
@@ -18,7 +18,6 @@
[metabase.test.http-client :as client]
[metabase.users.models.user :as user]
[metabase.util :as u]
- [metabase.util.password :as u.password]
[toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -358,21 +357,6 @@
(user-group-names :lucky))
"If an INVALID REMOVE is attempted, valid adds should not be persisted"))))))
-(deftest password-sync-to-auth-identity-test
- (testing "Password changes are automatically synced to AuthIdentity via lifecycle hooks"
- (testing "Password update via t2/update! also syncs to AuthIdentity"
- (mt/with-temp [:model/User {user-id :id} {:password "initial-password"}]
- (let [initial-user (t2/select-one [:model/User :password] :id user-id)
- initial-password-hash (:password initial-user)]
- (t2/update! :model/User user-id {:password "another-new-password"})
- (let [updated-user (t2/select-one [:model/User :password] :id user-id)
- updated-password-hash (:password updated-user)
- updated-auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
- auth-identity-hash (get-in updated-auth-identity [:credentials :password_hash])]
- (is (not= initial-password-hash updated-password-hash) "Password should be updated in User table")
- (is (some? updated-auth-identity) "AuthIdentity should still exist")
- (is (= updated-password-hash auth-identity-hash) "AuthIdentity password hash should match User table")))))))
-
(deftest validate-locale-test
(testing "`:locale` should be validated"
(testing "creating a new User"
@@ -426,31 +410,6 @@
(testing "subscription should no longer exist"
(is (not (subscription-exists?))))))))
-(deftest hash-password-on-update-test
- (testing "Setting `:password` with [[t2/update!]] should hash the password, just like [[t2/insert!]]"
- (let [plaintext-password "password-1234"]
- (mt/with-temp [:model/User {user-id :id} {:password plaintext-password}]
- (let [salt (fn [] (t2/select-one-fn :password_salt :model/User :id user-id))
- hashed-password (fn [] (t2/select-one-fn :password :model/User :id user-id))
- original-hashed-password (hashed-password)]
- (testing "sanity check: check that password can be verified"
- (is (u.password/verify-password plaintext-password
- (salt)
- original-hashed-password)))
- (is (= 1
- (t2/update! :model/User user-id {:password plaintext-password})))
- (let [new-hashed-password (hashed-password)]
- (testing "password should have been hashed"
- (is (not= plaintext-password
- new-hashed-password)))
- (testing "even tho the plaintext password is the same, hashed password should be different (different salts)"
- (is (not= original-hashed-password
- new-hashed-password)))
- (testing "salt should have been set; verify password was hashed correctly"
- (is (u.password/verify-password plaintext-password
- (salt)
- new-hashed-password)))))))))
-
(deftest last-acknowledged-version-can-be-read-and-set
(testing "last-acknowledged-version can be read and set"
(mt/with-test-user :rasta
diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.clj
index 3a0f3738fd5..b64c5d2f510 100644
--- a/test/metabase/users_rest/api_test.clj
+++ b/test/metabase/users_rest/api_test.clj
@@ -4,6 +4,7 @@
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.api.response :as api.response]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.collections.models.collection :as collection]
[metabase.config.core :as config]
[metabase.models.interface :as mi]
@@ -627,6 +628,7 @@
:password "p@ssw0rd"
:login_attributes {"role" "admin"
"department" "engineering"}}]
+ (auth-identity/set-password! (:id user) "p@ssw0rd")
(let [response (mt/user-http-request :crowberto :get 200 (str "user/" (:id user)))]
(testing "response includes structured_attributes"
(is (contains? response :structured_attributes)))
@@ -649,6 +651,7 @@
"env" "production"}
:login_attributes {"role" "admin"
"department" "engineering"}}]
+ (auth-identity/set-password! (:id user) "p@ssw0rd")
(let [response (mt/user-http-request :crowberto :get 200 (str "user/" (:id user)))]
(testing "User attributes override jwt attributes when keys conflict"
(is (= {:role {:source "user" :frozen false :value "admin"
@@ -1317,6 +1320,7 @@
(mt/with-temp [:model/User user {:email "[email protected]"
:password "def123"
:sso_source "google"}]
+ (auth-identity/set-password! (u/the-id user) "def123")
(let [creds {:username "[email protected]"
:password "def123"}]
(is (= "You don't have permissions to do that."
@@ -1327,6 +1331,7 @@
(mt/with-temp [:model/User user {:email "[email protected]"
:password "def123"
:sso_source "ldap"}]
+ (auth-identity/set-password! (u/the-id user) "def123")
(let [creds {:username "[email protected]"
:password "def123"}]
(is (= "You don't have permissions to do that."
@@ -1339,6 +1344,7 @@
(mt/with-temp [:model/User user {:email "[email protected]"
:password "def123"
:sso_source "google"}]
+ (auth-identity/set-password! (u/the-id user) "def123")
(let [creds {:username "[email protected]"
:password "def123"}]
(client/client creds :put 200 (format "user/%d" (u/the-id user))
@@ -1347,6 +1353,7 @@
(mt/with-temp [:model/User user {:email "[email protected]"
:password "def123"
:sso_source "ldap"}]
+ (auth-identity/set-password! (u/the-id user) "def123")
(let [creds {:username "[email protected]"
:password "def123"}]
(client/client creds :put 200 (format "user/%d" (u/the-id user))
@@ -1478,7 +1485,8 @@
(deftest update-locale-test
(testing "PUT /api/user/:id\n"
- (mt/with-temp [:model/User {user-id :id, email :email} {:password "p@ssw0rd"}]
+ (mt/with-temp [:model/User {user-id :id, email :email} {}]
+ (auth-identity/set-password! user-id "p@ssw0rd")
(letfn [(set-locale! [expected-status-code new-locale]
(mt/client {:username email, :password "p@ssw0rd"}
:put expected-status-code (str "user/" user-id)
@@ -1573,25 +1581,26 @@
;;; | Updating a Password -- PUT /api/user/:id/password |
;;; +----------------------------------------------------------------------------------------------------------------+
-(defn- user-can-reset-password? [superuser?]
- (mt/with-temp [:model/User user {:password "def", :is_superuser (boolean superuser?)}]
+(defn- user-can-reset-password! [superuser?]
+ (mt/with-temp [:model/User user {:is_superuser (boolean superuser?)}]
+ (auth-identity/set-password! (:id user) "def")
(let [creds {:username (:email user), :password "def"}
- hashed-password (t2/select-one-fn :password :model/User, :%lower.email (u/lower-case-en (:email user)))]
- ;; use API to reset the users password
+ password-hash (fn [] (:password_hash (t2/select-one-fn :credentials :model/AuthIdentity
+ :user_id (:id user), :provider "password")))
+ original-hash (password-hash)]
(mt/client creds :put 200 (format "user/%d/password" (:id user)) {:password "abc123!!DEF"
:old_password "def"})
- ;; now simply grab the lastest pass from the db and compare to the one we have from before reset
- (not= hashed-password (t2/select-one-fn :password :model/User, :%lower.email (u/lower-case-en (:email user)))))))
+ (not= original-hash (password-hash)))))
(deftest can-reset-password-test
(testing "PUT /api/user/:id/password"
(testing "Test that we can reset our own password. If user is a"
(testing "superuser"
(is (true?
- (user-can-reset-password? :superuser))))
+ (user-can-reset-password! :superuser))))
(testing "non-superuser"
(is (true?
- (user-can-reset-password? (not :superuser))))))))
+ (user-can-reset-password! (not :superuser))))))))
(deftest reset-password-permissions-test
(testing "PUT /api/user/:id/password"
@@ -1612,20 +1621,53 @@
{:password "whateverUP12!!"
:old_password "mismatched"}))))))
+(deftest reset-password-verifies-old-password-against-auth-identity-test
+ (testing "PUT /api/user/:id/password"
+ (testing "old_password is checked against the password AuthIdentity, like login, not the legacy core_user columns"
+ (mt/with-temp [:model/User user {:is_superuser false}]
+ (auth-identity/set-password! (:id user) "def")
+ (t2/update! (t2/table-name :model/User) (:id user) {:password "not-a-bcrypt-hash", :password_salt "stale"})
+ (is (=? {:success true}
+ (mt/client {:username (:email user), :password "def"}
+ :put 200 (format "user/%d/password" (:id user))
+ {:password "abc123!!DEF", :old_password "def"})))
+ (testing "the new password authenticates and the stale core_user columns are left untouched"
+ (is (some? (mt/client :post 200 "session" {:username (:email user), :password "abc123!!DEF"})))
+ (is (= {:password "not-a-bcrypt-hash", :password_salt "stale"}
+ (into {} (t2/select-one [:model/User :password :password_salt] :id (:id user))))))))))
+
(deftest reset-password-session-test
(testing "PUT /api/user/:id/password"
(testing "Test that we return a session if we are changing our own password"
- (mt/with-temp [:model/User user {:password "def", :is_superuser false}]
+ (mt/with-temp [:model/User user {:is_superuser false}]
+ (auth-identity/set-password! (:id user) "def")
(let [creds {:username (:email user), :password "def"}]
(is (=? {:session_id string/valid-uuid?
:success true}
(mt/client creds :put 200 (format "user/%d/password" (:id user)) {:password "abc123!!DEF"
:old_password "def"}))))))
(testing "Test that we don't return a session if we are changing our someone else's password as a superuser"
- (mt/with-temp [:model/User user {:password "def", :is_superuser false}]
+ (mt/with-temp [:model/User user {:is_superuser false}]
+ (auth-identity/set-password! (:id user) "def")
(is (nil? (mt/user-http-request :crowberto :put 204 (format "user/%d/password" (:id user)) {:password "abc123!!DEF"
:old_password "def"})))))))
+(deftest reset-password-invalidates-existing-sessions-test
+ (testing "PUT /api/user/:id/password invalidates the user's existing sessions"
+ (mt/with-temp [:model/User user {:is_superuser false}]
+ (auth-identity/set-password! (:id user) "def")
+ (let [session (auth-identity/create-session-with-auth-tracking!
+ user
+ {:device_id "test-device" :embedded false :token_exchange false
+ :device_description "Test" :ip_address "127.0.0.1"}
+ :provider/password)]
+ (is (some? (t2/select-one :model/Session :id (:id session)))
+ "sanity check: the session exists before the password change")
+ (mt/user-http-request :crowberto :put 204 (format "user/%d/password" (:id user))
+ {:password "abc123!!DEF", :old_password "def"})
+ (is (nil? (t2/select-one :model/Session :id (:id session)))
+ "the user's pre-existing session should be deleted after the password change")))))
+
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Deleting (Deactivating) a User -- DELETE /api/user/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
@@ -1677,6 +1719,7 @@
:last_name (mt/random-name)
:password "def123"}]
+ (auth-identity/set-password! id "def123")
(let [creds {:username "[email protected]"
:password "def123"}]
(testing "defaults to true"