Sha256: 2b00474a8c0e6c4a9da9ed2a7c9e791cfa13e18a126484e941020ca426b53696

Contents?: true

Size: 1.66 KB

Versions: 27

Compression:

Stored size: 1.66 KB

Contents

module Avo
  module Services
    class EncryptionService
      class << self
        def encrypt(...)
          new(...).encrypt
        end

        def decrypt(...)
          new(...).decrypt
        end
      end

      def initialize(message:, purpose:, **kwargs)
        @message = message
        @purpose = purpose
        @crypt = ActiveSupport::MessageEncryptor.new(encryption_key, **kwargs)
      end

      def encrypt
        @crypt.encrypt_and_sign(@message, purpose: @purpose)
      end

      def decrypt
        @crypt.decrypt_and_verify(@message, purpose: @purpose)
      end

      private

      def encryption_key
        secret_key_base[0..31]
      end

      def secret_key_base
        # Try to fetch the secret key base from ENV or the credentials file
        key = ENV["SECRET_KEY_BASE"] || Rails.application.credentials.secret_key_base

        # If key is blank and Rails version is less than 7.2.0
        # Try to fetch the secret key base from the secrets file
        # Rails 7.2.0 made secret_key_base from secrets obsolete
        if key.blank? && (Rails.gem_version < Gem::Version.new('7.2.0'))
          key = Rails.application.secrets.secret_key_base
        end

        return key if key.present?

        # Avoid breaking in production
        # All features relying on encryption will not work properly without a configured secret key base
        return SecureRandom.random_bytes(32) if Rails.env.production?

        raise "Unable to fetch secret key base. Please set it in your credentials or environment variables\n" \
          "For more information check https://docs.avohq.io/3.0/encryption-service.html#secret-key-base"
      end
    end
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
avo-3.6.4 lib/avo/services/encryption_service.rb
avo-3.6.3 lib/avo/services/encryption_service.rb
avo-3.6.2 lib/avo/services/encryption_service.rb
avo-3.6.1 lib/avo/services/encryption_service.rb
avo-3.6.0 lib/avo/services/encryption_service.rb
avo-3.5.8 lib/avo/services/encryption_service.rb
avo-3.5.7 lib/avo/services/encryption_service.rb
avo-3.5.6 lib/avo/services/encryption_service.rb
avo-3.5.6.beta1 lib/avo/services/encryption_service.rb
avo-3.5.5 lib/avo/services/encryption_service.rb
avo-3.5.4 lib/avo/services/encryption_service.rb
avo-3.5.3 lib/avo/services/encryption_service.rb
avo-3.5.2 lib/avo/services/encryption_service.rb
avo-3.5.1 lib/avo/services/encryption_service.rb
avo-3.5.0 lib/avo/services/encryption_service.rb
avo-3.4.4 lib/avo/services/encryption_service.rb
avo-3.4.3 lib/avo/services/encryption_service.rb
avo-3.4.2 lib/avo/services/encryption_service.rb
avo-3.4.1 lib/avo/services/encryption_service.rb
avo-3.4.0 lib/avo/services/encryption_service.rb