From a1a9387c2b8677b4e6f13ba0be95fa4677b94500 Mon Sep 17 00:00:00 2001 From: Kazuhiro Serizawa Date: Sat, 25 Feb 2017 21:45:07 +0900 Subject: [PATCH] Use retry_with_error in GCECredentials#fetch_access_token --- lib/googleauth/compute_engine.rb | 23 +++++++++++++---------- spec/googleauth/compute_engine_spec.rb | 14 ++++++++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/lib/googleauth/compute_engine.rb b/lib/googleauth/compute_engine.rb index 9b14e0a..119a04e 100644 --- a/lib/googleauth/compute_engine.rb +++ b/lib/googleauth/compute_engine.rb @@ -88,16 +88,19 @@ END def fetch_access_token(options = {}) c = options[:connection] || Faraday.default_connection c.headers = { 'Metadata-Flavor' => 'Google' } - resp = c.get(COMPUTE_AUTH_TOKEN_URI) - case resp.status - when 200 - Signet::OAuth2.parse_credentials(resp.body, - resp.headers['content-type']) - when 404 - raise(Signet::AuthorizationError, NO_METADATA_SERVER_ERROR) - else - msg = "Unexpected error code #{resp.status}" + UNEXPECTED_ERROR_SUFFIX - raise(Signet::AuthorizationError, msg) + + retry_with_error do + resp = c.get(COMPUTE_AUTH_TOKEN_URI) + case resp.status + when 200 + Signet::OAuth2.parse_credentials(resp.body, + resp.headers['content-type']) + when 404 + raise(Signet::AuthorizationError, NO_METADATA_SERVER_ERROR) + else + msg = "Unexpected error code #{resp.status}" + UNEXPECTED_ERROR_SUFFIX + raise(Signet::AuthorizationError, msg) + end end end end diff --git a/spec/googleauth/compute_engine_spec.rb b/spec/googleauth/compute_engine_spec.rb index c98fec2..f12d0ef 100644 --- a/spec/googleauth/compute_engine_spec.rb +++ b/spec/googleauth/compute_engine_spec.rb @@ -77,6 +77,20 @@ describe Google::Auth::GCECredentials do .to raise_error Signet::AuthorizationError expect(stub).to have_been_requested end + + it 'should fail with Signet::AuthorizationError if request times out' do + allow_any_instance_of(Faraday::Connection).to receive(:get) + .and_raise(Faraday::TimeoutError) + expect { @client.fetch_access_token! } + .to raise_error Signet::AuthorizationError + end + + it 'should fail with Signet::AuthorizationError if request fails' do + allow_any_instance_of(Faraday::Connection).to receive(:get) + .and_raise(Faraday::ConnectionFailed, nil) + expect { @client.fetch_access_token! } + .to raise_error Signet::AuthorizationError + end end end