Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Revoke OAuth tokens on every password change (#4191)

GFR5abf9de6e2a5
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rb
index c7d768fdbe..88f3605426 100644
--- a/app/controllers/api/v1/auth_controller.rb
+++ b/app/controllers/api/v1/auth_controller.rb
@@ -92,6 +92,9 @@ module Api
end
if user
+ # Taken before the reload below, so a password change after this check is noticed.
+ password_fingerprint = user.password_fingerprint
+
unless user.active?
render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized
return
@@ -133,10 +136,13 @@ module Api
end
begin
- token_response = device.issue_token!
+ token_response = device.issue_token!(password_fingerprint: password_fingerprint)
rescue User::InactiveError
render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized
return
+ rescue User::StaleCredentialsError
+ render json: { error: "Invalid email or password" }, status: :unauthorized
+ return
end
render json: token_response.merge(user: mobile_user_payload(user))
@@ -253,12 +259,16 @@ module Api
)
device = MobileDevice.upsert_device!(user, device_info)
- token_response = device.issue_token!
+ token_response = device.issue_token!(password_fingerprint: user.password_fingerprint)
end
rescue User::InactiveError
restore_linking_code!(linking_code, cached)
render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized
return
+ rescue User::StaleCredentialsError
+ restore_linking_code!(linking_code, cached)
+ render json: { error: "Invalid email or password" }, status: :unauthorized
+ return
rescue ActiveRecord::RecordInvalid => e
restore_linking_code!(linking_code, cached)
Rails.logger.error("[Auth] Device registration failed: #{e.message}")
diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb
index 2e7431d7f6..40bbc9c5d5 100644
--- a/app/controllers/concerns/authentication.rb
+++ b/app/controllers/concerns/authentication.rb
@@ -45,29 +45,39 @@ module Authentication
# Every sign-in path (password, OIDC, passkey, desktop exchange, MFA) mints
# its session here, so this is where the pre-auth Rails session is rotated
# to prevent fixation (CWE-384). Only an OIDC sign-in should ask to keep
- # the federated-logout keys it just stored.
- def create_session_for(user, preserve_oidc_handoff: false)
+ # the federated-logout keys it just stored. A path that checked the
+ # password passes the #password_fingerprint it saw, so a password change
+ # since that check ends the sign-in.
+ def create_session_for(user, preserve_oidc_handoff: false, password_fingerprint: nil)
return false unless user&.persisted?
# with_active_lock! has already refused an inactive user by the time the
# block runs, so a rejected sign-in never rotates the session.
- user.with_active_lock! do
+ user.with_active_lock!(password_fingerprint: password_fingerprint) do
rotate_rails_session(preserve_oidc_handoff: preserve_oidc_handoff)
session = user.sessions.create!
cookies.signed.permanent[:session_token] = { value: session.id, httponly: true }
session
end
- rescue User::InactiveError
+ rescue User::InactiveError, User::StaleCredentialsError
false
end
# Parks the user between the first factor and MFA. Only an OIDC sign-in
# carries federated-logout keys into the handoff; every other path drops
# whatever a previous OIDC session left behind, so a stale id_token_hint
- # can never be replayed into a locally authenticated session.
- def begin_mfa_handoff(user, from_oidc: false)
+ # can never be replayed into a locally authenticated session. A first
+ # factor that checked the password hands its #password_fingerprint on to
+ # the MFA step; any other first factor clears one left behind.
+ def begin_mfa_handoff(user, from_oidc: false, password_fingerprint: nil)
SESSION_KEYS_OIDC_HANDOFF.each { |key| session.delete(key) } unless from_oidc
session[:mfa_user_id] = user.id
+
+ if password_fingerprint
+ session[:mfa_password_fingerprint] = password_fingerprint
+ else
+ session.delete(:mfa_password_fingerprint)
+ end
end
def rotate_rails_session(preserve_oidc_handoff:)
diff --git a/app/controllers/mfa_controller.rb b/app/controllers/mfa_controller.rb
index 270af8377f..44e617ca2d 100644
--- a/app/controllers/mfa_controller.rb
+++ b/app/controllers/mfa_controller.rb
@@ -199,8 +199,10 @@ class MfaController < ApplicationController
# Cleared up front, as PasskeySessionsController does: a rejected user
# mints no session, so the rotation never runs to clear it for us.
session.delete(:mfa_user_id)
+ # Set only after a password check: a password change since then ends this sign-in.
+ password_fingerprint = session.delete(:mfa_password_fingerprint)
- @session = create_session_for(user, preserve_oidc_handoff: came_from_oidc)
+ @session = create_session_for(user, preserve_oidc_handoff: came_from_oidc, password_fingerprint: password_fingerprint)
return false unless @session
true
diff --git a/app/controllers/oidc_accounts_controller.rb b/app/controllers/oidc_accounts_controller.rb
index 26be6f75ce..5845e7d485 100644
--- a/app/controllers/oidc_accounts_controller.rb
+++ b/app/controllers/oidc_accounts_controller.rb
@@ -49,7 +49,7 @@ class OidcAccountsController < ApplicationController
)
unless user.otp_required?
- @session = create_session_for(user)
+ @session = create_session_for(user, password_fingerprint: user.password_fingerprint)
raise ActiveRecord::Rollback unless @session
end
@@ -65,7 +65,7 @@ class OidcAccountsController < ApplicationController
session.delete(:pending_oidc_auth)
if user.otp_required?
- begin_mfa_handoff(user)
+ begin_mfa_handoff(user, password_fingerprint: user.password_fingerprint)
redirect_to verify_mfa_path
else
redirect_to root_path, notice: t("sessions.openid_connect.account_linked", provider: @pending_auth["provider"])
diff --git a/app/controllers/password_resets_controller.rb b/app/controllers/password_resets_controller.rb
index e7266df0a3..9e2b1a6b4f 100644
--- a/app/controllers/password_resets_controller.rb
+++ b/app/controllers/password_resets_controller.rb
@@ -59,10 +59,10 @@ class PasswordResetsController < ApplicationController
next false unless @user.update(password_params)
SecurityAuditLog.log_password_changed!(user: @user, request: request)
- # The user is signed out on this path, so every session and every
- # OAuth token (mobile app included) goes (CWE-613).
+ # The user is signed out on this path, so every session goes
+ # (CWE-613). User#revoke_oauth_access has already revoked every OAuth
+ # token (mobile app included) as part of the update.
@user.sessions.destroy_all
- @user.revoke_oauth_tokens!
true
end
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index e494ba8dd4..d87757433f 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -76,11 +76,11 @@ class SessionsController < ApplicationController
if user.otp_required?
log_super_admin_override_login(user)
- begin_mfa_handoff(user)
+ begin_mfa_handoff(user, password_fingerprint: user.password_fingerprint)
redirect_to verify_mfa_path
else
log_super_admin_override_login(user)
- @session = create_session_for(user)
+ @session = create_session_for(user, password_fingerprint: user.password_fingerprint)
if @session
redirect_to root_path
diff --git a/app/models/mobile_device.rb b/app/models/mobile_device.rb
index af70fd043e..b6c08e44f5 100644
--- a/app/models/mobile_device.rb
+++ b/app/models/mobile_device.rb
@@ -80,8 +80,8 @@ class MobileDevice < ApplicationRecord
# already-checked the user seems. Raises User::InactiveError for a
# deactivated/concurrently-purged user, distinct from a genuine
# ActiveRecord::RecordInvalid from Doorkeeper::AccessToken.create! itself.
- def issue_token!
- user.with_active_lock! do
+ def issue_token!(password_fingerprint: nil)
+ user.with_active_lock!(password_fingerprint: password_fingerprint) do
revoke_all_tokens!
access_token = Doorkeeper::AccessToken.create!( # pipelock:ignore Credential in URL
diff --git a/app/models/user.rb b/app/models/user.rb
index 9f6e0a737a..a53ad93cfb 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -314,6 +314,14 @@ class User < ApplicationRecord
after_update_commit :purge_later, if: -> { saved_change_to_active?(from: true, to: false) }
after_update_commit :revoke_all_access_tokens, if: -> { saved_change_to_active?(from: true, to: false) }
+ # Runs inside the update's transaction: the user row stays locked until commit,
+ # so a concurrent /api/v1/auth/refresh (which takes the same lock) cannot mint
+ # a token the revocation misses. Doorkeeper's own /oauth/token refresh locks
+ # only the old token, so a refresh already holding it can still commit a new
+ # token the in-transaction sweep does not see; the second sweep after commit
+ # revokes it, and any later refresh finds the old token revoked.
+ after_update :revoke_oauth_access, if: :saved_change_to_password_digest?
+ after_update_commit :revoke_oauth_access, if: :saved_change_to_password_digest?
def deactivate
return true unless active?
@@ -396,18 +404,27 @@ class User < ApplicationRecord
# can never be confused with an unrelated persistence failure.
class InactiveError < StandardError; end
+ # Raised by #with_active_lock! when the password changed between the
+ # caller's password check and the locked issuance step. The new password's
+ # revocation sweep has already run by then, so issuing would hand out a
+ # session or token for the old password that nothing revokes.
+ class StaleCredentialsError < StandardError; end
+
# The one locked primitive for the actual authorization boundary: asserts
# this user is eligible for new session/token issuance *right now*, under
# a row lock, immediately before minting. Callers may additionally check
# #active? earlier for a fast, friendly rejection (skip an MFA/device
# round trip) — that's a UX optimization only, never a substitute for
# this check, however "obviously" already-checked the user seems.
- def with_active_lock!
+ # Pass the #password_fingerprint taken when the password was checked to
+ # also reject issuance after a concurrent password change.
+ def with_active_lock!(password_fingerprint: nil)
lock_acquired = false
with_lock do
lock_acquired = true
raise InactiveError unless active?
+ raise StaleCredentialsError if password_fingerprint && password_fingerprint != self.password_fingerprint
yield self
end
rescue ActiveRecord::RecordNotFound
@@ -545,6 +562,26 @@ class User < ApplicationRecord
end
end
+ # A new password must lock out whoever signed in to the mobile app or an
+ # OAuth client with the old one: their access and refresh tokens would
+ # otherwise stay valid for up to 30 days and keep renewing. API keys are
+ # created deliberately for integrations and do not depend on the password,
+ # so they stay.
+ def revoke_oauth_access
+ tokens_revoked, grants_revoked = revoke_oauth_tokens!
+
+ if tokens_revoked > 0 || grants_revoked > 0
+ Rails.logger.info(
+ "[AUTH] Revoked #{tokens_revoked} access token(s) and #{grants_revoked} authorization grant(s) " \
+ "after password change for user_id=#{id}"
+ )
+ end
+ end
+
+ def password_fingerprint
+ Digest::SHA256.hexdigest(password_digest.to_s)
+ end
+
def purge
if last_user_in_family?
family.destroy
diff --git a/test/controllers/admin/users_controller_test.rb b/test/controllers/admin/users_controller_test.rb
index 240901e578..18d2bba753 100644
--- a/test/controllers/admin/users_controller_test.rb
+++ b/test/controllers/admin/users_controller_test.rb
@@ -348,6 +348,17 @@ class Admin::UsersControllerTest < ActionDispatch::IntegrationTest
assert_not Session.exists?(other.id)
end
+ test "setting a user's password revokes that user's OAuth access tokens" do
+ target = users(:family_member)
+ oauth_app = Doorkeeper::Application.create!(name: "Sure Mobile", redirect_uri: "https://client.example.com/callback", scopes: "read_write")
+ access_token = Doorkeeper::AccessToken.create!(application: oauth_app, resource_owner_id: target.id, expires_in: 2.hours, scopes: "read_write", use_refresh_token: true)
+
+ patch admin_user_url(target), params: { user: { role: target.role, password: "Secure1!pass" } }
+
+ assert_redirected_to admin_users_url
+ assert access_token.reload.revoked?, "a mobile or OAuth token must not outlive an admin password reset"
+ end
+
test "a role-only change leaves the user's sessions alone" do
target = users(:family_member)
session_record = target.sessions.create!
diff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rb
index 669cb2b584..e26b46a8cb 100644
--- a/test/controllers/api/v1/auth_controller_test.rb
+++ b/test/controllers/api/v1/auth_controller_test.rb
@@ -393,6 +393,52 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
assert response_data["mfa_required"]
end
+ test "should not issue a token when the password changes during login" do
+ user = users(:family_admin)
+ user.mobile_devices.destroy_all
+ device = user.mobile_devices.create!(@device_info)
+
+ # The password changes after the login checked it but before the token is minted.
+ MobileDevice.stubs(:upsert_device!).with do |*|
+ User.find(user.id).update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")
+ true
+ end.returns(device)
+
+ assert_no_difference("Doorkeeper::AccessToken.count") do
+ post "/api/v1/auth/login", params: {
+ email: user.email,
+ password: user_password_test,
+ device: @device_info
+ }
+ end
+
+ assert_response :unauthorized
+ assert_equal "Invalid email or password", JSON.parse(response.body)["error"]
+ end
+
+ test "should not issue a token when the password changes before the login reloads the user" do
+ user = users(:family_admin)
+ user.mobile_devices.destroy_all
+
+ # The password changes right after the login checked it; the reload then sees the new digest.
+ Api::V1::AuthController.any_instance.stubs(:user_reloadable_and_active?).with do |reloaded_user|
+ User.find(reloaded_user.id).update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")
+ reloaded_user.reload
+ true
+ end.returns(true)
+
+ assert_no_difference("Doorkeeper::AccessToken.count") do
+ post "/api/v1/auth/login", params: {
+ email: user.email,
+ password: user_password_test,
+ device: @device_info
+ }
+ end
+
+ assert_response :unauthorized
+ assert_equal "Invalid email or password", JSON.parse(response.body)["error"]
+ end
+
test "should login with valid MFA code" do
user = users(:family_admin)
password = user_password_test
@@ -659,6 +705,33 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
assert_not initial_token.reload.revoked?, "the still-valid old token should be left alone, not silently revoked"
end
+ test "should not refresh a token issued before a password change" do
+ user = users(:family_admin)
+ device = user.mobile_devices.create!(@device_info)
+
+ initial_token = Doorkeeper::AccessToken.create!(
+ application: @shared_app,
+ resource_owner_id: user.id,
+ mobile_device_id: device.id,
+ expires_in: 30.days.to_i,
+ scopes: "read_write",
+ use_refresh_token: true
+ )
+
+ user.update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")
+
+ assert_no_difference("Doorkeeper::AccessToken.count") do
+ post "/api/v1/auth/refresh", params: {
+ refresh_token: initial_token.refresh_token,
+ device: @device_info
+ }
+ end
+
+ assert_response :unauthorized
+ assert_equal "Invalid refresh token", JSON.parse(response.body)["error"]
+ assert initial_token.reload.revoked?
+ end
+
test "should not refresh with invalid refresh token" do
assert_no_difference("Doorkeeper::AccessToken.count") do
post "/api/v1/auth/refresh", params: {
diff --git a/test/controllers/mfa_controller_test.rb b/test/controllers/mfa_controller_test.rb
index c6837f3d0b..1470851bd3 100644
--- a/test/controllers/mfa_controller_test.rb
+++ b/test/controllers/mfa_controller_test.rb
@@ -196,6 +196,23 @@ class MfaControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to new_session_path
end
+ test "verify_code cannot create a session after the password changed" do
+ @user.setup_mfa!
+ @user.enable_mfa!
+ sign_out
+
+ post sessions_path, params: { email: @user.email, password: user_password_test }
+ assert_redirected_to verify_mfa_path
+
+ totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")
+ User.find(@user.id).update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")
+
+ assert_no_difference -> { Session.where(user_id: @user.id).count } do
+ post verify_mfa_path, params: { code: totp.now }
+ end
+ assert_redirected_to new_session_path
+ end
+
test "verify_code authenticates with valid backup code" do
@user.setup_mfa!
backup_code = @user.enable_mfa!.first
diff --git a/test/controllers/passwords_controller_test.rb b/test/controllers/passwords_controller_test.rb
index b14236ed12..88a083491f 100644
--- a/test/controllers/passwords_controller_test.rb
+++ b/test/controllers/passwords_controller_test.rb
@@ -31,6 +31,16 @@ class PasswordsControllerTest < ActionDispatch::IntegrationTest
assert Session.exists?(@current_session.id)
end
+ test "changing the password revokes the user's OAuth access tokens" do
+ oauth_app = Doorkeeper::Application.create!(name: "Sure Mobile", redirect_uri: "https://client.example.com/callback", scopes: "read_write")
+ access_token = Doorkeeper::AccessToken.create!(application: oauth_app, resource_owner_id: @user.id, expires_in: 2.hours, scopes: "read_write", use_refresh_token: true)
+
+ patch password_path, params: { user: { password_challenge: user_password_test, password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }
+
+ assert_redirected_to root_path
+ assert access_token.reload.revoked?, "a mobile or OAuth token must not outlive a password change"
+ end
+
test "update rejects a wrong current password" do
assert_password_unchanged do
patch password_path, params: { user: { password_challenge: "wrongpassword123", password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }
diff --git a/test/models/user_test.rb b/test/models/user_test.rb
index 9b3fa83c0e..a6a272c861 100644
--- a/test/models/user_test.rb
+++ b/test/models/user_test.rb
@@ -1644,6 +1644,105 @@ class UserTest < ActiveSupport::TestCase
assert @user.valid?
end
+ test "changing the password revokes OAuth access tokens and grants but keeps API keys" do
+ user = users(:family_member)
+ api_key = ApiKey.create!( # pipelock:ignore
+ user: user,
+ name: "Test Key",
+ display_key: "test_password_key_#{SecureRandom.hex(8)}",
+ scopes: [ "read" ]
+ )
+ app = Doorkeeper::Application.create!(
+ name: "Test App #{SecureRandom.hex(4)}",
+ redirect_uri: "https://example.com/callback",
+ confidential: false
+ )
+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: user.id,
+ scopes: "read_write",
+ expires_in: 1.year,
+ use_refresh_token: true
+ )
+ grant = Doorkeeper::AccessGrant.create!(
+ application: app,
+ resource_owner_id: user.id,
+ redirect_uri: app.redirect_uri,
+ expires_in: 10.minutes,
+ scopes: "read_write"
+ )
+ other_token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: users(:family_admin).id,
+ scopes: "read_write",
+ expires_in: 1.year
+ )
+
+ user.update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")
+
+ assert token.reload.revoked_at.present?
+ assert grant.reload.revoked_at.present?
+ assert api_key.reload.active?
+ assert_nil other_token.reload.revoked_at
+ end
+
+ test "updating a user without changing the password keeps OAuth access tokens" do
+ user = users(:family_member)
+ app = Doorkeeper::Application.create!(
+ name: "Test App #{SecureRandom.hex(4)}",
+ redirect_uri: "https://example.com/callback",
+ confidential: false
+ )
+ token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: user.id,
+ scopes: "read_write",
+ expires_in: 1.year
+ )
+
+ user.update!(first_name: "Renamed")
+
+ assert_nil token.reload.revoked_at
+ end
+
+ test "changing the password revokes a token minted before the change commits" do
+ user = users(:family_member)
+ app = Doorkeeper::Application.create!(
+ name: "Test App #{SecureRandom.hex(4)}",
+ redirect_uri: "https://example.com/callback",
+ confidential: false
+ )
+ late_token = nil
+
+ User.transaction do
+ user.update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")
+ # Stands in for a concurrent /oauth/token refresh that held the old token's
+ # row lock and committed its replacement after the in-transaction sweep.
+ late_token = Doorkeeper::AccessToken.create!( # pipelock:ignore
+ application: app,
+ resource_owner_id: user.id,
+ scopes: "read_write",
+ expires_in: 1.year,
+ use_refresh_token: true
+ )
+ end
+
+ assert late_token.reload.revoked_at.present?
+ end
+
+ test "with_active_lock! rejects a password fingerprint taken before a password change" do
+ user = users(:family_member)
+ fingerprint = user.password_fingerprint
+
+ assert_equal :ok, user.with_active_lock!(password_fingerprint: fingerprint) { :ok }
+
+ User.find(user.id).update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")
+
+ assert_raises(User::StaleCredentialsError) do
+ user.with_active_lock!(password_fingerprint: fingerprint) { flunk "must not run" }
+ end
+ end
+
test "update_manual_account_order keeps other groups and only accessible accounts" do
@user.update_manual_account_order("credit_card", [ accounts(:credit_card).id ])
foreign = families(:empty).accounts.create!(name: "Foreign", currency: "USD", balance: 0, accountable: Depository.new, owner: users(:empty))