Class: ActiveSupport::EncryptedFile

Inherits:
Object
  • Object
show all
Defined in:
lib/active_support/encrypted_file.rb

Direct Known Subclasses

EncryptedConfiguration

Defined Under Namespace

Classes: MissingContentError, MissingKeyError

Constant Summary collapse

CIPHER =
"aes-128-gcm"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content_path:, key_path:, env_key:, raise_if_missing_key:) ⇒ EncryptedFile

Returns a new instance of EncryptedFile.



32
33
34
35
# File 'lib/active_support/encrypted_file.rb', line 32

def initialize(content_path:, key_path:, env_key:, raise_if_missing_key:)
  @content_path, @key_path = Pathname.new(content_path), Pathname.new(key_path)
  @env_key, @raise_if_missing_key = env_key, raise_if_missing_key
end

Instance Attribute Details

#content_pathObject (readonly)

Returns the value of attribute content_path.



30
31
32
# File 'lib/active_support/encrypted_file.rb', line 30

def content_path
  @content_path
end

#env_keyObject (readonly)

Returns the value of attribute env_key.



30
31
32
# File 'lib/active_support/encrypted_file.rb', line 30

def env_key
  @env_key
end

#key_pathObject (readonly)

Returns the value of attribute key_path.



30
31
32
# File 'lib/active_support/encrypted_file.rb', line 30

def key_path
  @key_path
end

#raise_if_missing_keyObject (readonly)

Returns the value of attribute raise_if_missing_key.



30
31
32
# File 'lib/active_support/encrypted_file.rb', line 30

def raise_if_missing_key
  @raise_if_missing_key
end

Class Method Details

.generate_keyObject



25
26
27
# File 'lib/active_support/encrypted_file.rb', line 25

def self.generate_key
  SecureRandom.hex(ActiveSupport::MessageEncryptor.key_len(CIPHER))
end

Instance Method Details

#change(&block) ⇒ Object



54
55
56
# File 'lib/active_support/encrypted_file.rb', line 54

def change(&block)
  writing read, &block
end

#keyObject



37
38
39
# File 'lib/active_support/encrypted_file.rb', line 37

def key
  read_env_key || read_key_file || handle_missing_key
end

#readObject



41
42
43
44
45
46
47
# File 'lib/active_support/encrypted_file.rb', line 41

def read
  if !key.nil? && content_path.exist?
    decrypt content_path.binread
  else
    raise MissingContentError, content_path
  end
end

#write(contents) ⇒ Object



49
50
51
52
# File 'lib/active_support/encrypted_file.rb', line 49

def write(contents)
  IO.binwrite "#{content_path}.tmp", encrypt(contents)
  FileUtils.mv "#{content_path}.tmp", content_path
end