fix: Retry fetch_access_token when GCE metadata server returns unexpected errors

This commit is contained in:
Spring_MT 2020-11-10 13:33:01 +09:00 committed by GitHub
parent 93b9380ee5
commit cd9b0126d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 4 deletions

View File

@ -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

View File

@ -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,