Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
21.9 KB
Raw Blame
require "test_helper"
require "webauthn/fake_client"

class MfaControllerTest < ActionDispatch::IntegrationTest
  setup do
    @user = users(:family_member)
    sign_in @user
  end

  def sign_out
    # Deleting sessions through the controller de-authenticates the request the
    # moment our own session dies, so every later delete in the loop is a
    # silent no-op and whichever sessions sort after it survive. The order is
    # unspecified, which made every suite that signs out this way flaky.
    # Teardown hygiene is not the behavior under test, so destroy directly.
    @user.sessions.destroy_all
  end

  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!

    get new_mfa_path
    assert_redirected_to root_path
  end

  test "sets up MFA when visiting new" do
    get new_mfa_path

    assert_response :success
    assert @user.reload.otp_secret.present?
    assert_not @user.otp_required?
    assert_select "svg" # QR code should be present
  end

  test "enables MFA with valid code" do
    @user.setup_mfa!
    totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")

    post mfa_path, params: { code: totp.now, password: user_password_test }

    assert_response :success
    assert @user.reload.otp_required?
    assert_equal 8, @user.otp_backup_codes.length
    assert @user.otp_backup_codes.all? { |code| code.start_with?("$2") }
    assert_select "div.grid-cols-2" # Check for backup codes grid
    rendered_codes = css_select("div.grid-cols-2 div").map { |node| node.text.strip }
    assert_equal 8, rendered_codes.length
    assert rendered_codes.all? { |code| code.match?(/\A[0-9a-f]{16}\z/) }
    assert_empty rendered_codes & @user.otp_backup_codes

    assert SecurityAuditLog.exists?(user: @user, event_type: "mfa_enabled")
  end

  test "does not enable MFA when the audit log write fails" do
    @user.setup_mfa!
    totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")
    SecurityAuditLog.stubs(:log_mfa_enabled!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))

    post mfa_path, params: { code: totp.now }

    assert_redirected_to new_mfa_path
    assert_not @user.reload.otp_required?
    assert_empty @user.otp_backup_codes
  end

  # A double-click or browser resubmit replays the correct enrollment code;
  # before the guard this fell into disable_mfa! and wiped the whole setup.
  test "resubmitting the enrollment code does not tear down the finished setup" do
    @user.setup_mfa!
    code = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances").now

    post mfa_path, params: { code: code, password: user_password_test }
    assert_response :success
    assert @user.reload.otp_required?

    @user.webauthn_credentials.create!(
      nickname: "Touch ID",
      credential_id: "touch-id-credential",
      public_key: "public-key"
    )

    post mfa_path, params: { code: code }

    assert_redirected_to root_path
    @user.reload
    assert @user.otp_required?, "MFA must stay enabled"
    assert_equal 8, @user.otp_backup_codes.length
    assert @user.webauthn_credentials.exists?, "WebAuthn credentials must survive"
  end

  # Same replay, but caught before the first submit finished enabling MFA
  # (the otp_required? guard cannot help yet): keep the pending secret so
  # the user can enter the next code instead of restarting setup.
  test "a replayed enrollment code keeps the pending secret" do
    @user.setup_mfa!
    code = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances").now
    assert @user.verify_otp?(code), "simulates the concurrent submit that claimed the step first"
    secret = @user.otp_secret

    post mfa_path, params: { code: code, password: user_password_test }

    assert_redirected_to new_mfa_path
    assert_equal I18n.t("mfa.create.code_already_used"), flash[:alert]
    @user.reload
    assert_equal secret, @user.otp_secret, "the pending secret must survive"
    assert_not @user.otp_required?
  end

  test "does not enable MFA with invalid code" do
    @user.setup_mfa!

    assert_no_difference "SecurityAuditLog.count" do
      post mfa_path, params: { code: "invalid", password: user_password_test }
    end

    assert_redirected_to new_mfa_path
    assert_not @user.reload.otp_required?
    assert_empty @user.otp_backup_codes
  end

  test "create refuses to touch an already-enabled MFA even with a wrong code" do
    @user.setup_mfa!
    @user.enable_mfa!
    assert @user.otp_required?

    assert_no_difference "SecurityAuditLog.count" do
      post mfa_path, params: { code: "invalid" }
    end

    assert_redirected_to root_path
    assert @user.reload.otp_required?
    assert @user.otp_secret.present?
  end

  test "verify shows MFA verification page" do
    @user.setup_mfa!
    @user.enable_mfa!
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }
    assert_redirected_to verify_mfa_path

    get verify_mfa_path
    assert_response :success
    assert_select "form[action=?]", verify_mfa_path
  end

  test "verify shows WebAuthn option when credentials are registered" do
    @user.setup_mfa!
    @user.enable_mfa!
    register_webauthn_credential
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }
    get verify_mfa_path

    assert_response :success
    assert_select "button", text: I18n.t("mfa.verify.webauthn_button")
    assert_select "[data-webauthn-authentication-error-fallback-value=?]", I18n.t("mfa.verify_webauthn.invalid_credential")
    assert_select "p[data-webauthn-authentication-target='error'][aria-live='assertive'][aria-atomic='true'][aria-hidden='true']"
  end

  test "verify_code authenticates with valid TOTP" do
    @user.setup_mfa!
    @user.enable_mfa!
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }
    assert_redirected_to verify_mfa_path
    assert_equal @user.id, session[:mfa_user_id]

    totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")

    post verify_mfa_path, params: { code: totp.now }

    assert_redirected_to root_path
    assert Session.exists?(user_id: @user.id)
  end

  test "verify_code cannot create a session after the user is deactivated" do
    @user.setup_mfa!
    @user.enable_mfa!
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }
    assert_redirected_to verify_mfa_path
    assert_equal @user.id, session[:mfa_user_id]

    totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")
    @user.update_column(:active, false)

    assert_no_difference -> { Session.where(user_id: @user.id).count } do
      post verify_mfa_path, params: { code: totp.now }
    end
    assert_redirected_to new_session_path
  end

  test "verify_code cannot create a session after the password changed" do
    @user.setup_mfa!
    @user.enable_mfa!
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }
    assert_redirected_to verify_mfa_path

    totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")
    User.find(@user.id).update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")

    assert_no_difference -> { Session.where(user_id: @user.id).count } do
      post verify_mfa_path, params: { code: totp.now }
    end
    assert_redirected_to new_session_path
  end

  test "verify_code authenticates with valid backup code" do
    @user.setup_mfa!
    backup_code = @user.enable_mfa!.first
    matching_digest = @user.otp_backup_codes.find { |digest| BCrypt::Password.new(digest).is_password?(backup_code) }
    assert_not_nil matching_digest
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }

    post verify_mfa_path, params: { code: backup_code }

    assert_redirected_to root_path
    assert Session.exists?(user_id: @user.id)
    assert_equal 7, @user.reload.otp_backup_codes.size
    assert_not_includes @user.otp_backup_codes, matching_digest
  end

  test "verify_code rejects invalid codes" do
    @user.setup_mfa!
    @user.enable_mfa!
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }
    post verify_mfa_path, params: { code: "invalid" }

    assert_response :unprocessable_entity
    assert_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" do
    post webauthn_options_mfa_path, as: :json

    assert_response :unprocessable_entity
  end

  test "verify_webauthn authenticates with a registered credential" do
    @user.setup_mfa!
    @user.enable_mfa!
    client = register_webauthn_credential
    stored_credential = @user.webauthn_credentials.first
    sign_out

    post 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 ]
    )

    post verify_webauthn_mfa_path, params: { credential: assertion }, as: :json

    assert_response :success
    assert_equal root_path, JSON.parse(response.body).fetch("redirect_url")
    assert Session.exists?(user_id: @user.id)
    assert stored_credential.reload.last_used_at.present?
    assert_operator stored_credential.sign_count, :>, 0
  end

  test "verify_webauthn rejects a user deactivated after MFA verification started" do
    @user.setup_mfa!
    @user.enable_mfa!
    client = register_webauthn_credential
    stored_credential = @user.webauthn_credentials.first
    sign_out

    post 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 ]
    )

    # 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 :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]
  end

  test "verify_webauthn authenticates with configured relying party id" do
    with_webauthn_config(rp_id: "example.test", allowed_origins: [ "https://app.example.test" ]) do
      @user.setup_mfa!
      @user.enable_mfa!
      client = register_webauthn_credential(origin: "https://app.example.test", rp_id: "example.test")
      stored_credential = @user.webauthn_credentials.first
      sign_out

      post 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)
      assert_equal "example.test", options.fetch("rpId")
      assertion = client.get(
        challenge: options.fetch("challenge"),
        rp_id: "example.test",
        allow_credentials: [ stored_credential.credential_id ]
      )

      post verify_webauthn_mfa_path, params: { credential: assertion }, as: :json

      assert_response :success
      assert_equal root_path, JSON.parse(response.body).fetch("redirect_url")
    end
  end

  test "verify_webauthn rejects invalid credentials" do
    @user.setup_mfa!
    @user.enable_mfa!
    client = register_webauthn_credential
    stored_credential = @user.webauthn_credentials.first
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }
    post webauthn_options_mfa_path, as: :json
    options = JSON.parse(response.body)
    assertion = client.get(
      challenge: options.fetch("challenge"),
      rp_id: "www.example.com",
      allow_credentials: [ stored_credential.credential_id ]
    )
    assertion["id"] = "invalid"

    post verify_webauthn_mfa_path, params: { credential: assertion }, as: :json

    assert_response :unprocessable_entity
    assert_not Session.exists?(user_id: @user.id)
  end

  test "verify_webauthn rejects malformed credential payloads" do
    @user.setup_mfa!
    @user.enable_mfa!
    register_webauthn_credential
    sign_out

    post sessions_path, params: { email: @user.email, password: user_password_test }
    post webauthn_options_mfa_path, as: :json
    assert_response :success

    post verify_webauthn_mfa_path, params: { credential: [] }, as: :json

    assert_response :unprocessable_entity
    assert_equal I18n.t("mfa.verify_webauthn.invalid_credential"), JSON.parse(response.body).fetch("error")
    assert_not Session.exists?(user_id: @user.id)
  end

  test "disable removes MFA" do
    @user.setup_mfa!
    @user.enable_mfa!
    @user.webauthn_credentials.create!(
      nickname: "YubiKey",
      credential_id: "disable-mfa-credential",
      public_key: "public-key"
    )

    delete disable_mfa_path, params: { password: user_password_test }

    assert_redirected_to settings_security_path
    assert_not @user.reload.otp_required?
    assert_nil @user.otp_secret
    assert_empty @user.otp_backup_codes
    assert_empty @user.webauthn_credentials

    assert SecurityAuditLog.exists?(user: @user, event_type: "mfa_disabled")
  end

  test "disable while impersonating attributes the audit entry to the impersonator, not the victim" do
    @user.setup_mfa!
    @user.enable_mfa!
    sign_out

    impersonator = users(:sure_support_staff)
    sign_in impersonator
    post join_impersonation_sessions_path, params: { impersonation_session_id: impersonation_sessions(:in_progress).id }
    assert_response :redirect

    delete disable_mfa_path, params: { password: user_password_test }

    log = SecurityAuditLog.find_by(user: @user, event_type: "mfa_disabled")
    assert_not_nil log
    assert_equal impersonator.id, log.metadata["actor_user_id"]
  end

  test "still disables MFA when the audit log write fails" do
    # Log-and-continue, not transactional: a failed audit write must not
    # block turning off a security control the user is actively trying to
    # disable (e.g. because they believe it's compromised).
    @user.setup_mfa!
    @user.enable_mfa!
    @user.webauthn_credentials.create!(
      nickname: "YubiKey",
      credential_id: "disable-mfa-audit-fail-credential",
      public_key: "public-key"
    )
    SecurityAuditLog.stubs(:log_mfa_disabled!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))

    delete disable_mfa_path, params: { password: user_password_test }

    assert_redirected_to settings_security_path
    assert_not @user.reload.otp_required?
    assert_nil @user.otp_secret
    assert_empty @user.webauthn_credentials
    assert_not SecurityAuditLog.exists?(user: @user, event_type: "mfa_disabled")
  end


  # 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 },
        extra: { raw_info: { iss: identity.issuer } },
        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)

      # A backup code confirms the registration so the current TOTP step stays
      # free for the sign-in steps these tests go on to exercise.
      code = @user.enable_mfa!.first
      post options_settings_webauthn_credentials_path, params: { webauthn_credential: { code: code } }, as: :json
      options = JSON.parse(response.body)
      credential = client.create(challenge: options.fetch("challenge"), rp_id: rp_id)
      post settings_webauthn_credentials_path, params: {
        webauthn_credential: { nickname: "MacBook Touch ID", code: code },
        credential: credential
      }, as: :json
      assert_response :success

      client
    end

    def with_webauthn_config(rp_id:, allowed_origins:)
      config = Rails.application.config.x.webauthn
      previous_rp_id = config.rp_id
      previous_allowed_origins = config.allowed_origins
      config.rp_id = rp_id
      config.allowed_origins = allowed_origins

      yield
    ensure
      config.rp_id = previous_rp_id
      config.allowed_origins = previous_allowed_origins
    end
end