Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
10.0 KB
Raw Blame
class OidcAccountsController < ApplicationController
  skip_authentication only: [ :link, :create_link, :new_user, :create_user ]
  before_action :set_pending_auth, only: [ :link, :create_link, :new_user, :create_user ]
  before_action :reject_removed_identity, only: [ :link, :create_link, :new_user, :create_user ]
  rescue_from SsoIdentityBlock::BlockedIdentity, with: :reject_removed_identity_after_lock
  rescue_from OidcIdentity::ProviderNotConfigured, OidcIdentity::IssuerMismatch, OidcIdentity::LegacyIdentityRebindRejected,
    with: :reject_invalid_pending_auth
  layout "auth"

  # Offer linking only while the pending identity remains trusted.
  def link
    # Check if there's pending OIDC auth in session
    if @pending_auth.nil?
      redirect_to new_session_path, alert: t(".no_pending_oidc")
      return
    end

    @email = @pending_auth["email"]
    @legacy_oidc_relink = session[:pending_oidc_legacy_relink].present?
    @user_exists = @legacy_oidc_relink || (@email.present? && User.find_by_email_with_legacy_fallback(@email).present?)

    # Check for a pending invitation for this email
    @pending_invitation = Invitation.pending.find_by(email: @email) if @email.present?

    # Determine whether we should offer JIT account creation for this
    # pending auth, based on JIT mode and allowed domains.
    @allow_account_creation = @pending_invitation.present? || (!AuthConfig.jit_link_only? && AuthConfig.allowed_oidc_domain?(@email))
  end

  # Link to a password-verified account while enforcing current issuer continuity.
  def create_link
    if @pending_auth.nil?
      redirect_to new_session_path, alert: t(".no_pending_oidc")
      return
    end

    # Verify user's password to confirm identity
    user = User.authenticate_by_email(email: params[:email], password: params[:password])

    if user&.active?
      linked = user.transaction do
        auth = build_auth_hash(@pending_auth)
        if session[:pending_oidc_legacy_relink]
          OidcIdentity.rebind_legacy_issuer_from_omniauth!(auth, user)
        else
          OidcIdentity.create_from_omniauth(auth, user)
        end

        SsoAuditLog.log_link!(
          user: user,
          provider: @pending_auth["provider"],
          request: request
        )

        unless user.otp_required?
          @session = create_session_for(user, password_fingerprint: user.password_fingerprint)
          raise ActiveRecord::Rollback unless @session
        end

        true
      end

      unless linked
        redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
        return
      end

      # Clear pending auth from session
      session.delete(:pending_oidc_auth)
      session.delete(:pending_oidc_legacy_relink)

      if user.otp_required?
        begin_mfa_handoff(user, password_fingerprint: user.password_fingerprint)
        redirect_to verify_mfa_path
      else
        redirect_to root_path, notice: t("sessions.openid_connect.account_linked", provider: @pending_auth["provider"])
      end
    else
      @email = params[:email]
      @legacy_oidc_relink = session[:pending_oidc_legacy_relink].present?
      @user_exists = @legacy_oidc_relink || (@email.present? && User.find_by_email_with_legacy_fallback(@email).present?)
      flash.now[:alert] = "Invalid email or password"
      render :link, status: :unprocessable_entity
    end
  end

  # Offer account creation only for a currently trusted pending identity.
  def new_user
    # Check if there's pending OIDC auth in session
    if @pending_auth.nil?
      redirect_to new_session_path, alert: t(".no_pending_oidc")
      return
    end

    if session[:pending_oidc_legacy_relink]
      redirect_to link_oidc_account_path
      return
    end

    # Pre-fill user details from OIDC provider
    @user = User.new(
      email: @pending_auth["email"],
      first_name: @pending_auth["first_name"],
      last_name: @pending_auth["last_name"]
    )
  end

  # Create the account and OIDC identity using revalidated provider settings.
  def create_user
    if @pending_auth.nil?
      redirect_to new_session_path, alert: t(".no_pending_oidc")
      return
    end

    if session[:pending_oidc_legacy_relink]
      redirect_to link_oidc_account_path
      return
    end

    email = @pending_auth["email"]

    # Check for a pending invitation for this email
    invitation = Invitation.pending.find_by(email: email)

    # Respect global JIT configuration: in link_only mode or when the email
    # domain is not allowed, block JIT account creation—unless there's a
    # pending invitation for this user.
    unless invitation.present? || (!AuthConfig.jit_link_only? && AuthConfig.allowed_oidc_domain?(email))
      redirect_to new_session_path, alert: t(".account_creation_disabled")
      return
    end

    # Create SSO-only user without local password.
    # Security: JIT users should NOT have password_digest set to prevent
    # chained authentication attacks where SSO users gain local login access
    # via password reset.
    # Allow user to edit first_name and last_name from the form, but email comes from OIDC
    user_params = params.fetch(:user, {}).permit(:first_name, :last_name)
    @user = User.new(
      email: email,
      first_name: user_params[:first_name].presence || @pending_auth["first_name"],
      last_name: user_params[:last_name].presence || @pending_auth["last_name"],
      skip_password_validation: true
    )

    if invitation.present?
      # Accept the pending invitation: join the existing family
      @user.family_id = invitation.family_id
      @user.role = invitation.role
    else
      # Create new family for this user
      @user.family = Family.new

      # New family creators must be able to administer their own family.
      # Lower provider defaults are promoted to admin by role_for_new_family_creator,
      # while intentional super_admin defaults remain supported.
      provider_config = AuthConfig.sso_providers&.find { |p| p[:name] == @pending_auth["provider"] }
      provider_default_role = provider_config&.dig(:settings, :default_role)
    end

    identity = nil
    account_created = false

    begin
      account_created = ActiveRecord::Base.transaction do
        unless invitation.present?
          User.lock_first_user_role!
          @user.role = User.role_for_new_family_creator(fallback_role: provider_default_role || :admin)
        end

        unless @user.save
          raise ActiveRecord::Rollback
        end

        # Mark invitation as accepted if one was used
        invitation&.update!(accepted_at: Time.current)

        # Joining an existing family via invitation must honor the family's
        # default sharing policy, matching token registration. Without this a
        # JIT SSO invitee lands in the family but sees none of its accounts.
        @user.family.auto_share_existing_accounts_with(@user) if invitation.present?

        # Create the OIDC (or other SSO) identity
        identity = OidcIdentity.create_from_omniauth(
          build_auth_hash(@pending_auth),
          @user
        )

        @session = create_session_for(@user)
        raise ActiveRecord::Rollback unless @session

        true
      end
    rescue ActiveRecord::RecordInvalid => e
      # Expected persistence failures (e.g. a duplicate identity) roll the whole
      # onboarding back and re-render the form. Unexpected errors propagate so
      # they surface instead of being hidden as a form validation message.
      @user.errors.add(:base, e.message)
    rescue ActiveRecord::RecordNotUnique
      # PostgreSQL's message names the index and echoes the conflicting values.
      @user.errors.add(:base, t(".duplicate_account"))
    end

    if account_created
      # Only log JIT account creation if identity was successfully created
      if identity&.persisted?
        SsoAuditLog.log_jit_account_created!(
          user: @user,
          provider: @pending_auth["provider"],
          request: request
        )
      end

      # Clear pending auth from session
      session.delete(:pending_oidc_auth)

      notice = invitation.present? ? t("invitations.accept_choice.joined_household") : t(".account_created")
      redirect_to root_path, notice: notice
    else
      render :new_user, status: :unprocessable_entity
    end
  end

  private

    # Reject an identity removed while the linking flow waited for its lock.
    def reject_removed_identity_after_lock
      session.delete(:pending_oidc_auth)
      session.delete(:pending_oidc_legacy_relink)
      redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
    end

    def set_pending_auth
      # Cache-backed sessions preserve symbol keys from the OAuth callback.
      @pending_auth = session[:pending_oidc_auth]&.with_indifferent_access
    end

    def reject_removed_identity
      pending_auth = @pending_auth
      return unless pending_auth.present?

      if SsoIdentityBlock.blocked?(provider: pending_auth["provider"], uid: pending_auth["uid"])
        session.delete(:pending_oidc_auth)
        session.delete(:pending_oidc_legacy_relink)
        redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
        return
      end

      config = OidcIdentity.provider_config_for(pending_auth["provider"])
      unless config
        session.delete(:pending_oidc_auth)
        session.delete(:pending_oidc_legacy_relink)
        redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
      end
    end

    # Reject deferred authentication if its provider or issuer is no longer trusted.
    def reject_invalid_pending_auth
      session.delete(:pending_oidc_auth)
      session.delete(:pending_oidc_legacy_relink)
      redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
    end

    # Convert pending auth hash to OmniAuth-like structure
    def build_auth_hash(pending_auth)
      OpenStruct.new(
        provider: pending_auth["provider"],
        uid: pending_auth["uid"],
        info: OpenStruct.new(pending_auth.slice("email", "name", "first_name", "last_name")),
        extra: OpenStruct.new(raw_info: OpenStruct.new(iss: pending_auth["issuer"]))
      )
    end
end