The personal finance app for everyone (by everyone)
Ruby
Send a repeat MFA code submit to the app instead of an error (#5300)
Alessandro Pogliaghi58c2d4b5fb43
diff --git a/app/controllers/mfa_controller.rb b/app/controllers/mfa_controller.rbindex 44e617ca2d..70e9b9e1dc 100644--- a/app/controllers/mfa_controller.rb+++ b/app/controllers/mfa_controller.rb@@ -3,6 +3,12 @@ class MfaController < ApplicationControllerlayout :determine_layoutskip_authentication only: [ :verify, :verify_code, :webauthn_options, :verify_webauthn ]+ # Completing the sign-in rotates the Rails session, so a repeat submit of the+ # code form carries a token that no longer verifies. Without a pending+ # sign-in verify_code only redirects, which leaves the token nothing to+ # protect. One predicate on purpose: passed as separate `only:` and `if:`+ # options, each would skip the check on its own.+ skip_forgery_protection if: :code_submit_without_pending_sign_in?before_action :require_mfa_enrollment_allowed, only: [ :new, :create ]before_action :require_local_password, only: [ :new, :create, :disable ]@@ -57,13 +63,20 @@ class MfaController < ApplicationControllerdef verify_code@user = User.find_by(id: session[:mfa_user_id])+ # No sign-in is pending, so there is no code to check. A repeat submit of+ # the form lands here once the first one has completed the sign-in:+ # root_path then shows the app. Without a session (a stale code page) it+ # sends the browser to the sign-in page, or to registration on a+ # self-hosted instance with no users.+ return redirect_to root_path if @user.nil?+# 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]?+ if [email protected]?session.delete(:mfa_user_id)redirect_to new_session_path, alert: t("sessions.create.account_deactivated")- elsif @user&.verify_otp?(params[:code])+ elsif @user.verify_otp?(params[:code])if complete_mfa_sign_in(@user)redirect_to root_pathelse@@ -181,6 +194,10 @@ class MfaController < ApplicationControllerredirect_to settings_security_path, alert: t("mfa.local_password_required")end+ def code_submit_without_pending_sign_in?+ action_name == "verify_code" && session[:mfa_user_id].blank?+ end+def determine_layoutif action_name.in?(%w[webauthn_options verify_webauthn])falsediff --git a/app/javascript/controllers/loading_button_controller.js b/app/javascript/controllers/loading_button_controller.jsindex 7a1e03d8db..5a72119c52 100644--- a/app/javascript/controllers/loading_button_controller.js+++ b/app/javascript/controllers/loading_button_controller.js@@ -7,6 +7,7 @@ export default class extends Controller {showLoading() {// Don't prevent form submission, just show loading stateif (this.hasButtonTarget) {+ this.originalContent = this.buttonTarget.innerHTMLthis.buttonTarget.disabled = truethis.buttonTarget.setAttribute("aria-disabled", "true")this.buttonTarget.setAttribute("aria-busy", "true")@@ -18,4 +19,17 @@ export default class extends Controller {`}}-}\ No newline at end of file++ // The browser's back/forward cache hands a page back as it was left, so+ // after a full-page submit the button would return disabled and spinning.+ // Wire with pageshow@window->loading-button#restoreIfPersisted.+ restoreIfPersisted(event) {+ if (!event.persisted || !this.hasButtonTarget || this.originalContent === undefined) return++ this.buttonTarget.disabled = false+ this.buttonTarget.removeAttribute("aria-disabled")+ this.buttonTarget.removeAttribute("aria-busy")+ this.buttonTarget.innerHTML = this.originalContent+ this.originalContent = undefined+ }+}diff --git a/app/views/mfa/verify.html.erb b/app/views/mfa/verify.html.erbindex 8627d15e9d..e3444a0a7b 100644--- a/app/views/mfa/verify.html.erb+++ b/app/views/mfa/verify.html.erb@@ -26,7 +26,15 @@</div><% end %>-<%= styled_form_with url: verify_mfa_path, method: :post, class: "space-y-4 mt-4 md:mt-0", data: { turbo: false } do |form| %>+<%= styled_form_with url: verify_mfa_path,+ method: :post,+ class: "space-y-4 mt-4 md:mt-0",+ data: {+ turbo: false,+ controller: "loading-button",+ action: "submit->loading-button#showLoading pageshow@window->loading-button#restoreIfPersisted",+ loading_button_loading_text_value: t(".verifying")+ } do |form| %><%= form.text_field :code,required: true,autofocus: true,@@ -34,5 +42,5 @@type: "text",label: t(".page_title") %>- <%= form.submit t(".verify_button") %>+ <%= form.submit t(".verify_button"), data: { loading_button_target: "button" } %><% end %>diff --git a/config/locales/views/mfa/en.yml b/config/locales/views/mfa/en.ymlindex 65bf8c3e9f..d00e233999 100644--- a/config/locales/views/mfa/en.yml+++ b/config/locales/views/mfa/en.yml@@ -45,6 +45,7 @@ en:page_title: Verify Two-Factor Authenticationtitle: Two-Factor Authenticationverify_button: Verify+ verifying: Verifying...webauthn_button: Use passkey or security keywebauthn_unsupported: This browser does not support passkeys or security keys.verify_code:diff --git a/test/controllers/mfa_controller_test.rb b/test/controllers/mfa_controller_test.rbindex 1470851bd3..f782a8e839 100644--- a/test/controllers/mfa_controller_test.rb+++ b/test/controllers/mfa_controller_test.rb@@ -16,6 +16,14 @@ class MfaControllerTest < ActionDispatch::IntegrationTest@user.sessions.destroy_allend+ def with_forgery_protection+ original = ActionController::Base.allow_forgery_protection+ ActionController::Base.allow_forgery_protection = true+ yield+ ensure+ ActionController::Base.allow_forgery_protection = original+ end+test "redirects to root if MFA already enabled" do@user.setup_mfa!@user.enable_mfa!@@ -242,6 +250,89 @@ class MfaControllerTest < ActionDispatch::IntegrationTestassert_not Session.exists?(user_id: @user.id)end+ test "verify_code sends a repeat submit after sign-in to the app" do+ @user.setup_mfa!+ @user.enable_mfa!+ sign_out++ # Frozen so the code cannot expire between generating and submitting it.+ freeze_time do+ post sessions_path, params: { email: @user.email, password: user_password_test }+ code = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances").now++ # Forgery protection is on, as in production: the first submit rotates the+ # session, so the repeat submit arrives with a token that no longer verifies.+ with_forgery_protection do+ get verify_mfa_path+ token = css_select("form[action='#{verify_mfa_path}'] input[name='authenticity_token']").first["value"]++ post verify_mfa_path, params: { code: code, authenticity_token: token }+ assert_redirected_to root_path++ assert_no_difference -> { Session.where(user_id: @user.id).count } do+ post verify_mfa_path, params: { code: code, authenticity_token: token }+ end+ assert_redirected_to root_path+ assert_nil flash[:alert]+ end++ follow_redirect!+ assert_response :success+ end+ end++ test "verify_code still requires a valid token while a sign-in is pending" do+ @user.setup_mfa!+ backup_code = @user.enable_mfa!.first+ sign_out++ post sessions_path, params: { email: @user.email, password: user_password_test }++ with_forgery_protection do+ post verify_mfa_path, params: { code: backup_code, authenticity_token: "forged" }+ assert_response :unprocessable_entity+ end++ # Rejected before verification: no session, and the single-use code is unspent.+ assert_not Session.exists?(user_id: @user.id)+ assert_equal 8, @user.reload.otp_backup_codes.size+ end++ test "other MFA actions keep requiring a valid token without a pending sign-in" do+ @user.setup_mfa!+ @user.enable_mfa!++ with_forgery_protection do+ delete disable_mfa_path, params: { password: user_password_test, authenticity_token: "forged" }+ assert_response :unprocessable_entity+ end++ assert @user.reload.otp_required?+ end++ test "verify_code without a pending sign-in redirects instead of reporting an invalid code" do+ sign_out++ post verify_mfa_path, params: { code: "123456" }+ assert_redirected_to root_path++ follow_redirect!+ assert_redirected_to new_session_path+ end++ test "verify form disables its button on submit" do+ @user.setup_mfa!+ @user.enable_mfa!+ sign_out++ post sessions_path, params: { email: @user.email, password: user_password_test }+ get verify_mfa_path++ assert_select "form[action=?][data-controller='loading-button'][data-action~='submit->loading-button#showLoading']", verify_mfa_path do+ assert_select "button[type='submit'][data-loading-button-target='button']"+ end+ end+test "webauthn_options require a pending MFA session" dopost webauthn_options_mfa_path, as: :jsondiff --git a/test/system/mfa_verify_test.rb b/test/system/mfa_verify_test.rbnew file mode 100644index 0000000000..80115980ec--- /dev/null+++ b/test/system/mfa_verify_test.rb@@ -0,0 +1,84 @@+require "application_system_test_case"++class MfaVerifyTest < ApplicationSystemTestCase+ setup do+ @user = users(:family_member)+ @user.setup_mfa!+ @backup_code = @user.enable_mfa!.first++ visit new_session_path+ within %(form[action='#{sessions_path}']) do+ find("input[type='email']").set(@user.email)+ find("input[type='password']").set(user_password_test)+ find("[type='submit']").click+ end+ assert_selector code_form+ end++ test "the code form submits once, and its button comes back with the page" do+ wait_for_loading_button++ # Hold the page in place so the state after a submit can be read; the+ # controller's own submit action still runs.+ page.execute_script(<<~JS)+ window.submitCount = 0+ document.querySelector("#{code_form}").addEventListener("submit", (event) => {+ window.submitCount+++ event.preventDefault()+ })+ JS++ # Labels as the browser rendered them: its locale need not be the test's.+ label = find(submit_button).text+ loading_label = find(code_form)["data-loading-button-loading-text-value"]+ assert_not_equal label, loading_label++ field = find("#{code_form} input[name='code']")+ field.set("123456")+ field.send_keys(:enter)++ assert_selector "#{submit_button}[disabled][aria-busy='true']", exact_text: loading_label++ # A second Enter, and a click on the disabled button, submit nothing.+ field.send_keys(:enter)+ page.execute_script(%(document.querySelector("#{submit_button}").click()))+ assert_equal 1, page.evaluate_script("window.submitCount")++ # What the browser fires when it restores the page from its back/forward cache.+ page.execute_script(%(window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }))))++ assert_selector "#{submit_button}:not([disabled]):not([aria-busy])", exact_text: label+ end++ test "a valid code signs in" do+ # A backup code, so a slow run cannot outlive the code it typed.+ field = find("#{code_form} input[name='code']")+ field.set(@backup_code)+ field.send_keys(:enter)++ assert_selector "h1", text: @user.first_name+ end++ private++ def code_form+ "form[action='#{verify_mfa_path}']"+ end++ def submit_button+ "#{code_form} button[type='submit']"+ end++ # The form is in the page before Stimulus has connected its controller.+ def wait_for_loading_button+ page.document.synchronize do+ connected = page.evaluate_script(<<~JS)+ (() => {+ const form = document.querySelector("#{code_form}");+ return !!form && !!window.Stimulus.getControllerForElementAndIdentifier(form, "loading-button");+ })()+ JS+ raise Capybara::ExpectationNotMet, "loading-button is not connected" unless connected+ end+ end+end