The personal finance app for everyone (by everyone)
Ruby
security: consolidate deactivated-user auth enforcement (#3504)
GFR698ab19d435e
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rbindex bf0619be03..16c3d852c0 100644--- a/app/controllers/api/v1/auth_controller.rb+++ b/app/controllers/api/v1/auth_controller.rb@@ -63,7 +63,7 @@ module Apidevice = MobileDevice.upsert_device!(user, device_params)token_response = device.issue_token!end- rescue ActiveRecord::RecordInvalid => e+ rescue ActiveRecord::RecordInvalid, User::InactiveError => eRails.logger.error("[Auth] Device registration failed: #{e.class} - #{e.message}")render json: { error: "Failed to register device" }, status: :unprocessable_entityreturn@@ -101,8 +101,9 @@ module Api# Fast-path re-check to skip a pointless device upsert for a user# already known to be inactive — issue_token! re-checks active? under# lock immediately before minting (see its comment) and is the actual- # authorization boundary, not this check.- unless user.reload.active?+ # authorization boundary, not this check. Treats a concurrently+ # purged user (reload raises RecordNotFound) the same as inactive.+ unless user_reloadable_and_active?(user)render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorizedreturnend@@ -117,7 +118,7 @@ module Apibegintoken_response = device.issue_token!- rescue ActiveRecord::RecordInvalid+ rescue User::InactiveErrorrender json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorizedreturnend@@ -193,15 +194,40 @@ module Api# Atomically claim the code before creating the identityreturn render json: { error: "Linking code is invalid or expired" }, status: :unauthorized unless consume_linking_code!(linking_code)- OidcIdentity.create_from_omniauth(build_omniauth_hash(cached), user)+ device_info = cached[:device_info]+ device_info = device_info.symbolize_keys if device_info.respond_to?(:symbolize_keys)- SsoAuditLog.log_link!(- user: user,- provider: cached[:provider],- request: request- )+ # Identity creation, the audit record, and the actual token mint all+ # run in one transaction so a rejected request can't leave a linked+ # identity or a successful-link audit record behind. issue_token!'s+ # locked active? recheck (the real authorization boundary) is what+ # decides whether this commits or rolls everything back together.+ token_response = nil+ begin+ ActiveRecord::Base.transaction do+ OidcIdentity.create_from_omniauth(build_omniauth_hash(cached), user)++ SsoAuditLog.log_link!(+ user: user,+ provider: cached[:provider],+ request: request+ )++ device = MobileDevice.upsert_device!(user, device_info)+ token_response = device.issue_token!+ 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 ActiveRecord::RecordInvalid => e+ restore_linking_code!(linking_code, cached)+ Rails.logger.error("[Auth] Device registration failed: #{e.message}")+ render json: { error: "Failed to register device" }, status: :unprocessable_entity+ return+ end- issue_mobile_tokens(user, cached[:device_info])+ render json: token_response.merge(user: mobile_user_payload(user))enddef sso_create_account@@ -324,9 +350,7 @@ module Apiuser = User.find_by(id: access_token.resource_owner_id)new_token = begin- user&.with_lock do- next false unless user.active?-+ user&.with_active_lock! doaccess_token.with_lock donext false if access_token.revoked?@@ -345,7 +369,7 @@ module Apitokenendend- rescue ActiveRecord::RecordNotFound+ rescue ActiveRecord::RecordNotFound, User::InactiveErrorfalseend@@ -425,6 +449,16 @@ module Api}end+ # A concurrent purge between the initial check and this fast-path+ # re-check raises RecordNotFound on reload; treat it the same as+ # inactive instead of letting it fall through to BaseController's+ # generic record_not_found handler.+ def user_reloadable_and_active?(user)+ user.reload.active?+ rescue ActiveRecord::RecordNotFound+ false+ end+def build_omniauth_hash(cached)OpenStruct.new(provider: cached[:provider],@@ -467,12 +501,23 @@ module ApiRails.cache.delete("mobile_sso_link:#{linking_code}")end- # Shared by sso_link (existing user, needs the active? re-check) and- # sso_create_account (brand-new user, always active — the reload is- # a harmless no-op there). Reload right before minting, same- # reasoning as Authentication#create_session_for.+ # Best-effort restore so a request rejected *after* consuming the+ # code (deactivation race or a device-registration failure inside+ # the transaction) can retry with the same code instead of+ # restarting the SSO flow from the IdP. Safe to write back verbatim:+ # a legitimate retry re-authenticates with email/password from+ # scratch, and OidcIdentity's unique (provider, uid) index is the+ # backstop if a second request somehow raced onto the restored code.+ def restore_linking_code!(linking_code, cached)+ Rails.cache.write("mobile_sso_link:#{linking_code}", cached, expires_in: 10.minutes)+ end++ # Used by sso_create_account for its brand-new user (always active —+ # the reload is a harmless no-op there, but still races a concurrent+ # purge the same way login's fast path does). Reload right before+ # minting, same reasoning as Authentication#create_session_for.def issue_mobile_tokens(user, device_info)- unless user.reload.active?+ unless user_reloadable_and_active?(user)render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorizedreturnend@@ -489,7 +534,7 @@ module Apibegintoken_response = device.issue_token!- rescue ActiveRecord::RecordInvalid+ rescue User::InactiveErrorrender json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorizedreturnenddiff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rbindex c2584ca24c..1ad099a395 100644--- a/app/controllers/concerns/authentication.rb+++ b/app/controllers/concerns/authentication.rb@@ -43,14 +43,12 @@ module Authenticationdef create_session_for(user)return false unless user&.persisted?- user.with_lock do- next false unless user.active?-+ user.with_active_lock! dosession = user.sessions.create!cookies.signed.permanent[:session_token] = { value: session.id, httponly: true }sessionend- rescue ActiveRecord::RecordNotFound+ rescue User::InactiveErrorfalseenddiff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rbindex 1366e7aaa4..cbaee7d531 100644--- a/app/controllers/sessions_controller.rb+++ b/app/controllers/sessions_controller.rb@@ -226,14 +226,6 @@ class SessionsController < ApplicationControllerreturnend- # Same reasoning as SessionsController#create: check before starting the- # MFA challenge, not just after, so a stale in-flight login can't finish- # once the user is reactivated.- unless user.active?- redirect_to new_session_path, alert: t("sessions.create.account_deactivated")- return- end-if user.otp_required?session[:mfa_user_id] = user.idredirect_to verify_mfa_path@@ -420,8 +412,10 @@ class SessionsController < ApplicationController# openid_connect already checked user.active? before dispatching here,# but record_authentication!/sync_user_attributes!/audit logging run in# between — reload right before actually minting a token to narrow that- # window, same reasoning as Authentication#create_session_for.- unless user.reload.active?+ # window, same reasoning as Authentication#create_session_for. Treats a+ # concurrently purged user (reload raises RecordNotFound) the same as+ # inactive instead of letting it fall through to a generic 404.+ unless user_reloadable_and_active?(user)Rails.logger.warn("[AUTH] Rejected mobile SSO token issuance for deactivated user_id=#{user.id}")session.delete(:mobile_sso)mobile_sso_redirect(error: "account_deactivated", message: t("sessions.create.account_deactivated"))@@ -445,7 +439,7 @@ class SessionsController < ApplicationControllerbegintoken_response = device.issue_token!- rescue ActiveRecord::RecordInvalid+ rescue User::InactiveErrorRails.logger.warn("[AUTH] Rejected mobile SSO token issuance for deactivated user_id=#{user.id}")mobile_sso_redirect(error: "account_deactivated", message: t("sessions.create.account_deactivated"))return@@ -529,6 +523,16 @@ class SessionsController < ApplicationControllerredirect_to "sureapp://oauth/callback?#{params.to_query}", allow_other_host: trueend+ # A concurrent purge between the initial check and this fast-path+ # re-check raises RecordNotFound on reload; treat it the same as+ # inactive instead of letting it fall through to StoreLocation's+ # generic not-found handler.+ def user_reloadable_and_active?(user)+ user.reload.active?+ rescue ActiveRecord::RecordNotFound+ false+ end+def set_session@session = Current.user.sessions.find(params[:id])enddiff --git a/app/models/mobile_device.rb b/app/models/mobile_device.rbindex e78a3444dd..f24c0b904a 100644--- a/app/models/mobile_device.rb+++ b/app/models/mobile_device.rb@@ -68,20 +68,17 @@ class MobileDevice < ApplicationRecord# response or deep-link callback.## This is the single choke point every mobile-token-issuing path funnels- # through, so the active? check lives here (under lock, immediately before- # minting) rather than at each call site. Callers may *additionally* check- # active? earlier for fast, friendly rejection (skip an MFA/device-validation- # round trip, avoid a pointless MobileDevice upsert) — but that's a UX- # optimization only. This check is the actual authorization boundary and- # must never be assumed redundant by a caller, however "obviously"- # already-checked the user seems.+ # through, so User#with_active_lock! (the actual authorization boundary,+ # locked immediately before minting) lives here rather than at each call+ # site. Callers may *additionally* check active? earlier for fast, friendly+ # rejection (skip an MFA/device-validation round trip, avoid a pointless+ # MobileDevice upsert) — but that's a UX optimization only and must never+ # be assumed a substitute for this check, however "obviously"+ # 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_lock do- unless user.active?- errors.add(:base, "User is inactive")- raise ActiveRecord::RecordInvalid, self- end-+ user.with_active_lock! dorevoke_all_tokens!access_token = Doorkeeper::AccessToken.create!( # pipelock:ignore Credential in URL@@ -101,9 +98,6 @@ class MobileDevice < ApplicationRecordcreated_at: access_token.created_at.to_i}end- rescue ActiveRecord::RecordNotFound- errors.add(:base, "User is inactive")- raise ActiveRecord::RecordInvalid, selfendprivatediff --git a/app/models/user.rb b/app/models/user.rbindex b7f7331413..7950a50623 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -324,6 +324,36 @@ class User < ApplicationRecordoidc_identities.destroy_allend+ # Raised by #with_active_lock! to reject session/token issuance for a+ # deactivated or concurrently-purged user. The one error contract every+ # web/JSON/mobile/OAuth-adapter caller rescues, so a deactivation result+ # can never be confused with an unrelated persistence failure.+ class InactiveError < 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!+ lock_acquired = false++ with_lock do+ lock_acquired = true+ raise InactiveError unless active?+ yield self+ end+ rescue ActiveRecord::RecordNotFound+ # Only translate a RecordNotFound raised by with_lock's own reload (the+ # row was deleted by a concurrent purge before we could lock it) into+ # InactiveError. Once the lock is held, re-raise: a RecordNotFound from+ # inside the caller's block is an unrelated failure and must not be+ # misreported as "inactive" either.+ raise if lock_acquired+ raise InactiveError+ end+def can_deactivateif admin? && family.users.count > 1errors.add(:base, :cannot_deactivate_admin_with_other_users)diff --git a/db/migrate/20260910130000_nullify_sessions_active_impersonator_session_on_delete.rb b/db/migrate/20260910130000_nullify_sessions_active_impersonator_session_on_delete.rbnew file mode 100644index 0000000000..e6c94ff3ae--- /dev/null+++ b/db/migrate/20260910130000_nullify_sessions_active_impersonator_session_on_delete.rb@@ -0,0 +1,11 @@+class NullifySessionsActiveImpersonatorSessionOnDelete < ActiveRecord::Migration[7.2]+ def up+ remove_foreign_key :sessions, :impersonation_sessions, column: :active_impersonator_session_id+ add_foreign_key :sessions, :impersonation_sessions, column: :active_impersonator_session_id, on_delete: :nullify+ end++ def down+ remove_foreign_key :sessions, :impersonation_sessions, column: :active_impersonator_session_id+ add_foreign_key :sessions, :impersonation_sessions, column: :active_impersonator_session_id+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 728ad397e5..3d5e057152 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_09_04_201444) do+ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -2758,7 +2758,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_04_201444) doadd_foreign_key "rule_runs", "rules"add_foreign_key "rules", "families"add_foreign_key "security_prices", "securities"- add_foreign_key "sessions", "impersonation_sessions", column: "active_impersonator_session_id"+ add_foreign_key "sessions", "impersonation_sessions", column: "active_impersonator_session_id", on_delete: :nullifyadd_foreign_key "sessions", "users"add_foreign_key "simplefin_accounts", "simplefin_items"add_foreign_key "simplefin_items", "families"diff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rbindex e4dd9dfd05..18f11d0087 100644--- a/test/controllers/api/v1/auth_controller_test.rb+++ b/test/controllers/api/v1/auth_controller_test.rb@@ -685,14 +685,49 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest}, expires_in: 10.minutes)# Simulate deactivation landing after the initial active? check but- # before issue_mobile_tokens actually mints a token — SsoAuditLog.log_link!+ # before issue_token! actually mints a token — SsoAuditLog.log_link!# runs in that window in the real flow, so hook the deactivation there.SsoAuditLog.stubs(:log_link!).with do |**kwargs|kwargs[:user].update_column(:active, false)trueend- assert_difference("OidcIdentity.count", 1) do+ # The identity, the device, and the token mint all run in the same+ # transaction as the locked active? recheck, so a deactivation landing+ # in that window must roll all of it back — nothing may survive a+ # rejected request.+ assert_no_difference [ "OidcIdentity.count", "MobileDevice.count", "Doorkeeper::AccessToken.count" ] do+ post "/api/v1/auth/sso_link", params: {+ linking_code: linking_code,+ email: user.email,+ password: user_password_test+ }+ end++ assert_response :unauthorized+ response_data = JSON.parse(response.body)+ assert_equal "This account has been deactivated. Please contact an administrator.", response_data["error"]++ # The code was already consumed before the rejected transaction; it+ # must be restored so the user can retry instead of restarting the+ # whole SSO flow from the IdP.+ assert Rails.cache.read("mobile_sso_link:#{linking_code}").present?, "Expected linking code to be restored after a rejected request"+ end++ test "should restore the linking code when device registration fails during sso_link" do+ user = users(:family_admin)++ linking_code = SecureRandom.urlsafe_base64(32)+ invalid_device_info = @device_info.merge(device_type: "invalid-type")+ Rails.cache.write("mobile_sso_link:#{linking_code}", {+ provider: "google_oauth2",+ uid: "google-uid-device-failure",+ email: "[email protected]",+ device_info: invalid_device_info.stringify_keys,+ allow_account_creation: true+ }, expires_in: 10.minutes)++ assert_no_difference [ "OidcIdentity.count", "MobileDevice.count" ] dopost "/api/v1/auth/sso_link", params: {linking_code: linking_code,email: user.email,@@ -700,6 +735,27 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest}end+ assert_response :unprocessable_entity+ response_data = JSON.parse(response.body)+ assert_equal "Failed to register device", response_data["error"]++ assert Rails.cache.read("mobile_sso_link:#{linking_code}").present?, "Expected linking code to be restored after a rejected request"+ end++ test "login rejects a user purged between authentication and the reload fast-path" do+ user = users(:family_admin)+ User.stubs(:find_by).with(email: user.email).returns(user)+ user.stubs(:reload).raises(ActiveRecord::RecordNotFound)++ post "/api/v1/auth/login", params: {+ email: user.email,+ password: user_password_test,+ device: @device_info+ }++ # Must fall through to the same "deactivated" response every other+ # rejection on this endpoint uses, not BaseController's generic+ # record_not_found handler.assert_response :unauthorizedresponse_data = JSON.parse(response.body)assert_equal "This account has been deactivated. Please contact an administrator.", response_data["error"]diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rbindex 461698da5c..796a617ab6 100644--- a/test/controllers/sessions_controller_test.rb+++ b/test/controllers/sessions_controller_test.rb@@ -656,6 +656,45 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestassert_nil session[:mobile_sso], "Expected mobile_sso session to be cleared"end+ test "mobile SSO rejects a user purged between the initial check and token issuance" do+ oidc_identity = oidc_identities(:bob_google)++ setup_omniauth_mock(+ provider: oidc_identity.provider,+ uid: oidc_identity.uid,+ email: @user.email,+ name: "Bob Dylan"+ )++ Rails.configuration.x.auth.stubs(:sso_providers).returns([+ { name: "openid_connect", strategy: "openid_connect", label: "Google" }+ ])++ get "/auth/mobile/openid_connect", params: {+ device_id: "flutter-device-012",+ device_name: "Pixel 8",+ device_type: "android"+ }++ # Same window as the deactivation race above, but the row disappears+ # entirely (async purge) instead of merely flipping active: false — the+ # reload fast-path must treat RecordNotFound the same as inactive rather+ # than letting it fall through to StoreLocation's generic 404.+ SsoAuditLog.stubs(:log_login!).with do |**kwargs|+ kwargs[:user].stubs(:reload).raises(ActiveRecord::RecordNotFound)+ true+ end++ assert_no_difference [ "Doorkeeper::AccessToken.count", "MobileDevice.count" ] do+ get "/auth/openid_connect/callback"+ end++ redirect_url = @response.redirect_url+ params = Rack::Utils.parse_query(URI.parse(redirect_url).query)+ assert_equal "account_deactivated", params["error"]+ assert_nil session[:mobile_sso], "Expected mobile_sso session to be cleared"+ end+test "mobile SSO refuses to issue a token for a deactivated user" dooidc_identity = oidc_identities(:bob_google)@user.update_column(:active, false)diff --git a/test/integration/oauth_basic_test.rb b/test/integration/oauth_basic_test.rbindex 063bca37a3..60bc714855 100644--- a/test/integration/oauth_basic_test.rb+++ b/test/integration/oauth_basic_test.rb@@ -36,6 +36,43 @@ class OauthBasicTest < ActionDispatch::IntegrationTestassert_not Session.exists?(id: session_record.id), "stale session should be destroyed, not just skipped"end+ test "oauth token endpoint refuses a refresh_token exchange after the user is deactivated" do+ oauth_app = Doorkeeper::Application.create!(+ name: "Test API Client",+ redirect_uri: "https://client.example.com/callback",+ scopes: "read_write"+ )+ user = users(:family_admin)++ access_token = Doorkeeper::AccessToken.create!(+ application: oauth_app,+ resource_owner_id: user.id,+ expires_in: 2.hours,+ scopes: "read_write",+ use_refresh_token: true+ )+ refresh_token = access_token.plaintext_refresh_token++ # update_column bypasses callbacks (same idiom as the test above), then+ # explicitly exercises User#revoke_all_access_tokens — the mechanism+ # that actually revokes standard Doorkeeper grants/tokens on+ # deactivation, since this endpoint never goes through our custom+ # Authentication concern or MobileDevice#issue_token! at all.+ user.update_column(:active, false)+ user.revoke_all_access_tokens++ post "/oauth/token", params: {+ grant_type: "refresh_token",+ refresh_token: refresh_token,+ client_id: oauth_app.uid,+ client_secret: oauth_app.secret+ }++ assert_response :bad_request+ response_body = JSON.parse(response.body)+ assert_equal "invalid_grant", response_body["error"]+ end+test "oauth token endpoint exists and handles requests" dopost "/oauth/token", params: {grant_type: "authorization_code",diff --git a/test/models/mobile_device_test.rb b/test/models/mobile_device_test.rbindex 7745a2a59e..a0d2c981b0 100644--- a/test/models/mobile_device_test.rb+++ b/test/models/mobile_device_test.rb@@ -31,7 +31,21 @@ class MobileDeviceTest < ActiveSupport::TestCaseuser.update_column(:active, false)assert_no_difference "Doorkeeper::AccessToken.count" do- assert_raises(ActiveRecord::RecordInvalid) { device.issue_token! }+ assert_raises(User::InactiveError) { device.issue_token! }endend++ test "issue_token! does not report a genuine persistence failure as an inactive user" do+ user = users(:family_member)+ device = user.mobile_devices.create!(+ device_id: "persistence-failure-test",+ device_name: "Persistence failure test device",+ device_type: "ios"+ )+ assert user.active?++ Doorkeeper::AccessToken.stubs(:create!).raises(ActiveRecord::RecordInvalid.new(Doorkeeper::AccessToken.new))++ assert_raises(ActiveRecord::RecordInvalid) { device.issue_token! }+ endenddiff --git a/test/models/user_test.rb b/test/models/user_test.rbindex d94997cc90..a16e1a0660 100644--- a/test/models/user_test.rb+++ b/test/models/user_test.rb@@ -962,6 +962,53 @@ class UserTest < ActiveSupport::TestCaseendend+ test "purging an impersonated user nullifies the admin's active_impersonator_session instead of failing" do+ admin = users(:sure_support_staff)+ target = users(:family_member)+ impersonation = ImpersonationSession.create!(impersonator: admin, impersonated: target, status: :in_progress)+ admin_session = admin.sessions.create!(active_impersonator_session: impersonation)++ # UserPurgeJob may run before the admin's next request notices the+ # target is gone — dependent: :destroy on User#impersonated_support_sessions+ # destroys the ImpersonationSession row underneath the admin's still-live+ # Session. Without ON DELETE SET NULL on that FK, this raises+ # ActiveRecord::InvalidForeignKey instead of completing the purge.+ perform_enqueued_jobs do+ target.purge+ end++ assert_not User.exists?(target.id)+ assert_nil admin_session.reload.active_impersonator_session_id+ end++ test "with_active_lock! rejects an inactive user without yielding" do+ @user.update_column(:active, false)+ yielded = false++ assert_raises(User::InactiveError) do+ @user.with_active_lock! { yielded = true }+ end++ assert_not yielded+ end++ test "with_active_lock! translates RecordNotFound only when the lock itself can't find the row" do+ @user.stubs(:with_lock).raises(ActiveRecord::RecordNotFound)++ assert_raises(User::InactiveError) do+ @user.with_active_lock! { flunk "should not yield when the row can't be locked" }+ end+ end++ test "with_active_lock! does not misreport a RecordNotFound raised inside the yielded block" do+ # A failure unrelated to the user's own activity status (e.g. resolving+ # some other record inside the caller's block) must propagate as-is,+ # not get swallowed into "this user is inactive".+ assert_raises(ActiveRecord::RecordNotFound) do+ @user.with_active_lock! { raise ActiveRecord::RecordNotFound, "unrelated record missing" }+ end+ end+test "deactivate refuses the last active super admin" dofamily = Family.create!(name: "Sole admin family", locale: "en", date_format: "%m-%d-%Y", currency: "USD")target = User.create!(