Skip to content

Commit

Permalink
fix: Retry fetch_access_token when GCE metadata server returns unexpe…
Browse files Browse the repository at this point in the history
…cted errors
  • Loading branch information
Spring_MT committed Nov 10, 2020
1 parent 93b9380 commit cd9b012
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib/googleauth/compute_engine.rb
Expand Up @@ -108,8 +108,7 @@ def fetch_access_token options = {}
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"]
Expand All @@ -118,11 +117,13 @@ def fetch_access_token options = {}
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
Expand Down
18 changes: 18 additions & 0 deletions spec/googleauth/compute_engine_spec.rb
Expand Up @@ -90,6 +90,24 @@ def make_auth_stubs opts
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,
Expand Down

0 comments on commit cd9b012

Please sign in to comment.