Sha256: 7f7e59437a776167751e67e6ed92022805ff33fce71be023b80b2de2859bb502

Contents?: true

Size: 1.09 KB

Versions: 10

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true
module Shipit
  class EnvironmentVariables
    NotPermitted = Class.new(StandardError)

    class << self
      def with(env)
        EnvironmentVariables.new(env)
      end
    end

    def permit(variable_definitions)
      return {} unless @env
      raise "A whitelist is required to sanitize environment variables" unless variable_definitions
      sanitize_env_vars(variable_definitions)
    end

    def interpolate(argument)
      return argument unless @env

      argument.gsub(/(\$\w+)/) do |variable|
        variable.sub!('$', '')
        Shellwords.escape(@env.fetch(variable) { ENV[variable] })
      end
    end

    private

    def initialize(env)
      @env = env
    end

    def sanitize_env_vars(variable_definitions)
      allowed_variables = variable_definitions.map(&:name)

      allowed, disallowed = @env.partition { |k, _| allowed_variables.include?(k) }.map(&:to_h)

      error_message = "Variables #{disallowed.keys.to_sentence} have not been whitelisted"
      raise NotPermitted, error_message unless disallowed.empty?

      allowed
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
shipit-engine-0.39.0 lib/shipit/environment_variables.rb
shipit-engine-0.38.0 lib/shipit/environment_variables.rb
shipit-engine-0.37.0 lib/shipit/environment_variables.rb
shipit-engine-0.36.1 lib/shipit/environment_variables.rb
shipit-engine-0.36.0 lib/shipit/environment_variables.rb
shipit-engine-0.35.1 lib/shipit/environment_variables.rb
shipit-engine-0.35.0 lib/shipit/environment_variables.rb
shipit-engine-0.34.0 lib/shipit/environment_variables.rb
shipit-engine-0.33.0 lib/shipit/environment_variables.rb
shipit-engine-0.32.0 lib/shipit/environment_variables.rb