test_impersonated_credentials.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. # Copyright 2018 Google Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import datetime
  15. import http.client as http_client
  16. import json
  17. import os
  18. import mock
  19. import pytest # type: ignore
  20. from google.auth import _helpers
  21. from google.auth import crypt
  22. from google.auth import exceptions
  23. from google.auth import impersonated_credentials
  24. from google.auth import transport
  25. from google.auth.impersonated_credentials import Credentials
  26. from google.oauth2 import credentials
  27. from google.oauth2 import service_account
  28. import yatest.common as yc
  29. DATA_DIR = os.path.join(os.path.dirname(yc.source_path(__file__)), "data")
  30. with open(os.path.join(DATA_DIR, "privatekey.pem"), "rb") as fh:
  31. PRIVATE_KEY_BYTES = fh.read()
  32. SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, "service_account.json")
  33. ID_TOKEN_DATA = (
  34. "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRmMzc1ODkwOGI3OTIyOTNhZDk3N2Ew"
  35. "Yjk5MWQ5OGE3N2Y0ZWVlY2QiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOiJodHRwc"
  36. "zovL2Zvby5iYXIiLCJhenAiOiIxMDIxMDE1NTA4MzQyMDA3MDg1NjgiLCJle"
  37. "HAiOjE1NjQ0NzUwNTEsImlhdCI6MTU2NDQ3MTQ1MSwiaXNzIjoiaHR0cHM6L"
  38. "y9hY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTAyMTAxNTUwODM0MjAwN"
  39. "zA4NTY4In0.redacted"
  40. )
  41. ID_TOKEN_EXPIRY = 1564475051
  42. with open(SERVICE_ACCOUNT_JSON_FILE, "rb") as fh:
  43. SERVICE_ACCOUNT_INFO = json.load(fh)
  44. SIGNER = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES, "1")
  45. TOKEN_URI = "https://example.com/oauth2/token"
  46. ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE = (
  47. "gl-python/3.7 auth/1.1 auth-request-type/at cred-type/imp"
  48. )
  49. ID_TOKEN_REQUEST_METRICS_HEADER_VALUE = (
  50. "gl-python/3.7 auth/1.1 auth-request-type/it cred-type/imp"
  51. )
  52. @pytest.fixture
  53. def mock_donor_credentials():
  54. with mock.patch("google.oauth2._client.jwt_grant", autospec=True) as grant:
  55. grant.return_value = (
  56. "source token",
  57. _helpers.utcnow() + datetime.timedelta(seconds=500),
  58. {},
  59. )
  60. yield grant
  61. class MockResponse:
  62. def __init__(self, json_data, status_code):
  63. self.json_data = json_data
  64. self.status_code = status_code
  65. def json(self):
  66. return self.json_data
  67. @pytest.fixture
  68. def mock_authorizedsession_sign():
  69. with mock.patch(
  70. "google.auth.transport.requests.AuthorizedSession.request", autospec=True
  71. ) as auth_session:
  72. data = {"keyId": "1", "signedBlob": "c2lnbmF0dXJl"}
  73. auth_session.return_value = MockResponse(data, http_client.OK)
  74. yield auth_session
  75. @pytest.fixture
  76. def mock_authorizedsession_idtoken():
  77. with mock.patch(
  78. "google.auth.transport.requests.AuthorizedSession.request", autospec=True
  79. ) as auth_session:
  80. data = {"token": ID_TOKEN_DATA}
  81. auth_session.return_value = MockResponse(data, http_client.OK)
  82. yield auth_session
  83. class TestImpersonatedCredentials(object):
  84. SERVICE_ACCOUNT_EMAIL = "service-account@example.com"
  85. TARGET_PRINCIPAL = "impersonated@project.iam.gserviceaccount.com"
  86. TARGET_SCOPES = ["https://www.googleapis.com/auth/devstorage.read_only"]
  87. # DELEGATES: List[str] = []
  88. # Because Python 2.7:
  89. DELEGATES = [] # type: ignore
  90. LIFETIME = 3600
  91. SOURCE_CREDENTIALS = service_account.Credentials(
  92. SIGNER, SERVICE_ACCOUNT_EMAIL, TOKEN_URI
  93. )
  94. USER_SOURCE_CREDENTIALS = credentials.Credentials(token="ABCDE")
  95. IAM_ENDPOINT_OVERRIDE = (
  96. "https://us-east1-iamcredentials.googleapis.com/v1/projects/-"
  97. + "/serviceAccounts/{}:generateAccessToken".format(SERVICE_ACCOUNT_EMAIL)
  98. )
  99. def make_credentials(
  100. self,
  101. source_credentials=SOURCE_CREDENTIALS,
  102. lifetime=LIFETIME,
  103. target_principal=TARGET_PRINCIPAL,
  104. iam_endpoint_override=None,
  105. ):
  106. return Credentials(
  107. source_credentials=source_credentials,
  108. target_principal=target_principal,
  109. target_scopes=self.TARGET_SCOPES,
  110. delegates=self.DELEGATES,
  111. lifetime=lifetime,
  112. iam_endpoint_override=iam_endpoint_override,
  113. )
  114. def test_get_cred_info(self):
  115. credentials = self.make_credentials()
  116. assert not credentials.get_cred_info()
  117. credentials._cred_file_path = "/path/to/file"
  118. assert credentials.get_cred_info() == {
  119. "credential_source": "/path/to/file",
  120. "credential_type": "impersonated credentials",
  121. "principal": "impersonated@project.iam.gserviceaccount.com",
  122. }
  123. def test__make_copy_get_cred_info(self):
  124. credentials = self.make_credentials()
  125. credentials._cred_file_path = "/path/to/file"
  126. cred_copy = credentials._make_copy()
  127. assert cred_copy._cred_file_path == "/path/to/file"
  128. def test_make_from_user_credentials(self):
  129. credentials = self.make_credentials(
  130. source_credentials=self.USER_SOURCE_CREDENTIALS
  131. )
  132. assert not credentials.valid
  133. assert credentials.expired
  134. def test_default_state(self):
  135. credentials = self.make_credentials()
  136. assert not credentials.valid
  137. assert credentials.expired
  138. def test_make_from_service_account_self_signed_jwt(self):
  139. source_credentials = service_account.Credentials(
  140. SIGNER, self.SERVICE_ACCOUNT_EMAIL, TOKEN_URI, always_use_jwt_access=True
  141. )
  142. credentials = self.make_credentials(source_credentials=source_credentials)
  143. # test the source credential don't lose self signed jwt setting
  144. assert credentials._source_credentials._always_use_jwt_access
  145. assert credentials._source_credentials._jwt_credentials
  146. def make_request(
  147. self,
  148. data,
  149. status=http_client.OK,
  150. headers=None,
  151. side_effect=None,
  152. use_data_bytes=True,
  153. ):
  154. response = mock.create_autospec(transport.Response, instance=False)
  155. response.status = status
  156. response.data = _helpers.to_bytes(data) if use_data_bytes else data
  157. response.headers = headers or {}
  158. request = mock.create_autospec(transport.Request, instance=False)
  159. request.side_effect = side_effect
  160. request.return_value = response
  161. return request
  162. def test_token_usage_metrics(self):
  163. credentials = self.make_credentials()
  164. credentials.token = "token"
  165. credentials.expiry = None
  166. headers = {}
  167. credentials.before_request(mock.Mock(), None, None, headers)
  168. assert headers["authorization"] == "Bearer token"
  169. assert headers["x-goog-api-client"] == "cred-type/imp"
  170. @pytest.mark.parametrize("use_data_bytes", [True, False])
  171. def test_refresh_success(self, use_data_bytes, mock_donor_credentials):
  172. credentials = self.make_credentials(lifetime=None)
  173. token = "token"
  174. expire_time = (
  175. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  176. ).isoformat("T") + "Z"
  177. response_body = {"accessToken": token, "expireTime": expire_time}
  178. request = self.make_request(
  179. data=json.dumps(response_body),
  180. status=http_client.OK,
  181. use_data_bytes=use_data_bytes,
  182. )
  183. with mock.patch(
  184. "google.auth.metrics.token_request_access_token_impersonate",
  185. return_value=ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE,
  186. ):
  187. credentials.refresh(request)
  188. assert credentials.valid
  189. assert not credentials.expired
  190. assert (
  191. request.call_args.kwargs["headers"]["x-goog-api-client"]
  192. == ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE
  193. )
  194. @pytest.mark.parametrize("use_data_bytes", [True, False])
  195. def test_refresh_success_iam_endpoint_override(
  196. self, use_data_bytes, mock_donor_credentials
  197. ):
  198. credentials = self.make_credentials(
  199. lifetime=None, iam_endpoint_override=self.IAM_ENDPOINT_OVERRIDE
  200. )
  201. token = "token"
  202. expire_time = (
  203. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  204. ).isoformat("T") + "Z"
  205. response_body = {"accessToken": token, "expireTime": expire_time}
  206. request = self.make_request(
  207. data=json.dumps(response_body),
  208. status=http_client.OK,
  209. use_data_bytes=use_data_bytes,
  210. )
  211. credentials.refresh(request)
  212. assert credentials.valid
  213. assert not credentials.expired
  214. # Confirm override endpoint used.
  215. request_kwargs = request.call_args[1]
  216. assert request_kwargs["url"] == self.IAM_ENDPOINT_OVERRIDE
  217. @pytest.mark.parametrize("time_skew", [150, -150])
  218. def test_refresh_source_credentials(self, time_skew):
  219. credentials = self.make_credentials(lifetime=None)
  220. # Source credentials is refreshed only if it is expired within
  221. # _helpers.REFRESH_THRESHOLD from now. We add a time_skew to the expiry, so
  222. # source credentials is refreshed only if time_skew <= 0.
  223. credentials._source_credentials.expiry = (
  224. _helpers.utcnow()
  225. + _helpers.REFRESH_THRESHOLD
  226. + datetime.timedelta(seconds=time_skew)
  227. )
  228. credentials._source_credentials.token = "Token"
  229. with mock.patch(
  230. "google.oauth2.service_account.Credentials.refresh", autospec=True
  231. ) as source_cred_refresh:
  232. expire_time = (
  233. _helpers.utcnow().replace(microsecond=0)
  234. + datetime.timedelta(seconds=500)
  235. ).isoformat("T") + "Z"
  236. response_body = {"accessToken": "token", "expireTime": expire_time}
  237. request = self.make_request(
  238. data=json.dumps(response_body), status=http_client.OK
  239. )
  240. credentials.refresh(request)
  241. assert credentials.valid
  242. assert not credentials.expired
  243. # Source credentials is refreshed only if it is expired within
  244. # _helpers.REFRESH_THRESHOLD
  245. if time_skew > 0:
  246. source_cred_refresh.assert_not_called()
  247. else:
  248. source_cred_refresh.assert_called_once()
  249. def test_refresh_failure_malformed_expire_time(self, mock_donor_credentials):
  250. credentials = self.make_credentials(lifetime=None)
  251. token = "token"
  252. expire_time = (_helpers.utcnow() + datetime.timedelta(seconds=500)).isoformat(
  253. "T"
  254. )
  255. response_body = {"accessToken": token, "expireTime": expire_time}
  256. request = self.make_request(
  257. data=json.dumps(response_body), status=http_client.OK
  258. )
  259. with pytest.raises(exceptions.RefreshError) as excinfo:
  260. credentials.refresh(request)
  261. assert excinfo.match(impersonated_credentials._REFRESH_ERROR)
  262. assert not credentials.valid
  263. assert credentials.expired
  264. def test_refresh_failure_unauthorzed(self, mock_donor_credentials):
  265. credentials = self.make_credentials(lifetime=None)
  266. response_body = {
  267. "error": {
  268. "code": 403,
  269. "message": "The caller does not have permission",
  270. "status": "PERMISSION_DENIED",
  271. }
  272. }
  273. request = self.make_request(
  274. data=json.dumps(response_body), status=http_client.UNAUTHORIZED
  275. )
  276. with pytest.raises(exceptions.RefreshError) as excinfo:
  277. credentials.refresh(request)
  278. assert excinfo.match(impersonated_credentials._REFRESH_ERROR)
  279. assert not credentials.valid
  280. assert credentials.expired
  281. def test_refresh_failure(self):
  282. credentials = self.make_credentials(lifetime=None)
  283. credentials.expiry = None
  284. credentials.token = "token"
  285. id_creds = impersonated_credentials.IDTokenCredentials(
  286. credentials, target_audience="audience"
  287. )
  288. response = mock.create_autospec(transport.Response, instance=False)
  289. response.status_code = http_client.UNAUTHORIZED
  290. response.json = mock.Mock(return_value="failed to get ID token")
  291. with mock.patch(
  292. "google.auth.transport.requests.AuthorizedSession.post",
  293. return_value=response,
  294. ):
  295. with pytest.raises(exceptions.RefreshError) as excinfo:
  296. id_creds.refresh(None)
  297. assert excinfo.match("Error getting ID token")
  298. def test_refresh_failure_http_error(self, mock_donor_credentials):
  299. credentials = self.make_credentials(lifetime=None)
  300. response_body = {}
  301. request = self.make_request(
  302. data=json.dumps(response_body), status=http_client.HTTPException
  303. )
  304. with pytest.raises(exceptions.RefreshError) as excinfo:
  305. credentials.refresh(request)
  306. assert excinfo.match(impersonated_credentials._REFRESH_ERROR)
  307. assert not credentials.valid
  308. assert credentials.expired
  309. def test_expired(self):
  310. credentials = self.make_credentials(lifetime=None)
  311. assert credentials.expired
  312. def test_signer(self):
  313. credentials = self.make_credentials()
  314. assert isinstance(credentials.signer, impersonated_credentials.Credentials)
  315. def test_signer_email(self):
  316. credentials = self.make_credentials(target_principal=self.TARGET_PRINCIPAL)
  317. assert credentials.signer_email == self.TARGET_PRINCIPAL
  318. def test_service_account_email(self):
  319. credentials = self.make_credentials(target_principal=self.TARGET_PRINCIPAL)
  320. assert credentials.service_account_email == self.TARGET_PRINCIPAL
  321. def test_sign_bytes(self, mock_donor_credentials, mock_authorizedsession_sign):
  322. credentials = self.make_credentials(lifetime=None)
  323. token = "token"
  324. expire_time = (
  325. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  326. ).isoformat("T") + "Z"
  327. token_response_body = {"accessToken": token, "expireTime": expire_time}
  328. response = mock.create_autospec(transport.Response, instance=False)
  329. response.status = http_client.OK
  330. response.data = _helpers.to_bytes(json.dumps(token_response_body))
  331. request = mock.create_autospec(transport.Request, instance=False)
  332. request.return_value = response
  333. credentials.refresh(request)
  334. assert credentials.valid
  335. assert not credentials.expired
  336. signature = credentials.sign_bytes(b"signed bytes")
  337. assert signature == b"signature"
  338. def test_sign_bytes_failure(self):
  339. credentials = self.make_credentials(lifetime=None)
  340. with mock.patch(
  341. "google.auth.transport.requests.AuthorizedSession.request", autospec=True
  342. ) as auth_session:
  343. data = {"error": {"code": 403, "message": "unauthorized"}}
  344. auth_session.return_value = MockResponse(data, http_client.FORBIDDEN)
  345. with pytest.raises(exceptions.TransportError) as excinfo:
  346. credentials.sign_bytes(b"foo")
  347. assert excinfo.match("'code': 403")
  348. def test_with_quota_project(self):
  349. credentials = self.make_credentials()
  350. quota_project_creds = credentials.with_quota_project("project-foo")
  351. assert quota_project_creds._quota_project_id == "project-foo"
  352. @pytest.mark.parametrize("use_data_bytes", [True, False])
  353. def test_with_quota_project_iam_endpoint_override(
  354. self, use_data_bytes, mock_donor_credentials
  355. ):
  356. credentials = self.make_credentials(
  357. lifetime=None, iam_endpoint_override=self.IAM_ENDPOINT_OVERRIDE
  358. )
  359. token = "token"
  360. # iam_endpoint_override should be copied to created credentials.
  361. quota_project_creds = credentials.with_quota_project("project-foo")
  362. expire_time = (
  363. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  364. ).isoformat("T") + "Z"
  365. response_body = {"accessToken": token, "expireTime": expire_time}
  366. request = self.make_request(
  367. data=json.dumps(response_body),
  368. status=http_client.OK,
  369. use_data_bytes=use_data_bytes,
  370. )
  371. quota_project_creds.refresh(request)
  372. assert quota_project_creds.valid
  373. assert not quota_project_creds.expired
  374. # Confirm override endpoint used.
  375. request_kwargs = request.call_args[1]
  376. assert request_kwargs["url"] == self.IAM_ENDPOINT_OVERRIDE
  377. def test_with_scopes(self):
  378. credentials = self.make_credentials()
  379. credentials._target_scopes = []
  380. assert credentials.requires_scopes is True
  381. credentials = credentials.with_scopes(["fake_scope1", "fake_scope2"])
  382. assert credentials.requires_scopes is False
  383. assert credentials._target_scopes == ["fake_scope1", "fake_scope2"]
  384. def test_with_scopes_provide_default_scopes(self):
  385. credentials = self.make_credentials()
  386. credentials._target_scopes = []
  387. credentials = credentials.with_scopes(
  388. ["fake_scope1"], default_scopes=["fake_scope2"]
  389. )
  390. assert credentials._target_scopes == ["fake_scope1"]
  391. def test_id_token_success(
  392. self, mock_donor_credentials, mock_authorizedsession_idtoken
  393. ):
  394. credentials = self.make_credentials(lifetime=None)
  395. token = "token"
  396. target_audience = "https://foo.bar"
  397. expire_time = (
  398. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  399. ).isoformat("T") + "Z"
  400. response_body = {"accessToken": token, "expireTime": expire_time}
  401. request = self.make_request(
  402. data=json.dumps(response_body), status=http_client.OK
  403. )
  404. credentials.refresh(request)
  405. assert credentials.valid
  406. assert not credentials.expired
  407. id_creds = impersonated_credentials.IDTokenCredentials(
  408. credentials, target_audience=target_audience
  409. )
  410. id_creds.refresh(request)
  411. assert id_creds.token == ID_TOKEN_DATA
  412. assert id_creds.expiry == datetime.datetime.utcfromtimestamp(ID_TOKEN_EXPIRY)
  413. def test_id_token_metrics(self, mock_donor_credentials):
  414. credentials = self.make_credentials(lifetime=None)
  415. credentials.token = "token"
  416. credentials.expiry = None
  417. target_audience = "https://foo.bar"
  418. id_creds = impersonated_credentials.IDTokenCredentials(
  419. credentials, target_audience=target_audience
  420. )
  421. with mock.patch(
  422. "google.auth.metrics.token_request_id_token_impersonate",
  423. return_value=ID_TOKEN_REQUEST_METRICS_HEADER_VALUE,
  424. ):
  425. with mock.patch(
  426. "google.auth.transport.requests.AuthorizedSession.post", autospec=True
  427. ) as mock_post:
  428. data = {"token": ID_TOKEN_DATA}
  429. mock_post.return_value = MockResponse(data, http_client.OK)
  430. id_creds.refresh(None)
  431. assert id_creds.token == ID_TOKEN_DATA
  432. assert id_creds.expiry == datetime.datetime.utcfromtimestamp(
  433. ID_TOKEN_EXPIRY
  434. )
  435. assert (
  436. mock_post.call_args.kwargs["headers"]["x-goog-api-client"]
  437. == ID_TOKEN_REQUEST_METRICS_HEADER_VALUE
  438. )
  439. def test_id_token_from_credential(
  440. self, mock_donor_credentials, mock_authorizedsession_idtoken
  441. ):
  442. credentials = self.make_credentials(lifetime=None)
  443. token = "token"
  444. target_audience = "https://foo.bar"
  445. expire_time = (
  446. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  447. ).isoformat("T") + "Z"
  448. response_body = {"accessToken": token, "expireTime": expire_time}
  449. request = self.make_request(
  450. data=json.dumps(response_body), status=http_client.OK
  451. )
  452. credentials.refresh(request)
  453. assert credentials.valid
  454. assert not credentials.expired
  455. new_credentials = self.make_credentials(lifetime=None)
  456. id_creds = impersonated_credentials.IDTokenCredentials(
  457. credentials, target_audience=target_audience, include_email=True
  458. )
  459. id_creds = id_creds.from_credentials(target_credentials=new_credentials)
  460. id_creds.refresh(request)
  461. assert id_creds.token == ID_TOKEN_DATA
  462. assert id_creds._include_email is True
  463. assert id_creds._target_credentials is new_credentials
  464. def test_id_token_with_target_audience(
  465. self, mock_donor_credentials, mock_authorizedsession_idtoken
  466. ):
  467. credentials = self.make_credentials(lifetime=None)
  468. token = "token"
  469. target_audience = "https://foo.bar"
  470. expire_time = (
  471. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  472. ).isoformat("T") + "Z"
  473. response_body = {"accessToken": token, "expireTime": expire_time}
  474. request = self.make_request(
  475. data=json.dumps(response_body), status=http_client.OK
  476. )
  477. credentials.refresh(request)
  478. assert credentials.valid
  479. assert not credentials.expired
  480. id_creds = impersonated_credentials.IDTokenCredentials(
  481. credentials, include_email=True
  482. )
  483. id_creds = id_creds.with_target_audience(target_audience=target_audience)
  484. id_creds.refresh(request)
  485. assert id_creds.token == ID_TOKEN_DATA
  486. assert id_creds.expiry == datetime.datetime.utcfromtimestamp(ID_TOKEN_EXPIRY)
  487. assert id_creds._include_email is True
  488. def test_id_token_invalid_cred(
  489. self, mock_donor_credentials, mock_authorizedsession_idtoken
  490. ):
  491. credentials = None
  492. with pytest.raises(exceptions.GoogleAuthError) as excinfo:
  493. impersonated_credentials.IDTokenCredentials(credentials)
  494. assert excinfo.match("Provided Credential must be" " impersonated_credentials")
  495. def test_id_token_with_include_email(
  496. self, mock_donor_credentials, mock_authorizedsession_idtoken
  497. ):
  498. credentials = self.make_credentials(lifetime=None)
  499. token = "token"
  500. target_audience = "https://foo.bar"
  501. expire_time = (
  502. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  503. ).isoformat("T") + "Z"
  504. response_body = {"accessToken": token, "expireTime": expire_time}
  505. request = self.make_request(
  506. data=json.dumps(response_body), status=http_client.OK
  507. )
  508. credentials.refresh(request)
  509. assert credentials.valid
  510. assert not credentials.expired
  511. id_creds = impersonated_credentials.IDTokenCredentials(
  512. credentials, target_audience=target_audience
  513. )
  514. id_creds = id_creds.with_include_email(True)
  515. id_creds.refresh(request)
  516. assert id_creds.token == ID_TOKEN_DATA
  517. def test_id_token_with_quota_project(
  518. self, mock_donor_credentials, mock_authorizedsession_idtoken
  519. ):
  520. credentials = self.make_credentials(lifetime=None)
  521. token = "token"
  522. target_audience = "https://foo.bar"
  523. expire_time = (
  524. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  525. ).isoformat("T") + "Z"
  526. response_body = {"accessToken": token, "expireTime": expire_time}
  527. request = self.make_request(
  528. data=json.dumps(response_body), status=http_client.OK
  529. )
  530. credentials.refresh(request)
  531. assert credentials.valid
  532. assert not credentials.expired
  533. id_creds = impersonated_credentials.IDTokenCredentials(
  534. credentials, target_audience=target_audience
  535. )
  536. id_creds = id_creds.with_quota_project("project-foo")
  537. id_creds.refresh(request)
  538. assert id_creds.quota_project_id == "project-foo"