Skip to content

Commit 83f0d5e

Browse files
fix: check id token error response (#1315)
1 parent 44267b7 commit 83f0d5e

File tree

3 files changed

+34
-5
lines changed

3 files changed

+34
-5
lines changed

packages/google-auth/google/auth/impersonated_credentials.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -438,11 +438,19 @@ def refresh(self, request):
438438
self._target_credentials._source_credentials, auth_request=request
439439
)
440440

441-
response = authed_session.post(
442-
url=iam_sign_endpoint,
443-
headers=headers,
444-
data=json.dumps(body).encode("utf-8"),
445-
)
441+
try:
442+
response = authed_session.post(
443+
url=iam_sign_endpoint,
444+
headers=headers,
445+
data=json.dumps(body).encode("utf-8"),
446+
)
447+
finally:
448+
authed_session.close()
449+
450+
if response.status_code != http_client.OK:
451+
raise exceptions.RefreshError(
452+
"Error getting ID token: {}".format(response.json())
453+
)
446454

447455
id_token = response.json()["token"]
448456
self.token = id_token
0 Bytes
Binary file not shown.

packages/google-auth/tests/test_impersonated_credentials.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,27 @@ def test_refresh_failure_unauthorzed(self, mock_donor_credentials):
318318
assert not credentials.valid
319319
assert credentials.expired
320320

321+
def test_refresh_failure(self):
322+
credentials = self.make_credentials(lifetime=None)
323+
credentials.expiry = None
324+
credentials.token = "token"
325+
id_creds = impersonated_credentials.IDTokenCredentials(
326+
credentials, target_audience="audience"
327+
)
328+
329+
response = mock.create_autospec(transport.Response, instance=False)
330+
response.status_code = http_client.UNAUTHORIZED
331+
response.json = mock.Mock(return_value="failed to get ID token")
332+
333+
with mock.patch(
334+
"google.auth.transport.requests.AuthorizedSession.post",
335+
return_value=response,
336+
):
337+
with pytest.raises(exceptions.RefreshError) as excinfo:
338+
id_creds.refresh(None)
339+
340+
assert excinfo.match("Error getting ID token")
341+
321342
def test_refresh_failure_http_error(self, mock_donor_credentials):
322343
credentials = self.make_credentials(lifetime=None)
323344

0 commit comments

Comments
 (0)