The personal finance app for everyone (by everyone)
Ruby
fix(auth): close remaining deactivated-user session/token gaps (post-#3131 rebase) (#2890)
GFRab908e47aa96
diff --git a/app/constraints/super_admin_constraint.rb b/app/constraints/super_admin_constraint.rbindex 39acc8b53e..675108dfba 100644--- a/app/constraints/super_admin_constraint.rb+++ b/app/constraints/super_admin_constraint.rb@@ -15,7 +15,18 @@ class SuperAdminConstraintcookie_value = request.cookie_jar.signed[:session_token]return false if cookie_value.blank?- Session.find_by(id: cookie_value)&.user&.super_admin? || false+ session_record = Session.find_by(id: cookie_value)+ return false unless session_record++ unless session_record.user&.active?+ # Same cleanup as Authentication#find_session_by_cookie — a stale+ # session belonging to a deactivated user is destroyed here, not just+ # denied, so it can't be reused once found.+ session_record.destroy+ return false+ end++ session_record.user.super_admin?rescue => eRails.logger.warn("SuperAdminConstraint rejected request: #{e.class}: #{e.message}")falsediff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rbindex 49515a58bb..bf0619be03 100644--- a/app/controllers/api/v1/auth_controller.rb+++ b/app/controllers/api/v1/auth_controller.rb@@ -76,6 +76,11 @@ module Apiuser = User.find_by(email: params[:email])if user&.authenticate(params[:password])+ unless user.active?+ render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized+ return+ end+# Check MFA if enabledif user.otp_required?unless params[:otp_code].present? && user.verify_otp?(params[:otp_code])@@ -93,16 +98,30 @@ module Apireturnend- # Create device and OAuth token+ # 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?+ render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized+ return+ end+begindevice = MobileDevice.upsert_device!(user, device_params)- token_response = device.issue_token!rescue ActiveRecord::RecordInvalid => eRails.logger.error("[Auth] Device registration failed: #{e.message}")render json: { error: "Failed to register device" }, status: :unprocessable_entityreturnend+ begin+ token_response = device.issue_token!+ rescue ActiveRecord::RecordInvalid+ render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized+ return+ end+render json: token_response.merge(user: mobile_user_payload(user))elserender json: { error: "Invalid email or password" }, status: :unauthorized@@ -156,11 +175,16 @@ module Apiuser = User.authenticate_by(email: params[:email], password: params[:password])- unless user&.active?+ unless userrender json: { error: "Invalid email or password" }, status: :unauthorizedreturnend+ unless user.active?+ render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized+ return+ end+if user.otp_required?render json: { error: "MFA users should sign in with email and password", mfa_required: true }, status: :unauthorizedreturn@@ -443,15 +467,34 @@ 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.def issue_mobile_tokens(user, device_info)+ unless user.reload.active?+ render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized+ return+ end+device_info = device_info.symbolize_keys if device_info.respond_to?(:symbolize_keys)- device = MobileDevice.upsert_device!(user, device_info)- token_response = device.issue_token!++ begin+ device = MobileDevice.upsert_device!(user, device_info)+ rescue ActiveRecord::RecordInvalid => e+ Rails.logger.error("[Auth] Device registration failed: #{e.message}")+ render json: { error: "Failed to register device" }, status: :unprocessable_entity+ return+ end++ begin+ token_response = device.issue_token!+ rescue ActiveRecord::RecordInvalid+ render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized+ return+ endrender json: token_response.merge(user: mobile_user_payload(user))- rescue ActiveRecord::RecordInvalid => e- Rails.logger.error("[Auth] Device registration failed: #{e.message}")- render json: { error: "Failed to register device" }, status: :unprocessable_entityenddef ensure_write_scopediff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rbindex b724720f74..c2584ca24c 100644--- a/app/controllers/concerns/authentication.rb+++ b/app/controllers/concerns/authentication.rb@@ -18,6 +18,7 @@ module Authenticationdef authenticate_user!if session_record = find_session_by_cookieCurrent.session = session_record+ end_impersonation_if_target_inactive!elseif self_hosted_first_login?redirect_to new_registration_url@@ -53,6 +54,21 @@ module Authenticationfalseend+ # If a super admin is currently impersonating a user who gets deactivated+ # mid-session, end the impersonation (same mechanism as+ # ImpersonationSessionsController#leave) rather than logging the admin out+ # entirely — their own session is still valid.+ def end_impersonation_if_target_inactive!+ impersonation = Current.session&.active_impersonator_session+ return unless impersonation && !impersonation.impersonated.active?++ Rails.logger.warn(+ "[AUTH] Ending impersonation_session_id=#{impersonation.id}: " \+ "impersonated user_id=#{impersonation.impersonated_id} is deactivated"+ )+ Current.session.update!(active_impersonator_session: nil)+ end+def self_hosted_first_login?Rails.application.config.app_mode.self_hosted? && User.count.zero?enddiff --git a/app/controllers/impersonation_sessions_controller.rb b/app/controllers/impersonation_sessions_controller.rbindex 1a8c5db7ec..42811cf08f 100644--- a/app/controllers/impersonation_sessions_controller.rb+++ b/app/controllers/impersonation_sessions_controller.rb@@ -9,6 +9,13 @@ class ImpersonationSessionsController < ApplicationControllerdef join@impersonation_session = Current.true_user.impersonator_support_sessions.find_by(id: params[:impersonation_session_id])++ # Structural guard, not just the self-healing one in+ # Authentication#end_impersonation_if_target_inactive! — that check only+ # runs on the *next* request, so without this, an admin could briefly+ # join an impersonation targeting an already-deactivated user.+ raise_unauthorized! if @impersonation_session && !@impersonation_session.impersonated.active?+Current.session.update!(active_impersonator_session: @impersonation_session)redirect_to root_path, notice: t(".success")enddiff --git a/app/controllers/mfa_controller.rb b/app/controllers/mfa_controller.rbindex 16f348de02..6c6cdadd9a 100644--- a/app/controllers/mfa_controller.rb+++ b/app/controllers/mfa_controller.rb@@ -30,12 +30,18 @@ class MfaController < ApplicationControllerdef verify_code@user = User.find_by(id: session[:mfa_user_id])- if @user&.verify_otp?(params[:code])- unless complete_mfa_sign_in(@user)- redirect_to new_session_path- return+ # Check before verify_otp? — a backup code is single-use and gets consumed+ # by verification, so a deactivated user shouldn't be able to burn one on+ # a login attempt that was always going to be rejected.+ if @user && [email protected]?+ session.delete(:mfa_user_id)+ redirect_to new_session_path, alert: t("sessions.create.account_deactivated")+ elsif @user&.verify_otp?(params[:code])+ if complete_mfa_sign_in(@user)+ redirect_to root_path+ else+ redirect_to new_session_path, alert: t("sessions.create.account_deactivated")end- redirect_to root_pathelseflash.now[:alert] = t(".invalid_code")render :verify, status: :unprocessable_entity@@ -66,6 +72,14 @@ class MfaController < ApplicationControllerreturn render json: { error: t(".invalid_credential") }, status: :unprocessable_entityend+ # Check before verifying/consuming the credential (sign_count gets+ # bumped below) — a deactivated user shouldn't be able to spend a+ # WebAuthn assertion on a login that was always going to be rejected.+ unless @user.active?+ session.delete(:mfa_user_id)+ return render json: { error: t("sessions.create.account_deactivated") }, status: :unauthorized+ end+credential = WebAuthn::Credential.from_get(webauthn_credential_payload,relying_party: webauthn_relying_partydiff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rbindex 076dc1096f..1366e7aaa4 100644--- a/app/controllers/sessions_controller.rb+++ b/app/controllers/sessions_controller.rb@@ -65,6 +65,16 @@ class SessionsController < ApplicationControllerendif user+ # Check before starting the MFA challenge, not just after — otherwise a+ # deactivated user's correct password still sets session[:mfa_user_id],+ # and completing MFA later (e.g. after being reactivated) would finish+ # a login whose first factor was accepted while inactive.+ unless user.active?+ flash.now[:alert] = t(".account_deactivated")+ render :new, status: :unprocessable_entity+ return+ end+if user.otp_required?log_super_admin_override_login(user)session[:mfa_user_id] = user.id@@ -72,12 +82,13 @@ class SessionsController < ApplicationControllerelselog_super_admin_override_login(user)@session = create_session_for(user)- unless @session- redirect_to new_session_path, alert: t("sessions.openid_connect.failed")- return++ if @session+ flash[:notice] = t("invitations.accept_choice.joined_household") if accept_pending_invitation_for(user)+ redirect_to root_path+ else+ redirect_to new_session_path, alert: t("sessions.create.account_deactivated")end- flash[:notice] = t("invitations.accept_choice.joined_household") if accept_pending_invitation_for(user)- redirect_to root_pathendelseflash.now[:alert] = t(".invalid_credentials")@@ -215,6 +226,14 @@ 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@@ -249,6 +268,25 @@ class SessionsController < ApplicationControllerif oidc_identity# Existing OIDC identity found - authenticate the useruser = oidc_identity.user++ # Check before recording authentication/audit success — a deactivated+ # user's credentials being valid shouldn't show up in the audit trail+ # as a successful login when access is actually being denied.+ unless user.active?+ Rails.logger.warn("[AUTH] Rejected OIDC login for deactivated user_id=#{user.id}")++ if session[:mobile_sso].present?+ session.delete(:mobile_sso)+ mobile_sso_redirect(error: "account_deactivated", message: t("sessions.create.account_deactivated"))+ elsif session[:desktop_sso].present?+ session.delete(:desktop_sso)+ redirect_to "sure://sso/callback?error=account_deactivated", allow_other_host: true+ else+ redirect_to new_session_path, alert: t("sessions.create.account_deactivated")+ end+ return+ end+oidc_identity.record_authentication!oidc_identity.sync_user_attributes!(auth)@@ -379,6 +417,17 @@ class SessionsController < ApplicationControllerenddef handle_mobile_sso_callback(user)+ # 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?+ 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"))+ return+ end+device_info = session.delete(:mobile_sso)unless device_info.present?@@ -386,8 +435,21 @@ class SessionsController < ApplicationControllerreturnend- device = MobileDevice.upsert_device!(user, device_info.symbolize_keys)- token_response = device.issue_token!+ begin+ device = MobileDevice.upsert_device!(user, device_info.symbolize_keys)+ rescue ActiveRecord::RecordInvalid => e+ Rails.logger.warn("[Mobile SSO] Device save failed: #{e.record.errors.full_messages.join(', ')}")+ mobile_sso_redirect(error: "device_error", message: "Unable to register device")+ return+ end++ begin+ token_response = device.issue_token!+ rescue ActiveRecord::RecordInvalid+ Rails.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+ end# Store tokens behind a one-time authorization code instead of passing in URLauthorization_code = SecureRandom.urlsafe_base64(32)@@ -405,9 +467,6 @@ class SessionsController < ApplicationController)mobile_sso_redirect(code: authorization_code)- rescue ActiveRecord::RecordInvalid => e- Rails.logger.warn("[Mobile SSO] Device save failed: #{e.record.errors.full_messages.join(', ')}")- mobile_sso_redirect(error: "device_error", message: "Unable to register device")enddef handle_desktop_sso_callback(user)diff --git a/app/models/mobile_device.rb b/app/models/mobile_device.rbindex ad6fa0625f..e78a3444dd 100644--- a/app/models/mobile_device.rb+++ b/app/models/mobile_device.rb@@ -66,6 +66,15 @@ class MobileDevice < ApplicationRecord# Issues a fresh Doorkeeper access token for this device, revoking any# previous tokens. Returns a hash with token details ready for an API# 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.def issue_token!user.with_lock dounless user.active?diff --git a/app/models/user.rb b/app/models/user.rbindex 67549ff6db..b7f7331413 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -245,6 +245,7 @@ class User < ApplicationRecordbefore_destroy :ensure_not_last_super_admin_on_destroyafter_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) }def deactivatereturn true unless active?@@ -386,6 +387,29 @@ class User < ApplicationRecordprovider.public_send(item_association.name) if item_associationend+ # Revokes mobile/third-party API access alongside the web-session+ # invalidation above. Without this, a deactivated user's existing+ # Doorkeeper tokens and API keys stay valid on the wire — currently+ # harmless only because Api::V1::BaseController/McpController re-check+ # active? on every request, but that's a second, independent safeguard,+ # not a substitute for actually revoking the credentials. Also revokes+ # unexchanged OAuth authorization grants — /oauth/token doesn't go+ # through the cookie authenticator, so a still-valid grant issued right+ # before deactivation could otherwise be exchanged for a fresh token+ # afterward.+ def revoke_all_access_tokens+ tokens_revoked = Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil).update_all(revoked_at: Time.current)+ grants_revoked = Doorkeeper::AccessGrant.where(resource_owner_id: id, revoked_at: nil).update_all(revoked_at: Time.current)+ keys_revoked = api_keys.active.visible.update_all(revoked_at: Time.current)++ if tokens_revoked > 0 || grants_revoked > 0 || keys_revoked > 0+ Rails.logger.warn(+ "[AUTH] Revoked #{tokens_revoked} access token(s), #{grants_revoked} authorization grant(s), " \+ "and #{keys_revoked} API key(s) for deactivated user_id=#{id}"+ )+ end+ end+def purgeif last_user_in_family?family.destroydiff --git a/config/initializers/doorkeeper.rb b/config/initializers/doorkeeper.rbindex ee13a9a640..2b53e4c74d 100644--- a/config/initializers/doorkeeper.rb+++ b/config/initializers/doorkeeper.rb@@ -8,13 +8,24 @@ Doorkeeper.configure do# This block will be called to check whether the resource owner is authenticated or not.resource_owner_authenticator do# Manually replicate the app's session-based authentication logic, since- # Doorkeeper controllers don't include our Authentication concern.+ # Doorkeeper controllers don't include our Authentication concern. This+ # must reject (and destroy) a session whose user has been deactivated,+ # the same way Authentication#find_session_by_cookie does — otherwise a+ # stale session (e.g. `active` flipped via update_column, which skips+ # callbacks) could still be used to issue a fresh OAuth authorization+ # grant for a deactivated user.if (session_id = cookies.signed[:session_token]).present?if (session_record = Session.find_by(id: session_id))- # Set Current.session so downstream code expecting it behaves normally.- Current.session = session_record- # Return the authenticated user object as the resource owner.- session_record.user+ if session_record.user&.active?+ # Set Current.session so downstream code expecting it behaves normally.+ Current.session = session_record+ # Return the authenticated user object as the resource owner.+ session_record.user+ else+ Rails.logger.warn("[AUTH] Rejected OAuth authorization for deactivated user_id=#{session_record.user_id}")+ session_record.destroy+ redirect_to new_session_url+ endelseredirect_to new_session_urlend@@ -28,11 +39,18 @@ Doorkeeper.configure do# adding oauth authorized applications. In other case it will return 403 Forbidden response# every time somebody will try to access the admin web interface.#+ # Same active?-check-and-destroy treatment as resource_owner_authenticator above.admin_authenticator doif (session_id = cookies.signed[:session_token]).present?if (session_record = Session.find_by(id: session_id))- Current.session = session_record- head :forbidden unless session_record.user&.super_admin?+ if session_record.user&.active?+ Current.session = session_record+ head :forbidden unless session_record.user.super_admin?+ else+ Rails.logger.warn("[AUTH] Rejected Doorkeeper admin access for deactivated user_id=#{session_record.user_id}")+ session_record.destroy+ redirect_to new_session_url+ endelseredirect_to new_session_urlenddiff --git a/config/locales/views/sessions/de.yml b/config/locales/views/sessions/de.ymlindex a517c60bb4..62f4c9b9aa 100644--- a/config/locales/views/sessions/de.yml+++ b/config/locales/views/sessions/de.yml@@ -4,6 +4,7 @@ de:create:invalid_credentials: Ungültige E-Mail-Adresse oder falsches Passwort.local_login_disabled: Anmeldung mit Passwort ist deaktiviert. Bitte nutze Single Sign-On.+ account_deactivated: Dieses Konto wurde deaktiviert. Bitte wende dich an einen Administrator.destroy:logout_successful: Du hast dich erfolgreich abgemeldet.post_logout:diff --git a/config/locales/views/sessions/en.yml b/config/locales/views/sessions/en.ymlindex 5ea0890182..327d08ebba 100644--- a/config/locales/views/sessions/en.yml+++ b/config/locales/views/sessions/en.yml@@ -4,6 +4,7 @@ en:create:invalid_credentials: Invalid email or password.local_login_disabled: Local password login is disabled. Please use single sign-on.+ account_deactivated: This account has been deactivated. Please contact an administrator.destroy:logout_successful: You have signed out successfully.post_logout:diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex d10b4862a6..e536d00e38 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -3627,7 +3627,7 @@ paths:ai_enabled:type: boolean'401':- description: invalid credentials or MFA required+ description: invalid credentials, MFA required, or account deactivatedcontent:application/json:schema:@@ -3760,7 +3760,7 @@ paths:created_at:type: integer'401':- description: invalid refresh token+ description: invalid or revoked refresh token, or account deactivatedcontent:application/json:schema:@@ -3844,7 +3844,7 @@ paths:schema:"$ref": "#/components/schemas/ErrorResponse"'401':- description: invalid credentials or expired linking code+ description: invalid credentials, expired linking code, or account deactivatedcontent:application/json:schema:diff --git a/spec/requests/api/v1/auth_spec.rb b/spec/requests/api/v1/auth_spec.rbindex 4a98dabba7..6905b674d7 100644--- a/spec/requests/api/v1/auth_spec.rb+++ b/spec/requests/api/v1/auth_spec.rb@@ -123,7 +123,7 @@ RSpec.describe 'API V1 Auth', type: :request dorun_test!end- response '401', 'invalid credentials or MFA required' do+ response '401', 'invalid credentials, MFA required, or account deactivated' doschema '$ref' => '#/components/schemas/ErrorResponse'run_test!end@@ -206,7 +206,7 @@ RSpec.describe 'API V1 Auth', type: :request dorun_test!end- response '401', 'invalid refresh token' do+ response '401', 'invalid or revoked refresh token, or account deactivated' doschema '$ref' => '#/components/schemas/ErrorResponse'run_test!end@@ -262,7 +262,7 @@ RSpec.describe 'API V1 Auth', type: :request dorun_test!end- response '401', 'invalid credentials or expired linking code' do+ response '401', 'invalid credentials, expired linking code, or account deactivated' doschema oneOf: [{ '$ref' => '#/components/schemas/ErrorResponse' },{ '$ref' => '#/components/schemas/MfaRequiredResponse' }diff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rbindex 6b6858792c..e4dd9dfd05 100644--- a/test/controllers/api/v1/auth_controller_test.rb+++ b/test/controllers/api/v1/auth_controller_test.rb@@ -345,6 +345,72 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert existing_token.revoked?end+ test "should not login a deactivated user even with correct password" do+ user = users(:family_admin)+ user.update_column(:active, false)++ assert_no_difference([ "MobileDevice.count", "Doorkeeper::AccessToken.count" ]) do+ post "/api/v1/auth/login", params: {+ email: user.email,+ password: user_password_test,+ device: @device_info+ }+ end++ assert_response :unauthorized+ response_data = JSON.parse(response.body)+ assert_equal "This account has been deactivated. Please contact an administrator.", response_data["error"]+ end++ test "should not login a user deactivated between the initial check and token issuance" do+ user = users(:family_admin)++ # Simulate deactivation landing after the early active? check but before+ # the token is actually minted — device validation runs in that window+ # in the real flow, so hook the deactivation there.+ Api::V1::AuthController.any_instance.stubs(:valid_device_info?).with do+ user.update_column(:active, false)+ true+ end.returns(true)++ assert_no_difference([ "MobileDevice.count", "Doorkeeper::AccessToken.count" ]) do+ post "/api/v1/auth/login", params: {+ email: user.email,+ password: user_password_test,+ device: @device_info+ }+ end++ assert_response :unauthorized+ response_data = JSON.parse(response.body)+ assert_equal "This account has been deactivated. Please contact an administrator.", response_data["error"]+ end++ test "should not login a user deactivated between device upsert and token issuance" do+ user = users(:family_admin)+ # Pre-create the real device so the stub below can return it as-is —+ # this isolates the test to the gap between upsert_device! and+ # issue_token!, not the earlier device-creation step.+ device = MobileDevice.upsert_device!(user, @device_info)++ MobileDevice.stubs(:upsert_device!).with do |*_args|+ user.update_column(:active, false)+ 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+ response_data = JSON.parse(response.body)+ assert_equal "This account has been deactivated. Please contact an administrator.", response_data["error"]+ end+test "should not login with invalid password" douser = users(:family_admin)@@ -450,22 +516,10 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert initial_token.revoked?end- test "should not refresh with invalid refresh token" do- assert_no_difference("Doorkeeper::AccessToken.count") do- post "/api/v1/auth/refresh", params: {- refresh_token: "invalid_token",- device: @device_info- }- end-- assert_response :unauthorized- response_data = JSON.parse(response.body)- assert_equal "Invalid refresh token", response_data["error"]- end-- test "should not refresh a token after its user is deactivated" do+ test "should not refresh for a deactivated user" douser = users(:family_admin)device = user.mobile_devices.create!(@device_info)+initial_token = Doorkeeper::AccessToken.create!(application: @shared_app,resource_owner_id: user.id,@@ -474,6 +528,7 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestscopes: "read_write",use_refresh_token: true)+user.update_column(:active, false)assert_no_difference("Doorkeeper::AccessToken.count") do@@ -484,7 +539,22 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestendassert_response :unauthorized- assert_equal "Invalid refresh token", JSON.parse(response.body)["error"]+ response_data = JSON.parse(response.body)+ assert_equal "Invalid refresh token", response_data["error"]+ assert_not initial_token.reload.revoked?, "the still-valid old token should be left alone, not silently revoked"+ end++ test "should not refresh with invalid refresh token" do+ assert_no_difference("Doorkeeper::AccessToken.count") do+ post "/api/v1/auth/refresh", params: {+ refresh_token: "invalid_token",+ device: @device_info+ }+ end++ assert_response :unauthorized+ response_data = JSON.parse(response.body)+ assert_equal "Invalid refresh token", response_data["error"]endtest "should not refresh without refresh token" do@@ -573,14 +643,15 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert_nil Rails.cache.read("mobile_sso_link:#{linking_code}")end- test "should reject SSO link with invalid password" do+ test "should reject SSO link for a deactivated user even with correct password" douser = users(:family_admin)+ user.update_column(:active, false)linking_code = SecureRandom.urlsafe_base64(32)Rails.cache.write("mobile_sso_link:#{linking_code}", {provider: "google_oauth2",- uid: "google-uid-123",- email: "[email protected]",+ uid: "google-uid-deactivated",+ email: "[email protected]",device_info: @device_info.stringify_keys,allow_account_creation: true}, expires_in: 10.minutes)@@ -589,31 +660,39 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestpost "/api/v1/auth/sso_link", params: {linking_code: linking_code,email: user.email,- password: "wrong_password"+ password: user_password_test}endassert_response :unauthorizedresponse_data = JSON.parse(response.body)- assert_equal "Invalid email or password", response_data["error"]+ assert_equal "This account has been deactivated. Please contact an administrator.", response_data["error"]- # Linking code should NOT be consumed on failed password- assert Rails.cache.read("mobile_sso_link:#{linking_code}").present?, "Expected linking code to survive a failed attempt"+ # Linking code should NOT be consumed on rejection+ assert Rails.cache.read("mobile_sso_link:#{linking_code}").present?, "Expected linking code to survive a rejected link attempt"end- test "should reject SSO link for an inactive user" do+ test "should reject SSO link for a user deactivated between the initial check and token issuance" douser = users(:family_admin)- user.update_column(:active, false)+linking_code = SecureRandom.urlsafe_base64(32)Rails.cache.write("mobile_sso_link:#{linking_code}", {provider: "google_oauth2",- uid: "google-uid-inactive",- email: "[email protected]",+ uid: "google-uid-race",+ email: "[email protected]",device_info: @device_info.stringify_keys,allow_account_creation: true}, expires_in: 10.minutes)- assert_no_difference "OidcIdentity.count" do+ # Simulate deactivation landing after the initial active? check but+ # before issue_mobile_tokens 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)+ true+ end++ assert_difference("OidcIdentity.count", 1) dopost "/api/v1/auth/sso_link", params: {linking_code: linking_code,email: user.email,@@ -622,8 +701,36 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestendassert_response :unauthorized- assert_equal "Invalid email or password", JSON.parse(response.body)["error"]- assert Rails.cache.read("mobile_sso_link:#{linking_code}").present?+ response_data = JSON.parse(response.body)+ assert_equal "This account has been deactivated. Please contact an administrator.", response_data["error"]+ end++ test "should reject SSO link with invalid password" do+ user = users(:family_admin)++ linking_code = SecureRandom.urlsafe_base64(32)+ Rails.cache.write("mobile_sso_link:#{linking_code}", {+ provider: "google_oauth2",+ uid: "google-uid-123",+ email: "[email protected]",+ device_info: @device_info.stringify_keys,+ allow_account_creation: true+ }, expires_in: 10.minutes)++ assert_no_difference("OidcIdentity.count") do+ post "/api/v1/auth/sso_link", params: {+ linking_code: linking_code,+ email: user.email,+ password: "wrong_password"+ }+ end++ assert_response :unauthorized+ response_data = JSON.parse(response.body)+ assert_equal "Invalid email or password", response_data["error"]++ # Linking code should NOT be consumed on failed password+ assert Rails.cache.read("mobile_sso_link:#{linking_code}").present?, "Expected linking code to survive a failed attempt"endtest "should reject SSO link when user has MFA enabled" dodiff --git a/test/controllers/impersonation_sessions_controller_test.rb b/test/controllers/impersonation_sessions_controller_test.rbindex 7dce7f5acd..2f73ce58e0 100644--- a/test/controllers/impersonation_sessions_controller_test.rb+++ b/test/controllers/impersonation_sessions_controller_test.rb@@ -24,6 +24,20 @@ class ImpersonationSessionsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to root_pathend+ test "cannot join an impersonation session targeting an already-deactivated user" do+ sign_in super_admin = users(:sure_support_staff)+ impersonated = users(:family_member)+ impersonated.update_column(:active, false)++ impersonator_session = impersonation_sessions(:in_progress)+ super_admin_session = super_admin.sessions.order(created_at: :desc).first++ post join_impersonation_sessions_path, params: { impersonation_session_id: impersonator_session.id }++ assert_response :not_found+ assert_nil super_admin_session.reload.active_impersonator_session+ end+test "super admin can join and leave an in progress impersonation session" dosign_in super_admin = users(:sure_support_staff)@@ -51,6 +65,26 @@ class ImpersonationSessionsControllerTest < ActionDispatch::IntegrationTestassert_equal "in_progress", impersonator_session.reload.statusend+ test "impersonation ends automatically when the impersonated user is deactivated mid-session" do+ sign_in super_admin = users(:sure_support_staff)+ impersonated = users(:family_member)++ impersonator_session = impersonation_sessions(:in_progress)+ super_admin_session = super_admin.sessions.order(created_at: :desc).first++ post join_impersonation_sessions_path, params: { impersonation_session_id: impersonator_session.id }+ assert_equal impersonator_session, super_admin_session.reload.active_impersonator_session++ impersonated.update_column(:active, false)++ # The admin's own session is still valid — they should land on root, not+ # get logged out — but the impersonation link itself must be gone.+ get root_path+ assert_response :success+ assert_nil super_admin_session.reload.active_impersonator_session+ assert Session.exists?(id: super_admin_session.id), "the admin's own session must survive"+ end+test "super admin can complete an impersonation session" dosign_in super_admin = users(:sure_support_staff)diff --git a/test/controllers/mfa_controller_test.rb b/test/controllers/mfa_controller_test.rbindex ea098eba98..cd58661c64 100644--- a/test/controllers/mfa_controller_test.rb+++ b/test/controllers/mfa_controller_test.rb@@ -185,7 +185,7 @@ class MfaControllerTest < ActionDispatch::IntegrationTestassert_operator stored_credential.sign_count, :>, 0end- test "verify_webauthn rejects authentication when session creation fails" do+ test "verify_webauthn rejects a user deactivated after MFA verification started" do@user.setup_mfa!@user.enable_mfa!client = register_webauthn_credential@@ -194,19 +194,31 @@ class MfaControllerTest < ActionDispatch::IntegrationTestpost sessions_path, params: { email: @user.email, password: user_password_test }post webauthn_options_mfa_path, as: :json+ assert_response :success+options = JSON.parse(response.body)assertion = client.get(challenge: options.fetch("challenge"),rp_id: "www.example.com",allow_credentials: [ stored_credential.credential_id ])- MfaController.any_instance.stubs(:create_session_for).returns(false)++ # Simulate deactivation happening after the challenge was issued but+ # before the assertion is submitted.+ @user.update_column(:active, false)post verify_webauthn_mfa_path, params: { credential: assertion }, as: :json- assert_response :unprocessable_entity- assert_equal I18n.t("mfa.verify_webauthn.invalid_credential"), JSON.parse(response.body).fetch("error")+ assert_response :unauthorized+ assert_equal "This account has been deactivated. Please contact an administrator.", JSON.parse(response.body)["error"]assert_not Session.exists?(user_id: @user.id)+ # The credential must not be consumed by a rejected login attempt.+ assert_nil stored_credential.reload.last_used_at+ assert_equal 0, stored_credential.sign_count+ # The pending MFA state must not survive the rejection either — otherwise+ # a later reactivation could let the user finish MFA without redoing the+ # first factor.+ assert_nil session[:mfa_user_id]endtest "verify_webauthn authenticates with configured relying party id" dodiff --git a/test/controllers/oidc_accounts_controller_test.rb b/test/controllers/oidc_accounts_controller_test.rbindex 4e255c936e..f3b9970edb 100644--- a/test/controllers/oidc_accounts_controller_test.rb+++ b/test/controllers/oidc_accounts_controller_test.rb@@ -77,7 +77,8 @@ class OidcAccountsControllerTest < ActionController::TestCaseassert_equal "Invalid email or password", flash[:alert]end- test "should reject linking an identity to an inactive user" do+ test "should reject linking for a deactivated user even with correct password" do+ @user.sessions.destroy_all # @user (family_admin) has a pre-existing fixture session@user.update_column(:active, false)session[:pending_oidc_auth] = pending_auth@@ -93,6 +94,34 @@ class OidcAccountsControllerTest < ActionController::TestCaseassert_equal "Invalid email or password", flash[:alert]end+ test "should reject linking for a user deactivated between the initial check and session creation" do+ session[:pending_oidc_auth] = pending_auth+ @user.sessions.destroy_all++ # Simulate deactivation landing after the initial active? check but+ # before create_session_for's reload catches it — SsoAuditLog.log_link!+ # runs in that window in the real flow, so hook the deactivation there.+ # create_link wraps identity creation, the audit log, and session creation+ # in one transaction, so a failed session creation rolls back the identity+ # link too — no dangling, unlinked OidcIdentity left behind.+ SsoAuditLog.stubs(:log_link!).with do |**kwargs|+ kwargs[:user].update_column(:active, false)+ true+ end++ assert_no_difference "OidcIdentity.count" do+ post :create_link,+ params: {+ email: @user.email,+ password: user_password_test+ }+ end++ assert_redirected_to new_session_path+ assert_equal "Could not authenticate via OpenID Connect.", flash[:alert]+ assert_not Session.exists?(user_id: @user.id)+ end+test "should redirect to MFA when user has MFA enabled" do@user.setup_mfa!@user.enable_mfa!diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rbindex 1625c0486c..461698da5c 100644--- a/test/controllers/sessions_controller_test.rb+++ b/test/controllers/sessions_controller_test.rb@@ -90,6 +90,36 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestassert_equal "Invalid email or password.", flash[:alert]end+ test "rejects fresh login for a deactivated user even with correct password" do+ # @user (family_admin) has a pre-existing fixture session (sessions.yml),+ # unrelated to this login attempt — clear it so the later assertion+ # actually proves no *new* session was created.+ @user.sessions.destroy_all++ # update_column bypasses the deactivation business rules (e.g. an admin+ # can't self-deactivate while other family members exist) since we're+ # testing the auth-layer guard, not User#deactivate itself.+ @user.update_column(:active, false)++ post sessions_url, params: { email: @user.email, password: user_password_test }++ assert_response :unprocessable_entity+ assert_equal "This account has been deactivated. Please contact an administrator.", flash[:alert]+ assert_not Session.exists?(user_id: @user.id)+ end++ test "an existing session stops working once the user is deactivated" do+ @user.sessions.destroy_all # Clean up the fixture session so the count below is exact+ sign_in @user+ assert Session.exists?(user_id: @user.id)++ @user.update_column(:active, false)++ get root_url+ assert_redirected_to new_session_path+ assert_not Session.exists?(user_id: @user.id), "stale session should be destroyed, not just skipped"+ end+test "redirects when local login is disabled" doAuthConfig.stubs(:local_login_enabled?).returns(false)AuthConfig.stubs(:local_admin_override_enabled?).returns(false)@@ -168,6 +198,20 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestassert_nil Session.find_by(id: session_record.id)end+ test "rejects a deactivated MFA-enabled user before starting the MFA challenge" do+ @user.setup_mfa!+ @user.enable_mfa!+ @user.sessions.destroy_all+ @user.update_column(:active, false)++ post sessions_path, params: { email: @user.email, password: user_password_test }++ assert_response :unprocessable_entity+ assert_equal "This account has been deactivated. Please contact an administrator.", flash[:alert]+ assert_nil session[:mfa_user_id]+ assert_not Session.exists?(user_id: @user.id)+ end+test "redirects to MFA verification when MFA enabled" do@user.setup_mfa!@user.enable_mfa!@@ -221,6 +265,24 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestassert_equal "removed_identity", SsoAuditLog.by_event("login_failed").order(:created_at).last.metadata.fetch("reason")end+ test "rejects OIDC login for a deactivated user" do+ oidc_identity = oidc_identities(:bob_google)+ @user.sessions.destroy_all # Clear the fixture session so the later assertion is exact+ @user.update_column(:active, false)++ setup_omniauth_mock(+ provider: oidc_identity.provider,+ uid: oidc_identity.uid,+ email: @user.email,+ name: "Bob Dylan"+ )++ get "/auth/openid_connect/callback"++ assert_redirected_to new_session_path+ assert_not Session.exists?(user_id: @user.id)+ end+test "redirects to MFA when user has MFA and uses OIDC" do@user.setup_mfa!@user.enable_mfa!@@ -555,6 +617,76 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestassert first_token.revoked_at.present?, "Expected first token to be revoked"end+ test "mobile SSO rejects a user deactivated 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-011",+ device_name: "Pixel 8",+ device_type: "android"+ }++ # Simulate deactivation landing after openid_connect's initial active?+ # check but before handle_mobile_sso_callback actually mints a token —+ # SsoAuditLog.log_login! runs in that window in the real flow, so hook+ # the deactivation there.+ SsoAuditLog.stubs(:log_login!).with do |**kwargs|+ kwargs[:user].update_column(:active, false)+ 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" do+ oidc_identity = oidc_identities(:bob_google)+ @user.update_column(:active, false)++ 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-010",+ device_name: "Pixel 8",+ device_type: "android"+ }++ 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 redirects MFA user with error" do@user.setup_mfa!@user.enable_mfa!@@ -831,6 +963,38 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestRails.cache = original_cacheend+ test "desktop SSO exchange rejects a deactivated MFA-enabled user before starting the MFA challenge" do+ original_cache = Rails.cache+ Rails.cache = ActiveSupport::Cache::MemoryStore.new++ @user.setup_mfa!+ @user.enable_mfa!+ @user.sessions.destroy_all # Clear the fixture session so the later assertion is exact++ verifier = SecureRandom.hex(32)+ challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)+ oidc_identity = oidc_identities(:bob_google)++ Rails.configuration.x.auth.stubs(:sso_providers).returns([+ { name: "openid_connect", strategy: "openid_connect", label: "Google" }+ ])+ setup_omniauth_mock(provider: oidc_identity.provider, uid: oidc_identity.uid, email: @user.email, name: "Bob Dylan")++ get "/auth/desktop/openid_connect", params: { code_challenge: challenge }+ get "/auth/openid_connect/callback"+ code = Rack::Utils.parse_query(URI.parse(@response.redirect_url).query)["code"]++ @user.update_column(:active, false)++ post desktop_sso_exchange_path, params: { code: code, code_verifier: verifier }++ assert_redirected_to new_session_path+ assert_nil session[:mfa_user_id]+ assert_not Session.exists?(user_id: @user.id)+ ensure+ Rails.cache = original_cache+ end+test "desktop_sso_start rejects a missing PKCE code_challenge" doRails.configuration.x.auth.stubs(:sso_providers).returns([{ name: "openid_connect", strategy: "openid_connect", label: "Google" }diff --git a/test/fixtures/users.yml b/test/fixtures/users.ymlindex dfdf4800f2..7b563c3012 100644--- a/test/fixtures/users.yml+++ b/test/fixtures/users.yml@@ -106,7 +106,7 @@ sso_only:last_name: Useremail: [email protected]password_digest: ~- role: admin+ role: memberonboarded_at: <%= 1.day.ago %>ai_enabled: truediff --git a/test/integration/oauth_basic_test.rb b/test/integration/oauth_basic_test.rbindex 7a4dd405e0..063bca37a3 100644--- a/test/integration/oauth_basic_test.rb+++ b/test/integration/oauth_basic_test.rb@@ -16,6 +16,26 @@ class OauthBasicTest < ActionDispatch::IntegrationTestassert_redirected_to new_session_pathend+ test "oauth authorization endpoint rejects a deactivated user's existing session" do+ oauth_app = Doorkeeper::Application.create!(+ name: "Test API Client",+ redirect_uri: "https://client.example.com/callback",+ scopes: "read"+ )+ user = users(:family_admin)+ sign_in user+ session_record = user.sessions.order(created_at: :desc).first++ # update_column bypasses callbacks, matching the exact scenario this+ # check exists to defend against (a stale session outliving deactivation).+ user.update_column(:active, false)++ get "/oauth/authorize?client_id=#{oauth_app.uid}&redirect_uri=#{CGI.escape(oauth_app.redirect_uri)}&response_type=code&scope=read"++ assert_redirected_to new_session_path+ assert_not Session.exists?(id: session_record.id), "stale session should be destroyed, not just skipped"+ end+test "oauth token endpoint exists and handles requests" dopost "/oauth/token", params: {grant_type: "authorization_code",diff --git a/test/integration/sidekiq_web_access_test.rb b/test/integration/sidekiq_web_access_test.rbindex 5f3ca95632..6c8ee7ff43 100644--- a/test/integration/sidekiq_web_access_test.rb+++ b/test/integration/sidekiq_web_access_test.rb@@ -31,6 +31,18 @@ class SidekiqWebAccessTest < ActionDispatch::IntegrationTestassert_response :successend+ test "deactivated super admin gets 404 and the stale session is destroyed" do+ super_admin = users(:sure_support_staff)+ sign_in super_admin+ session_record = super_admin.sessions.order(created_at: :desc).first+ super_admin.update_column(:active, false)++ get "/sidekiq"++ assert_response :not_found+ assert_not Session.exists?(id: session_record.id), "stale session should be destroyed, not just denied"+ end+test "garbage session cookie fails closed" docookies[:session_token] = "not-a-signed-cookie"diff --git a/test/models/user_test.rb b/test/models/user_test.rbindex 74d2f6a33d..d94997cc90 100644--- a/test/models/user_test.rb+++ b/test/models/user_test.rb@@ -1017,4 +1017,44 @@ class UserTest < ActiveSupport::TestCaseassert admin1.update(role: :member)end++ test "deactivating a user revokes their API keys, access tokens, and authorization grants" do+ user = users(:family_member)+ api_key = ApiKey.create!( # pipelock:ignore+ user: user,+ name: "Test Key",+ display_key: "test_revoke_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+ )+ # An unexchanged authorization code — the step before a token is minted,+ # which /oauth/token would otherwise still accept post-deactivation.+ grant = Doorkeeper::AccessGrant.create!(+ application: app,+ resource_owner_id: user.id,+ redirect_uri: app.redirect_uri,+ expires_in: 10.minutes,+ scopes: "read_write"+ )++ assert api_key.active?+ assert_nil token.revoked_at+ assert_nil grant.revoked_at++ user.deactivate++ assert api_key.reload.revoked?+ assert token.reload.revoked_at.present?+ assert grant.reload.revoked_at.present?+ endend