test_impersonated_credentials.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 json
  16. import os
  17. import mock
  18. import pytest
  19. from six.moves import http_client
  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
  29. DATA_DIR = os.path.join(yatest.common.test_source_path(), "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, "r") 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. @pytest.fixture
  47. def mock_donor_credentials():
  48. with mock.patch("google.oauth2._client.jwt_grant", autospec=True) as grant:
  49. grant.return_value = (
  50. "source token",
  51. _helpers.utcnow() + datetime.timedelta(seconds=500),
  52. {},
  53. )
  54. yield grant
  55. class MockResponse:
  56. def __init__(self, json_data, status_code):
  57. self.json_data = json_data
  58. self.status_code = status_code
  59. def json(self):
  60. return self.json_data
  61. @pytest.fixture
  62. def mock_authorizedsession_sign():
  63. with mock.patch(
  64. "google.auth.transport.requests.AuthorizedSession.request", autospec=True
  65. ) as auth_session:
  66. data = {"keyId": "1", "signedBlob": "c2lnbmF0dXJl"}
  67. auth_session.return_value = MockResponse(data, http_client.OK)
  68. yield auth_session
  69. @pytest.fixture
  70. def mock_authorizedsession_idtoken():
  71. with mock.patch(
  72. "google.auth.transport.requests.AuthorizedSession.request", autospec=True
  73. ) as auth_session:
  74. data = {"token": ID_TOKEN_DATA}
  75. auth_session.return_value = MockResponse(data, http_client.OK)
  76. yield auth_session
  77. class TestImpersonatedCredentials(object):
  78. SERVICE_ACCOUNT_EMAIL = "service-account@example.com"
  79. TARGET_PRINCIPAL = "impersonated@project.iam.gserviceaccount.com"
  80. TARGET_SCOPES = ["https://www.googleapis.com/auth/devstorage.read_only"]
  81. DELEGATES = []
  82. LIFETIME = 3600
  83. SOURCE_CREDENTIALS = service_account.Credentials(
  84. SIGNER, SERVICE_ACCOUNT_EMAIL, TOKEN_URI
  85. )
  86. USER_SOURCE_CREDENTIALS = credentials.Credentials(token="ABCDE")
  87. IAM_ENDPOINT_OVERRIDE = (
  88. "https://us-east1-iamcredentials.googleapis.com/v1/projects/-"
  89. + "/serviceAccounts/{}:generateAccessToken".format(SERVICE_ACCOUNT_EMAIL)
  90. )
  91. def make_credentials(
  92. self,
  93. source_credentials=SOURCE_CREDENTIALS,
  94. lifetime=LIFETIME,
  95. target_principal=TARGET_PRINCIPAL,
  96. iam_endpoint_override=None,
  97. ):
  98. return Credentials(
  99. source_credentials=source_credentials,
  100. target_principal=target_principal,
  101. target_scopes=self.TARGET_SCOPES,
  102. delegates=self.DELEGATES,
  103. lifetime=lifetime,
  104. iam_endpoint_override=iam_endpoint_override,
  105. )
  106. def test_make_from_user_credentials(self):
  107. credentials = self.make_credentials(
  108. source_credentials=self.USER_SOURCE_CREDENTIALS
  109. )
  110. assert not credentials.valid
  111. assert credentials.expired
  112. def test_default_state(self):
  113. credentials = self.make_credentials()
  114. assert not credentials.valid
  115. assert credentials.expired
  116. def make_request(
  117. self,
  118. data,
  119. status=http_client.OK,
  120. headers=None,
  121. side_effect=None,
  122. use_data_bytes=True,
  123. ):
  124. response = mock.create_autospec(transport.Response, instance=False)
  125. response.status = status
  126. response.data = _helpers.to_bytes(data) if use_data_bytes else data
  127. response.headers = headers or {}
  128. request = mock.create_autospec(transport.Request, instance=False)
  129. request.side_effect = side_effect
  130. request.return_value = response
  131. return request
  132. @pytest.mark.parametrize("use_data_bytes", [True, False])
  133. def test_refresh_success(self, use_data_bytes, mock_donor_credentials):
  134. credentials = self.make_credentials(lifetime=None)
  135. token = "token"
  136. expire_time = (
  137. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  138. ).isoformat("T") + "Z"
  139. response_body = {"accessToken": token, "expireTime": expire_time}
  140. request = self.make_request(
  141. data=json.dumps(response_body),
  142. status=http_client.OK,
  143. use_data_bytes=use_data_bytes,
  144. )
  145. credentials.refresh(request)
  146. assert credentials.valid
  147. assert not credentials.expired
  148. @pytest.mark.parametrize("use_data_bytes", [True, False])
  149. def test_refresh_success_iam_endpoint_override(
  150. self, use_data_bytes, mock_donor_credentials
  151. ):
  152. credentials = self.make_credentials(
  153. lifetime=None, iam_endpoint_override=self.IAM_ENDPOINT_OVERRIDE
  154. )
  155. token = "token"
  156. expire_time = (
  157. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  158. ).isoformat("T") + "Z"
  159. response_body = {"accessToken": token, "expireTime": expire_time}
  160. request = self.make_request(
  161. data=json.dumps(response_body),
  162. status=http_client.OK,
  163. use_data_bytes=use_data_bytes,
  164. )
  165. credentials.refresh(request)
  166. assert credentials.valid
  167. assert not credentials.expired
  168. # Confirm override endpoint used.
  169. request_kwargs = request.call_args[1]
  170. assert request_kwargs["url"] == self.IAM_ENDPOINT_OVERRIDE
  171. @pytest.mark.parametrize("time_skew", [100, -100])
  172. def test_refresh_source_credentials(self, time_skew):
  173. credentials = self.make_credentials(lifetime=None)
  174. # Source credentials is refreshed only if it is expired within
  175. # _helpers.CLOCK_SKEW from now. We add a time_skew to the expiry, so
  176. # source credentials is refreshed only if time_skew <= 0.
  177. credentials._source_credentials.expiry = (
  178. _helpers.utcnow()
  179. + _helpers.CLOCK_SKEW
  180. + datetime.timedelta(seconds=time_skew)
  181. )
  182. credentials._source_credentials.token = "Token"
  183. with mock.patch(
  184. "google.oauth2.service_account.Credentials.refresh", autospec=True
  185. ) as source_cred_refresh:
  186. expire_time = (
  187. _helpers.utcnow().replace(microsecond=0)
  188. + datetime.timedelta(seconds=500)
  189. ).isoformat("T") + "Z"
  190. response_body = {"accessToken": "token", "expireTime": expire_time}
  191. request = self.make_request(
  192. data=json.dumps(response_body), status=http_client.OK
  193. )
  194. credentials.refresh(request)
  195. assert credentials.valid
  196. assert not credentials.expired
  197. # Source credentials is refreshed only if it is expired within
  198. # _helpers.CLOCK_SKEW
  199. if time_skew > 0:
  200. source_cred_refresh.assert_not_called()
  201. else:
  202. source_cred_refresh.assert_called_once()
  203. def test_refresh_failure_malformed_expire_time(self, mock_donor_credentials):
  204. credentials = self.make_credentials(lifetime=None)
  205. token = "token"
  206. expire_time = (_helpers.utcnow() + datetime.timedelta(seconds=500)).isoformat(
  207. "T"
  208. )
  209. response_body = {"accessToken": token, "expireTime": expire_time}
  210. request = self.make_request(
  211. data=json.dumps(response_body), status=http_client.OK
  212. )
  213. with pytest.raises(exceptions.RefreshError) as excinfo:
  214. credentials.refresh(request)
  215. assert excinfo.match(impersonated_credentials._REFRESH_ERROR)
  216. assert not credentials.valid
  217. assert credentials.expired
  218. def test_refresh_failure_unauthorzed(self, mock_donor_credentials):
  219. credentials = self.make_credentials(lifetime=None)
  220. response_body = {
  221. "error": {
  222. "code": 403,
  223. "message": "The caller does not have permission",
  224. "status": "PERMISSION_DENIED",
  225. }
  226. }
  227. request = self.make_request(
  228. data=json.dumps(response_body), status=http_client.UNAUTHORIZED
  229. )
  230. with pytest.raises(exceptions.RefreshError) as excinfo:
  231. credentials.refresh(request)
  232. assert excinfo.match(impersonated_credentials._REFRESH_ERROR)
  233. assert not credentials.valid
  234. assert credentials.expired
  235. def test_refresh_failure_http_error(self, mock_donor_credentials):
  236. credentials = self.make_credentials(lifetime=None)
  237. response_body = {}
  238. request = self.make_request(
  239. data=json.dumps(response_body), status=http_client.HTTPException
  240. )
  241. with pytest.raises(exceptions.RefreshError) as excinfo:
  242. credentials.refresh(request)
  243. assert excinfo.match(impersonated_credentials._REFRESH_ERROR)
  244. assert not credentials.valid
  245. assert credentials.expired
  246. def test_expired(self):
  247. credentials = self.make_credentials(lifetime=None)
  248. assert credentials.expired
  249. def test_signer(self):
  250. credentials = self.make_credentials()
  251. assert isinstance(credentials.signer, impersonated_credentials.Credentials)
  252. def test_signer_email(self):
  253. credentials = self.make_credentials(target_principal=self.TARGET_PRINCIPAL)
  254. assert credentials.signer_email == self.TARGET_PRINCIPAL
  255. def test_service_account_email(self):
  256. credentials = self.make_credentials(target_principal=self.TARGET_PRINCIPAL)
  257. assert credentials.service_account_email == self.TARGET_PRINCIPAL
  258. def test_sign_bytes(self, mock_donor_credentials, mock_authorizedsession_sign):
  259. credentials = self.make_credentials(lifetime=None)
  260. token = "token"
  261. expire_time = (
  262. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  263. ).isoformat("T") + "Z"
  264. token_response_body = {"accessToken": token, "expireTime": expire_time}
  265. response = mock.create_autospec(transport.Response, instance=False)
  266. response.status = http_client.OK
  267. response.data = _helpers.to_bytes(json.dumps(token_response_body))
  268. request = mock.create_autospec(transport.Request, instance=False)
  269. request.return_value = response
  270. credentials.refresh(request)
  271. assert credentials.valid
  272. assert not credentials.expired
  273. signature = credentials.sign_bytes(b"signed bytes")
  274. assert signature == b"signature"
  275. def test_with_quota_project(self):
  276. credentials = self.make_credentials()
  277. quota_project_creds = credentials.with_quota_project("project-foo")
  278. assert quota_project_creds._quota_project_id == "project-foo"
  279. @pytest.mark.parametrize("use_data_bytes", [True, False])
  280. def test_with_quota_project_iam_endpoint_override(
  281. self, use_data_bytes, mock_donor_credentials
  282. ):
  283. credentials = self.make_credentials(
  284. lifetime=None, iam_endpoint_override=self.IAM_ENDPOINT_OVERRIDE
  285. )
  286. token = "token"
  287. # iam_endpoint_override should be copied to created credentials.
  288. quota_project_creds = credentials.with_quota_project("project-foo")
  289. expire_time = (
  290. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  291. ).isoformat("T") + "Z"
  292. response_body = {"accessToken": token, "expireTime": expire_time}
  293. request = self.make_request(
  294. data=json.dumps(response_body),
  295. status=http_client.OK,
  296. use_data_bytes=use_data_bytes,
  297. )
  298. quota_project_creds.refresh(request)
  299. assert quota_project_creds.valid
  300. assert not quota_project_creds.expired
  301. # Confirm override endpoint used.
  302. request_kwargs = request.call_args[1]
  303. assert request_kwargs["url"] == self.IAM_ENDPOINT_OVERRIDE
  304. def test_id_token_success(
  305. self, mock_donor_credentials, mock_authorizedsession_idtoken
  306. ):
  307. credentials = self.make_credentials(lifetime=None)
  308. token = "token"
  309. target_audience = "https://foo.bar"
  310. expire_time = (
  311. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  312. ).isoformat("T") + "Z"
  313. response_body = {"accessToken": token, "expireTime": expire_time}
  314. request = self.make_request(
  315. data=json.dumps(response_body), status=http_client.OK
  316. )
  317. credentials.refresh(request)
  318. assert credentials.valid
  319. assert not credentials.expired
  320. id_creds = impersonated_credentials.IDTokenCredentials(
  321. credentials, target_audience=target_audience
  322. )
  323. id_creds.refresh(request)
  324. assert id_creds.token == ID_TOKEN_DATA
  325. assert id_creds.expiry == datetime.datetime.fromtimestamp(ID_TOKEN_EXPIRY)
  326. def test_id_token_from_credential(
  327. self, mock_donor_credentials, mock_authorizedsession_idtoken
  328. ):
  329. credentials = self.make_credentials(lifetime=None)
  330. token = "token"
  331. target_audience = "https://foo.bar"
  332. expire_time = (
  333. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  334. ).isoformat("T") + "Z"
  335. response_body = {"accessToken": token, "expireTime": expire_time}
  336. request = self.make_request(
  337. data=json.dumps(response_body), status=http_client.OK
  338. )
  339. credentials.refresh(request)
  340. assert credentials.valid
  341. assert not credentials.expired
  342. id_creds = impersonated_credentials.IDTokenCredentials(
  343. credentials, target_audience=target_audience, include_email=True
  344. )
  345. id_creds = id_creds.from_credentials(target_credentials=credentials)
  346. id_creds.refresh(request)
  347. assert id_creds.token == ID_TOKEN_DATA
  348. assert id_creds._include_email is True
  349. def test_id_token_with_target_audience(
  350. self, mock_donor_credentials, mock_authorizedsession_idtoken
  351. ):
  352. credentials = self.make_credentials(lifetime=None)
  353. token = "token"
  354. target_audience = "https://foo.bar"
  355. expire_time = (
  356. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  357. ).isoformat("T") + "Z"
  358. response_body = {"accessToken": token, "expireTime": expire_time}
  359. request = self.make_request(
  360. data=json.dumps(response_body), status=http_client.OK
  361. )
  362. credentials.refresh(request)
  363. assert credentials.valid
  364. assert not credentials.expired
  365. id_creds = impersonated_credentials.IDTokenCredentials(
  366. credentials, include_email=True
  367. )
  368. id_creds = id_creds.with_target_audience(target_audience=target_audience)
  369. id_creds.refresh(request)
  370. assert id_creds.token == ID_TOKEN_DATA
  371. assert id_creds.expiry == datetime.datetime.fromtimestamp(ID_TOKEN_EXPIRY)
  372. assert id_creds._include_email is True
  373. def test_id_token_invalid_cred(
  374. self, mock_donor_credentials, mock_authorizedsession_idtoken
  375. ):
  376. credentials = None
  377. with pytest.raises(exceptions.GoogleAuthError) as excinfo:
  378. impersonated_credentials.IDTokenCredentials(credentials)
  379. assert excinfo.match("Provided Credential must be" " impersonated_credentials")
  380. def test_id_token_with_include_email(
  381. self, mock_donor_credentials, mock_authorizedsession_idtoken
  382. ):
  383. credentials = self.make_credentials(lifetime=None)
  384. token = "token"
  385. target_audience = "https://foo.bar"
  386. expire_time = (
  387. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  388. ).isoformat("T") + "Z"
  389. response_body = {"accessToken": token, "expireTime": expire_time}
  390. request = self.make_request(
  391. data=json.dumps(response_body), status=http_client.OK
  392. )
  393. credentials.refresh(request)
  394. assert credentials.valid
  395. assert not credentials.expired
  396. id_creds = impersonated_credentials.IDTokenCredentials(
  397. credentials, target_audience=target_audience
  398. )
  399. id_creds = id_creds.with_include_email(True)
  400. id_creds.refresh(request)
  401. assert id_creds.token == ID_TOKEN_DATA
  402. def test_id_token_with_quota_project(
  403. self, mock_donor_credentials, mock_authorizedsession_idtoken
  404. ):
  405. credentials = self.make_credentials(lifetime=None)
  406. token = "token"
  407. target_audience = "https://foo.bar"
  408. expire_time = (
  409. _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)
  410. ).isoformat("T") + "Z"
  411. response_body = {"accessToken": token, "expireTime": expire_time}
  412. request = self.make_request(
  413. data=json.dumps(response_body), status=http_client.OK
  414. )
  415. credentials.refresh(request)
  416. assert credentials.valid
  417. assert not credentials.expired
  418. id_creds = impersonated_credentials.IDTokenCredentials(
  419. credentials, target_audience=target_audience
  420. )
  421. id_creds = id_creds.with_quota_project("project-foo")
  422. id_creds.refresh(request)
  423. assert id_creds.quota_project_id == "project-foo"