class Secrets

Attributes

ejson_config_file[R]

Public Class Methods

new(config_file = nil, required = []) click to toggle source
# File lib/helpers/secrets.rb, line 10
def initialize(config_file = nil, required = [])
  @ejson_config_file = config_file
  @secrets = {}
  unless config_file.nil?
    load_from_ejson(config_file)
    load_from_env(@secrets.keys)
  end
  unless required.empty?
    load_from_env(required)
    check_required(required)
  end
end

Public Instance Methods

[](key) click to toggle source
# File lib/helpers/secrets.rb, line 58
def [](key)
  @secrets[key.to_sym]
end
check_required(required = []) click to toggle source
# File lib/helpers/secrets.rb, line 54
def check_required(required = [])
  required.each { |key| raise "required secrets not set: #{key}" if @secrets[key].nil? }
end
hash_symblize_keys(hash) click to toggle source
# File lib/helpers/secrets.rb, line 73
def hash_symblize_keys(hash)
  hash.keys.each do |key|
    hash[(begin
      key.to_sym
    rescue
      key
    end) || key] = hash.delete(key)
  end
  hash
end
load_from_ejson(ejson_path) click to toggle source
# File lib/helpers/secrets.rb, line 23
def load_from_ejson(ejson_path)
  ejson_path = File.absolute_path(ejson_path) unless Pathname.new(ejson_path).absolute?
  raise "config file: #{ejson_path} not found" unless File.exist?(ejson_path)

  encrypted_json = JSON.parse(File.read(ejson_path))
  public_key = encrypted_json['_public_key']
  private_key_path = "/opt/ejson/keys/#{public_key}"
  raise "Private key is not listed in #{private_key_path}." unless File.exist?(private_key_path)

  output, status = Open3.capture2e("ejson", "decrypt", ejson_path.to_s)
  raise "ejson: #{output}" unless status.success?

  secrets = JSON.parse(output)
  secrets = hash_symblize_keys(secrets)

  @secrets.merge!(secrets)
end
load_from_env(keys) click to toggle source
# File lib/helpers/secrets.rb, line 41
def load_from_env(keys)
  secrets = {}
  keys.each do |key|
    key = key.to_s
    next if key.start_with?("_")
    value = ENV[key.upcase]
    secrets[key] = value unless value.nil?
  end

  secrets = hash_symblize_keys(secrets)
  @secrets.merge!(secrets)
end
method_missing(key, *args) click to toggle source
Calls superclass method
# File lib/helpers/secrets.rb, line 62
def method_missing(key, *args)
  value = @secrets[key]
  return value unless value.nil?
  puts "no secret for key: #{key}"
  super
end
respond_to_missing?(*args) click to toggle source
Calls superclass method
# File lib/helpers/secrets.rb, line 69
def respond_to_missing?(*args)
  super
end