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) }