From cd9b0126d3419b9953982f71edc9e6ba3f640e3c Mon Sep 17 00:00:00 2001 From: Spring_MT Date: Tue, 10 Nov 2020 13:33:01 +0900 Subject: [PATCH] fix: Retry fetch_access_token when GCE metadata server returns unexpected errors --- lib/googleauth/compute_engine.rb | 9 +++++---- spec/googleauth/compute_engine_spec.rb | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/lib/googleauth/compute_engine.rb b/lib/googleauth/compute_engine.rb index a11c422..eb197df 100644 --- a/lib/googleauth/compute_engine.rb +++ b/lib/googleauth/compute_engine.rb @@ -108,8 +108,7 @@ module Google uri = target_audience ? GCECredentials.compute_id_token_uri : GCECredentials.compute_auth_token_uri query = target_audience ? { "audience" => target_audience, "format" => "full" } : {} query[:scopes] = Array(scope).join "," if scope - headers = { "Metadata-Flavor" => "Google" } - resp = c.get uri, query, headers + resp = c.get uri, query, "Metadata-Flavor" => "Google" case resp.status when 200 content_type = resp.headers["content-type"] @@ -118,11 +117,13 @@ module Google else Signet::OAuth2.parse_credentials resp.body, content_type end + when 403, 500 + msg = "Unexpected error code #{resp.status} #{UNEXPECTED_ERROR_SUFFIX}" + raise Signet::UnexpectedStatusError, msg when 404 raise Signet::AuthorizationError, NO_METADATA_SERVER_ERROR else - msg = "Unexpected error code #{resp.status}" \ - "#{UNEXPECTED_ERROR_SUFFIX}" + msg = "Unexpected error code #{resp.status} #{UNEXPECTED_ERROR_SUFFIX}" raise Signet::AuthorizationError, msg end end diff --git a/spec/googleauth/compute_engine_spec.rb b/spec/googleauth/compute_engine_spec.rb index 156e55f..53ebd7b 100644 --- a/spec/googleauth/compute_engine_spec.rb +++ b/spec/googleauth/compute_engine_spec.rb @@ -90,6 +90,24 @@ describe Google::Auth::GCECredentials do expect(stub).to have_been_requested end + it "should fail if the metadata request returns a 403" do + stub = stub_request(:get, MD_ACCESS_URI) + .to_return(status: 403, + headers: { "Metadata-Flavor" => "Google" }) + expect { @client.fetch_access_token! } + .to raise_error Signet::AuthorizationError + expect(stub).to have_been_requested.times(6) + end + + it "should fail if the metadata request returns a 500" do + stub = stub_request(:get, MD_ACCESS_URI) + .to_return(status: 500, + headers: { "Metadata-Flavor" => "Google" }) + expect { @client.fetch_access_token! } + .to raise_error Signet::AuthorizationError + expect(stub).to have_been_requested.times(6) + end + it "should fail if the metadata request returns an unexpected code" do stub = stub_request(:get, MD_ACCESS_URI) .to_return(status: 503,