From 9232aa31760c0d29095b5ce2cf43e7fc9140008e Mon Sep 17 00:00:00 2001 From: Daniel Azuma Date: Tue, 5 Jun 2018 09:56:48 -0700 Subject: [PATCH] Unescape private_key loaded from ENV (#132) --- lib/googleauth/service_account.rb | 11 ++++++++++- spec/googleauth/service_account_spec.rb | 7 +++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/googleauth/service_account.rb b/lib/googleauth/service_account.rb index 03bc0cf..2b96ed5 100644 --- a/lib/googleauth/service_account.rb +++ b/lib/googleauth/service_account.rb @@ -58,7 +58,7 @@ module Google if json_key_io private_key, client_email = read_json_key(json_key_io) else - private_key = ENV[CredentialsLoader::PRIVATE_KEY_VAR] + private_key = unescape ENV[CredentialsLoader::PRIVATE_KEY_VAR] client_email = ENV[CredentialsLoader::CLIENT_EMAIL_VAR] end @@ -78,6 +78,15 @@ module Google [json_key['private_key'], json_key['client_email']] end + # Handles certain escape sequences that sometimes appear in input. + # Specifically, interprets the "\n" sequence for newline, and removes + # enclosing quotes. + def self.unescape(str) + str = str.gsub '\n', "\n" + str = str[1..-2] if str.start_with?('"') && str.end_with?('"') + str + end + def initialize(options = {}) super(options) end diff --git a/spec/googleauth/service_account_spec.rb b/spec/googleauth/service_account_spec.rb index 26bbcba..799b051 100644 --- a/spec/googleauth/service_account_spec.rb +++ b/spec/googleauth/service_account_spec.rb @@ -211,6 +211,13 @@ describe Google::Auth::ServiceAccountCredentials do ENV[CLIENT_EMAIL_VAR] = cred_json[:client_email] expect(@clz.from_env(@scope)).to_not be_nil end + + it 'succeeds when GOOGLE_PRIVATE_KEY is escaped' do + escaped_key = cred_json[:private_key].gsub "\n", '\n' + ENV[PRIVATE_KEY_VAR] = "\"#{escaped_key}\"" + ENV[CLIENT_EMAIL_VAR] = cred_json[:client_email] + expect(@clz.from_env(@scope)).to_not be_nil + end end describe '#from_well_known_path' do