Module: Slosilo::Migration::MigrateKeys

Defined in:
lib/slosilo/migration/migrate_keys.rb

Constant Summary collapse

DEFAULT_KEYSTORE_TABLE =
:slosilo_keystore

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#keystore_tableObject



11
12
13
# File 'lib/slosilo/migration/migrate_keys.rb', line 11

def keystore_table
  @keystore_table ||= DEFAULT_KEYSTORE_TABLE
end

Instance Method Details

#progress_bar(count) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/slosilo/migration/migrate_keys.rb', line 48

def progress_bar count
  begin
    require 'ruby-progressbar'
    ProgressBar.create total: count, output: $stderr, format: '%t |%w>%i| %e'
  rescue LoadError
    Object.new.tap do |o|
      def o.increment; $stderr << '.' end
    end
  end
end

#upgrade!(db) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/slosilo/migration/migrate_keys.rb', line 15

def upgrade! db
  keystore = db[keystore_table]
  return unless keystore.count > 0

  key = Slosilo::encryption_key
  if key.nil?
    warn "Slosilo::encryption_key not set, assuming unencrypted key store"
    return
  end


  old_cipher = Slosilo::Migration::Symmetric.new
  new_cipher = Slosilo::Symmetric.new


  progress = progress_bar keystore.count

  keystore.each  do |row|
    begin
      # try to decrypt using new cipher
      new_cipher.decrypt row[:key], key: key, aad: row[:id]
      # it worked, no need to update
    rescue OpenSSL::Cipher::CipherError
      # otherwise, needs to be upgraded.
      ptext = old_cipher.decrypt row[:key], key: key
      ctext = new_cipher.encrypt ptext, key: key, aad: row[:id]
      keystore.where(id: row[:id]).update(key: Sequel.blob(ctext))
    end
    progress.increment
  end
end