Class: OpCredentials::Vault

Inherits:
Object
  • Object
show all
Defined in:
lib/op_credentials/vault.rb

Constant Summary collapse

OP_VAULT_SECRETS =
{}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Vault

Returns a new instance of Vault.



11
12
13
# File 'lib/op_credentials/vault.rb', line 11

def initialize(name)
  @name = name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/op_credentials/vault.rb', line 8

def name
  @name
end

Instance Method Details

#fetch_secret(label:, default: nil, delete: true) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/op_credentials/vault.rb', line 30

def fetch_secret(label:, default: nil, delete: true)
  if compiling_assets?
    "" # doesn't matter for asset compilation
  elsif !Rails.env.local?
    (delete ? OP_VAULT_SECRETS.delete(label) : OP_VAULT_SECRETS[label]) || raise("Secret `#{label}` not found in 1Password")
  else # look for it in credentials; if not, in env, if not, the default
    Rails.application.credentials.fetch(:label, ENV.fetch(label, default))
  end
end

#load(tags: [ENV["RAILS_ENV"]]) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/op_credentials/vault.rb', line 15

def load(tags: [ENV["RAILS_ENV"]])
  # To reduce the amount of API calls to 1Password, we can
  # grab one document that contains all the secrets we need
  if !compiling_assets? && !Rails.env.local?
    result = op_load_vault_into_env(tags: tags)
    if result.is_a?(Array)
      raise RuntimeError, "No items found in vault `#{@name}` for tags: #{tags}"
    end

    result["fields"].select { |f| f["value"] }.each do |field|
      load_vault_secret(field)
    end
  end
end