lib/legion/crypt/cipher.rb in legion-crypt-0.3.0 vs lib/legion/crypt/cipher.rb in legion-crypt-1.2.0
- old
+ new
@@ -1,10 +1,13 @@
require 'securerandom'
+require 'legion/crypt/cluster_secret'
module Legion
module Crypt
module Cipher
+ include Legion::Crypt::ClusterSecret
+
def encrypt(message)
cipher = OpenSSL::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.key = cs
iv = cipher.random_iv
@@ -43,61 +46,9 @@
@private_key ||= if Legion::Settings[:crypt][:read_private_key] && File.exist?('./legionio.key')
OpenSSL::PKey::RSA.new File.read './legionio.key'
else
OpenSSL::PKey::RSA.new 2048
end
- end
-
- def cs
- @cs ||= Digest::SHA256.digest(fetch_cs)
- end
-
- def fetch_cs # rubocop:disable Metrics/AbcSize,Metrics/PerceivedComplexity,Metrics/CyclomaticComplexity
- if Legion::Settings[:crypt][:vault][:read_cluster_secret] && Legion::Settings[:crypt][:vault][:connected] && Legion::Crypt.exist?('crypt') # rubocop:disable Layout/LineLength
- Legion::Crypt.get('crypt')[:cluster_secret]
- elsif Legion::Settings[:crypt][:cluster_secret].is_a? String
- Legion::Settings[:crypt][:cluster_secret]
- elsif Legion::Transport::Queue.new('node.crypt', passive: true).consumer_count.zero?
- Legion::Settings[:crypt][:cluster_secret] = generate_secure_random
- elsif Legion::Transport::Queue.new('node.crypt', passive: true).consumer_count.positive?
- require 'legion/transport/messages/request_cluster_secret'
- Legion::Logging.info 'Requesting cluster secret via public key'
- start = Time.now
- Legion::Transport::Messages::RequestClusterSecret.new.publish
- sleep_time = 0.001
- until !Legion::Settings[:crypt][:cluster_secret].nil? || (Time.now - start) > Legion::Settings[:crypt][:cluster_secret_timeout]
- sleep(sleep_time)
- sleep_time *= 2 unless sleep_time > 0.5
- end
-
- if Legion::Settings[:crypt][:cluster_secret].nil?
- Legion::Logging.warn 'Cluster secret is still nil'
- else
- Legion::Logging.info "Received cluster secret in #{((Time.new - start) * 1000.0).round}ms"
- end
- end
- rescue StandardError => e
- Legion::Logging.error(e.message)
- Legion::Logging.error(e.backtrace)
- ensure
- Legion::Settings[:crypt][:cluster_secret] = generate_secure_random unless Legion::Settings[:crypt].key? :cluster_secret
- nil if Legion::Settings[:crypt][:cluster_secret].nil?
-
- Legion::Settings[:crypt][:cs_encrypt_ready] = true
- push_cs_to_vault if Legion::Settings[:crypt][:vault][:push_cs_to_vault]
-
- return Legion::Settings[:crypt][:cluster_secret] # rubocop:disable Lint/EnsureReturn
- end
-
- def push_cs_to_vault
- return false unless Legion::Settings[:crypt][:vault][:connected] && Legion::Settings[:crypt][:cluster_secret]
-
- Legion::Logging.info 'Pushing Cluster Secret to Vault'
- Legion::Crypt.write('cluster', secret: Legion::Settings[:crypt][:cluster_secret])
- end
-
- def generate_secure_random
- SecureRandom.uuid
end
end
end
end