From 511e666f6274285dfdc709486cd55a94cddd4dc8 Mon Sep 17 00:00:00 2001 From: Nick Carboni Date: Fri, 9 Dec 2016 09:32:22 -0500 Subject: [PATCH] Expose a method for encrypting using a remote v2_key These keys are saved as a part of configuring central admin. When encrypted data must be send to a remote region, that data has to be encrypted using the remote region's encryption key. This allows callers to encrypt the data so that the remote region can use it properly. https://bugzilla.redhat.com/show_bug.cgi?id=1400995 --- app/models/miq_region.rb | 18 +++++++++++------- spec/models/miq_region_spec.rb | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/app/models/miq_region.rb b/app/models/miq_region.rb index 2fa2a24a485..5a5fd204f21 100644 --- a/app/models/miq_region.rb +++ b/app/models/miq_region.rb @@ -290,29 +290,33 @@ def auth_key_configured? end def api_system_auth_token(userid) - region_v2_key = authentication_token(AUTHENTICATION_TYPE) - token_hash = { :server_guid => remote_ws_miq_server.guid, :userid => userid, :timestamp => Time.now.utc } + encrypt(token_hash.to_yaml) + end + + def required_credential_fields(_type) + [:auth_key] + end + + def encrypt(string) + region_v2_key = authentication_token(AUTHENTICATION_TYPE) + raise "No key configured for region #{region}. Configure Central Admin to fetch the key" if region_v2_key.nil? file = Tempfile.new("region_auth_key") begin file.write(region_v2_key) file.close key = EzCrypto::Key.load(file.path) - MiqPassword.new.encrypt(token_hash.to_yaml, "v2", key) + MiqPassword.new.encrypt(string, "v2", key) ensure file.unlink end end - def required_credential_fields(_type) - [:auth_key] - end - def self.api_system_auth_token_for_region(region_id, user) find_by_region(region_id).api_system_auth_token(user) end diff --git a/spec/models/miq_region_spec.rb b/spec/models/miq_region_spec.rb index 977450c0332..36ca3a161c0 100644 --- a/spec/models/miq_region_spec.rb +++ b/spec/models/miq_region_spec.rb @@ -238,6 +238,24 @@ end end + describe "#encrypt" do + let(:region) { FactoryGirl.create(:miq_region, :region => ApplicationRecord.my_region_number) } + + it "correctly encrypts a string using the authentication token" do + expect(region).to receive(:authentication_token).and_return(File.read(Rails.root.join("certs/v2_key"))) + + a_string = "this should be encrypted correctly" + enc = region.encrypt(a_string) + other_string = MiqPassword.decrypt(enc) + + expect(other_string).to eq(a_string) + end + + it "raises if no key is configured" do + expect { region.encrypt("a string") }.to raise_error(RuntimeError) + end + end + context "ConfigurationManagementMixin" do let(:region) { FactoryGirl.create(:miq_region, :region => ApplicationRecord.my_region_number) }