The personal finance app for everyone (by everyone)
Ruby
security: mobile API auth gates, MFA password re-auth, credential revocation on deactivate (#1942)
David Gil7e70a3955e2f
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rbindex 7a8df89a49..d58fc01a5d 100644--- a/app/controllers/api/v1/auth_controller.rb+++ b/app/controllers/api/v1/auth_controller.rb@@ -13,6 +13,15 @@ module Apirescue_from SsoIdentityBlock::BlockedIdentity, with: :render_removed_identitydef signup+ # RegistrationsController refuses to register a user while the instance+ # is closed. That gate is declared `if: :self_hosted?`, but+ # onboarding_state only ever reaches "closed" on a self-hosted+ # instance, so checking the state alone matches its effect.+ if Setting.onboarding_state == "closed"+ render json: { error: "Registration is currently closed" }, status: :forbidden+ return+ end+# Check if invite code is requiredif invite_code_required? && params[:invite_code].blank?render json: { error: "Invite code is required" }, status: :forbidden@@ -75,6 +84,11 @@ module Apidef loginuser = User.find_by(email: params[:email])+ unless local_login_permitted_for?(user)+ render json: { error: "Local login is disabled. Please use SSO." }, status: :forbidden+ return+ end+if user&.authenticate(params[:password])unless user.active?render json: { error: "This account has been deactivated. Please contact an administrator." }, status: :unauthorized@@ -392,6 +406,14 @@ module Apiprivate+ # Mirrors SessionsController#create: with SSO-only mode on, the only+ # local sign-in allowed is a super admin using the emergency override.+ def local_login_permitted_for?(user)+ return true if AuthConfig.local_login_enabled?++ AuthConfig.local_admin_override_enabled? && user&.super_admin?+ end+def user_signup_paramsparams.require(:user).permit(:email, :password, :first_name, :last_name)enddiff --git a/app/controllers/mfa_controller.rb b/app/controllers/mfa_controller.rbindex 8f266d90c6..551b35f716 100644--- a/app/controllers/mfa_controller.rb+++ b/app/controllers/mfa_controller.rb@@ -3,6 +3,7 @@ class MfaController < ApplicationControllerlayout :determine_layoutskip_authentication only: [ :verify, :verify_code, :webauthn_options, :verify_webauthn ]+ before_action :require_local_password, only: [ :new, :create, :disable ]def newredirect_to root_path if Current.user.otp_required?@@ -15,6 +16,14 @@ class MfaController < ApplicationController# through to disable_mfa! and tear a finished setup down.return redirect_to root_path if Current.user.otp_required?+ unless password_confirmed?+ # Deliberately not disable_mfa! here: a wrong password must not throw away+ # the otp_secret and backup codes the user is midway through setting up.+ # Only a code mismatch below does that.+ redirect_to new_mfa_path, alert: t(".invalid_password")+ return+ end+case Current.user.verify_otp(params[:code])when :accepted@backup_codes = Current.user.enable_mfa!@@ -124,12 +133,34 @@ class MfaController < ApplicationControllerenddef disable+ unless password_confirmed?+ redirect_to settings_security_path, alert: t(".invalid_password")+ return+ end+Current.user.disable_mfa!redirect_to settings_security_path, notice: t(".success")endprivate+ # Turning the second factor on or off changes how the account is protected,+ # so it is confirmed with the password rather than with possession of an+ # already-open session.+ def password_confirmed?+ Current.user.authenticate(params[:password]).present?+ end++ # A user who signs in through an identity provider has no local password to+ # confirm with, so these pages are closed to them rather than left as a+ # dead end. GET /mfa/new matters as much as the writes: it calls setup_mfa!+ # and would strand an otp_secret they could never finish wiring up.+ def require_local_password+ return if Current.user.has_local_password?++ redirect_to settings_security_path, alert: t("mfa.local_password_required")+ end+def determine_layoutif action_name.in?(%w[webauthn_options verify_webauthn])falsediff --git a/app/views/mfa/new.html.erb b/app/views/mfa/new.html.erbindex 65d56380f5..b55158da03 100644--- a/app/views/mfa/new.html.erb+++ b/app/views/mfa/new.html.erb@@ -46,7 +46,7 @@</div><%= styled_form_with url: mfa_path, method: :post, class: "mt-5", data: { turbo: false } do |f| %>- <div>+ <div class="space-y-4"><%= f.text_field :code,required: true,autofocus: true,@@ -56,6 +56,12 @@label: t(".code_label"),placeholder: t(".code_placeholder") %>+ <%= f.password_field :password,+ required: true,+ autocomplete: "current-password",+ label: t(".password_label"),+ placeholder: t(".password_placeholder") %>+<div class="flex justify-end mt-4"><%= f.submit t(".verify_button") %></div>diff --git a/app/views/settings/securities/show.html.erb b/app/views/settings/securities/show.html.erbindex dc97bb415d..1f7f4fbe37 100644--- a/app/views/settings/securities/show.html.erb+++ b/app/views/settings/securities/show.html.erb@@ -34,19 +34,25 @@</div><div class="mt-4 md:mt-0">- <% if Current.user.otp_required? %>- <%= render DS::Button.new(- text: t(".disable_mfa"),- variant: "secondary",- href: disable_mfa_path,- method: :delete,- confirm: CustomConfirm.new(- title: t(".disable_mfa_confirm"),- body: t(".disable_mfa_confirm"),- btn_text: t(".disable_mfa"),- destructive: true- )- ) %>+ <% if !Current.user.has_local_password? %>+ <%# No local password to confirm with, so there is no form to show. %>+ <p class="text-sm text-subdued"><%= t(".mfa_sso_only") %></p>+ <% elsif Current.user.otp_required? %>+ <%# Turning MFA off asks for the password, so the confirm dialog is+ replaced by a form that can carry it. %>+ <%= render DS::Disclosure.new(variant: :inline, open: flash[:alert].present?) do |disclosure| %>+ <% disclosure.with_summary_content do %>+ <span class="text-sm font-medium text-destructive"><%= t(".disable_mfa") %></span>+ <% end %>+ <%= styled_form_with url: disable_mfa_path, method: :delete, class: "mt-3 space-y-3", data: { turbo: false } do |f| %>+ <%= f.password_field :password,+ required: true,+ autocomplete: "current-password",+ label: t(".disable_mfa_password_label"),+ placeholder: t(".disable_mfa_password_placeholder") %>+ <%= f.submit t(".disable_mfa") %>+ <% end %>+ <% end %><% else %><%= render DS::Link.new(text: t(".enable_mfa"),diff --git a/config/locales/views/mfa/en.yml b/config/locales/views/mfa/en.ymlindex f435ad3b7f..e6679c0fd4 100644--- a/config/locales/views/mfa/en.yml+++ b/config/locales/views/mfa/en.yml@@ -1,6 +1,8 @@---en:mfa:+ local_password_required: Two-factor authentication needs a local password.+ Yours is managed through your identity provider.backup_codes:backup_codes_description: Each code can only be used once. Keep these codessafe and secure.@@ -13,13 +15,17 @@ en:create:code_already_used: That code was already used. Please enter the next code from your authenticator app.invalid_code: Invalid verification code. Please try again.+ invalid_password: Incorrect password. Please try again.disable:+ invalid_password: Incorrect password. Please try again.success: Two-factor authentication has been disablednew:code_label: Verification Codecode_placeholder: Enter 6-digit codedescription: Enhance your account security by setting up two-factor authenticationpage_title: Two-Factor Authentication Setup+ password_label: Confirm with your password+ password_placeholder: Enter your passwordscan_description: Use an authenticator app like Google Authenticator or 1Passwordto scan this QR codescan_title: 1. Scan QR Codediff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 839706033f..3c03b34121 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -312,6 +312,10 @@ en:enable_mfa: Enable 2FAdisable_mfa: Disable 2FAdisable_mfa_confirm: Are you sure you want to disable two-factor authentication?+ disable_mfa_password_label: Confirm with your password+ disable_mfa_password_placeholder: Enter your password+ mfa_sso_only: Two-factor authentication is managed through your identity+ provider.sso_title: Connected Accountssso_subtitle: Manage your single sign-on account connectionssso_disconnect: Disconnectdiff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 707360dd0f..85dfe09d8d 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -4698,7 +4698,8 @@ paths:schema:"$ref": "#/components/schemas/ErrorResponse"'403':- description: invite code required or invalid+ description: 'registration refused: the instance is closed to new registrations,+ or an invite code is required or invalid'content:application/json:schema:@@ -4806,6 +4807,13 @@ paths:application/json:schema:"$ref": "#/components/schemas/ErrorResponse"+ '403':+ description: 'local login is disabled: the instance is SSO-only, and this+ account is not a super admin using the emergency override'+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"requestBody:content:application/json:diff --git a/spec/requests/api/v1/auth_spec.rb b/spec/requests/api/v1/auth_spec.rbindex 6905b674d7..0dd88ec2ca 100644--- a/spec/requests/api/v1/auth_spec.rb+++ b/spec/requests/api/v1/auth_spec.rb@@ -67,7 +67,7 @@ RSpec.describe 'API V1 Auth', type: :request dorun_test!end- response '403', 'invite code required or invalid' do+ response '403', 'registration refused: the instance is closed to new registrations, or an invite code is required or invalid' doschema '$ref' => '#/components/schemas/ErrorResponse'run_test!end@@ -127,6 +127,11 @@ RSpec.describe 'API V1 Auth', type: :request doschema '$ref' => '#/components/schemas/ErrorResponse'run_test!end++ response '403', 'local login is disabled: the instance is SSO-only, and this account is not a super admin using the emergency override' do+ schema '$ref' => '#/components/schemas/ErrorResponse'+ run_test!+ endendenddiff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rbindex a58a336030..0b24efe4bd 100644--- a/test/controllers/api/v1/auth_controller_test.rb+++ b/test/controllers/api/v1/auth_controller_test.rb@@ -77,6 +77,21 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert_equal @device_info[:device_type], device.device_typeend+ # RegistrationsController refuses to register when the instance is closed.+ # The API creates the same account and did not check.+ test "signup is refused when the instance is closed to registration" do+ Setting.stubs(:onboarding_state).returns("closed")++ assert_no_difference("User.count") do+ post "/api/v1/auth/signup", params: {+ user: { email: "[email protected]", password: "Password1!", password_confirmation: "Password1!" },+ device: @device_info+ }+ end++ assert_response :forbidden+ end+test "should not signup without device info" doassert_no_difference("User.count") dopost "/api/v1/auth/signup", params: {@@ -273,6 +288,64 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert device.active?end+ # SessionsController refuses local sign-in when SSO-only mode is on, with a+ # single exception for a super-admin when the emergency override is enabled.+ # The API mints the same credentials and enforced neither.+ test "login is refused when local login is disabled" do+ AuthConfig.stubs(:local_login_enabled?).returns(false)+ AuthConfig.stubs(:local_admin_override_enabled?).returns(false)+ user = users(:family_admin)++ 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 :forbidden+ end++ test "login allows a super admin through the emergency override" do+ AuthConfig.stubs(:local_login_enabled?).returns(false)+ AuthConfig.stubs(:local_admin_override_enabled?).returns(true)+ user = users(:family_admin)+ user.update!(role: :super_admin)+ user.mobile_devices.destroy_all++ post "/api/v1/auth/login", params: {+ email: user.email, password: user_password_test, device: @device_info+ }++ assert_response :success+ end++ test "login refuses a non super admin even with the emergency override on" do+ AuthConfig.stubs(:local_login_enabled?).returns(false)+ AuthConfig.stubs(:local_admin_override_enabled?).returns(true)+ user = users(:family_member)++ 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 :forbidden+ end++ test "login refuses a deactivated user" do+ user = users(:family_admin)+ user.update_column(:active, false)++ 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+ end+test "should require MFA when enabled" douser = users(:family_admin)password = user_password_testdiff --git a/test/controllers/mfa_controller_test.rb b/test/controllers/mfa_controller_test.rbindex 7b9e9f9f34..37f919bc26 100644--- a/test/controllers/mfa_controller_test.rb+++ b/test/controllers/mfa_controller_test.rb@@ -37,7 +37,7 @@ class MfaControllerTest < ActionDispatch::IntegrationTest@user.setup_mfa!totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")- post mfa_path, params: { code: totp.now }+ post mfa_path, params: { code: totp.now, password: user_password_test }assert_response :successassert @user.reload.otp_required?@@ -56,7 +56,7 @@ class MfaControllerTest < ActionDispatch::IntegrationTest@user.setup_mfa!code = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances").now- post mfa_path, params: { code: code }+ post mfa_path, params: { code: code, password: user_password_test }assert_response :successassert @user.reload.otp_required?@@ -84,7 +84,7 @@ class MfaControllerTest < ActionDispatch::IntegrationTestassert @user.verify_otp?(code), "simulates the concurrent submit that claimed the step first"secret = @user.otp_secret- post mfa_path, params: { code: code }+ post mfa_path, params: { code: code, password: user_password_test }assert_redirected_to new_mfa_pathassert_equal I18n.t("mfa.create.code_already_used"), flash[:alert]@@ -96,7 +96,7 @@ class MfaControllerTest < ActionDispatch::IntegrationTesttest "does not enable MFA with invalid code" do@user.setup_mfa!- post mfa_path, params: { code: "invalid" }+ post mfa_path, params: { code: "invalid", password: user_password_test }assert_redirected_to new_mfa_pathassert_not @user.reload.otp_required?@@ -340,7 +340,7 @@ class MfaControllerTest < ActionDispatch::IntegrationTestpublic_key: "public-key")- delete disable_mfa_path+ delete disable_mfa_path, params: { password: user_password_test }assert_redirected_to settings_security_pathassert_not @user.reload.otp_required?@@ -349,7 +349,75 @@ class MfaControllerTest < ActionDispatch::IntegrationTestassert_empty @user.webauthn_credentialsend++ # Turning MFA on or off is a change to how the account is protected, so it+ # asks for the password. Without it, anyone who walks up to an unlocked+ # session can strip the second factor.+ test "enabling MFA requires the password" do+ @user.setup_mfa!+ totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")++ post mfa_path, params: { code: totp.now, password: "wrong-password" }++ assert_redirected_to new_mfa_path+ assert_not @user.reload.otp_required?+ end++ test "a wrong password while enabling does not discard the setup in progress" do+ @user.setup_mfa!+ secret = @user.otp_secret+ totp = ROTP::TOTP.new(secret, issuer: "Sure Finances")++ post mfa_path, params: { code: totp.now, password: "wrong-password" }++ assert_equal secret, @user.reload.otp_secret, "the in-progress secret must survive a wrong password"+ end++ test "disabling MFA requires the password" do+ @user.setup_mfa!+ @user.enable_mfa!++ delete disable_mfa_path, params: { password: "wrong-password" }++ assert_redirected_to settings_security_path+ assert @user.reload.otp_required?, "MFA must stay on"+ end++ # A user with no local password can never satisfy that prompt, so the MFA+ # pages are closed to them rather than left as a dead end. Visiting /mfa/new+ # would otherwise call setup_mfa! and strand an otp_secret they cannot+ # finish wiring up.+ test "a user without a local password cannot reach the MFA pages" do+ identity = oidc_identities(:sso_only_identity)+ sso_user = identity.user+ sign_in_through_sso(identity)++ get new_mfa_path+ assert_redirected_to settings_security_path+ assert_nil sso_user.reload.otp_secret, "no half-finished secret may be left behind"++ delete disable_mfa_path+ assert_redirected_to settings_security_path+ end+private+ # The SSO-only fixture has no password, so the normal sign_in helper, which+ # posts to /sessions, cannot be used. Sign in the way that user actually+ # would, through the identity provider.+ def sign_in_through_sso(identity)+ @user.sessions.destroy_all+ OmniAuth.config.mock_auth[:openid_connect] = OmniAuth::AuthHash.new(+ provider: identity.provider,+ uid: identity.uid,+ info: { email: identity.user.email, name: identity.user.display_name },+ credentials: {}+ )+ get "/auth/openid_connect/callback"+ assert Session.exists?(user_id: identity.user_id), "the SSO sign-in must establish a session"+ ensure+ OmniAuth.config.mock_auth[:openid_connect] = nil+ end+def register_webauthn_credential(origin: "http://www.example.com", rp_id: "www.example.com")client = WebAuthn::FakeClient.new(origin)diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rbindex 007535fe39..aed9cf0898 100644--- a/test/controllers/sessions_controller_test.rb+++ b/test/controllers/sessions_controller_test.rb@@ -1143,4 +1143,24 @@ class SessionsControllerTest < ActionDispatch::IntegrationTestget "/auth/desktop/openid_connect"assert_redirected_to new_session_pathend++ # create_session_for refuses a deactivated user, so the OIDC callback cannot+ # mint one either. Nothing covered that, and the identity record survives+ # deactivation, so it is worth pinning down.+ test "a deactivated user cannot sign in again through their SSO identity" do+ oidc_identity = oidc_identities(:bob_google)+ @user.sessions.destroy_all+ @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)+ endenddiff --git a/test/controllers/settings/securities_controller_test.rb b/test/controllers/settings/securities_controller_test.rbindex 26c12306d3..a1b126e53c 100644--- a/test/controllers/settings/securities_controller_test.rb+++ b/test/controllers/settings/securities_controller_test.rb@@ -31,4 +31,36 @@ class Settings::SecuritiesControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_not_includes response.body, I18n.t("settings.securities.show.encryption_warning.title")end++ test "the disable-MFA control asks for the password" do+ user = users(:family_admin)+ user.setup_mfa!+ user.enable_mfa!++ get settings_security_url++ assert_response :success+ assert_select "form[action=?][method=?]", disable_mfa_path, "post" do+ assert_select "input[type=password][name=?]", "password"+ end+ end++ test "a user without a local password is told MFA lives with their provider" do+ identity = oidc_identities(:sso_only_identity)+ OmniAuth.config.mock_auth[:openid_connect] = OmniAuth::AuthHash.new(+ provider: identity.provider,+ uid: identity.uid,+ info: { email: identity.user.email, name: identity.user.display_name },+ credentials: {}+ )+ get "/auth/openid_connect/callback"++ get settings_security_url++ assert_response :success+ assert_includes response.body, I18n.t("settings.securities.show.mfa_sso_only")+ assert_select "a[href=?]", new_mfa_path, count: 0+ ensure+ OmniAuth.config.mock_auth[:openid_connect] = nil+ endend