test_service_account.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. # Copyright 2016 Google LLC
  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 # type: ignore
  19. from google.auth import _helpers
  20. from google.auth import crypt
  21. from google.auth import exceptions
  22. from google.auth import jwt
  23. from google.auth import transport
  24. from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN
  25. from google.oauth2 import service_account
  26. import yatest.common as yc
  27. DATA_DIR = os.path.join(os.path.dirname(yc.source_path(__file__)), "..", "data")
  28. with open(os.path.join(DATA_DIR, "privatekey.pem"), "rb") as fh:
  29. PRIVATE_KEY_BYTES = fh.read()
  30. with open(os.path.join(DATA_DIR, "public_cert.pem"), "rb") as fh:
  31. PUBLIC_CERT_BYTES = fh.read()
  32. with open(os.path.join(DATA_DIR, "other_cert.pem"), "rb") as fh:
  33. OTHER_CERT_BYTES = fh.read()
  34. SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, "service_account.json")
  35. SERVICE_ACCOUNT_NON_GDU_JSON_FILE = os.path.join(
  36. DATA_DIR, "service_account_non_gdu.json"
  37. )
  38. FAKE_UNIVERSE_DOMAIN = "universe.foo"
  39. with open(SERVICE_ACCOUNT_JSON_FILE, "rb") as fh:
  40. SERVICE_ACCOUNT_INFO = json.load(fh)
  41. with open(SERVICE_ACCOUNT_NON_GDU_JSON_FILE, "rb") as fh:
  42. SERVICE_ACCOUNT_INFO_NON_GDU = json.load(fh)
  43. SIGNER = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES, "1")
  44. class TestCredentials(object):
  45. SERVICE_ACCOUNT_EMAIL = "service-account@example.com"
  46. TOKEN_URI = "https://example.com/oauth2/token"
  47. @classmethod
  48. def make_credentials(cls, universe_domain=DEFAULT_UNIVERSE_DOMAIN):
  49. return service_account.Credentials(
  50. SIGNER,
  51. cls.SERVICE_ACCOUNT_EMAIL,
  52. cls.TOKEN_URI,
  53. universe_domain=universe_domain,
  54. )
  55. def test_constructor_no_universe_domain(self):
  56. credentials = service_account.Credentials(
  57. SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, universe_domain=None
  58. )
  59. assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN
  60. def test_from_service_account_info(self):
  61. credentials = service_account.Credentials.from_service_account_info(
  62. SERVICE_ACCOUNT_INFO
  63. )
  64. assert credentials._signer.key_id == SERVICE_ACCOUNT_INFO["private_key_id"]
  65. assert credentials.service_account_email == SERVICE_ACCOUNT_INFO["client_email"]
  66. assert credentials._token_uri == SERVICE_ACCOUNT_INFO["token_uri"]
  67. assert credentials._universe_domain == DEFAULT_UNIVERSE_DOMAIN
  68. assert not credentials._always_use_jwt_access
  69. def test_from_service_account_info_non_gdu(self):
  70. credentials = service_account.Credentials.from_service_account_info(
  71. SERVICE_ACCOUNT_INFO_NON_GDU
  72. )
  73. assert credentials.universe_domain == FAKE_UNIVERSE_DOMAIN
  74. assert credentials._always_use_jwt_access
  75. def test_from_service_account_info_args(self):
  76. info = SERVICE_ACCOUNT_INFO.copy()
  77. scopes = ["email", "profile"]
  78. subject = "subject"
  79. additional_claims = {"meta": "data"}
  80. credentials = service_account.Credentials.from_service_account_info(
  81. info, scopes=scopes, subject=subject, additional_claims=additional_claims
  82. )
  83. assert credentials.service_account_email == info["client_email"]
  84. assert credentials.project_id == info["project_id"]
  85. assert credentials._signer.key_id == info["private_key_id"]
  86. assert credentials._token_uri == info["token_uri"]
  87. assert credentials._scopes == scopes
  88. assert credentials._subject == subject
  89. assert credentials._additional_claims == additional_claims
  90. assert not credentials._always_use_jwt_access
  91. def test_from_service_account_file(self):
  92. info = SERVICE_ACCOUNT_INFO.copy()
  93. credentials = service_account.Credentials.from_service_account_file(
  94. SERVICE_ACCOUNT_JSON_FILE
  95. )
  96. assert credentials.service_account_email == info["client_email"]
  97. assert credentials.project_id == info["project_id"]
  98. assert credentials._signer.key_id == info["private_key_id"]
  99. assert credentials._token_uri == info["token_uri"]
  100. def test_from_service_account_file_non_gdu(self):
  101. info = SERVICE_ACCOUNT_INFO_NON_GDU.copy()
  102. credentials = service_account.Credentials.from_service_account_file(
  103. SERVICE_ACCOUNT_NON_GDU_JSON_FILE
  104. )
  105. assert credentials.service_account_email == info["client_email"]
  106. assert credentials.project_id == info["project_id"]
  107. assert credentials._signer.key_id == info["private_key_id"]
  108. assert credentials._token_uri == info["token_uri"]
  109. assert credentials._universe_domain == FAKE_UNIVERSE_DOMAIN
  110. assert credentials._always_use_jwt_access
  111. def test_from_service_account_file_args(self):
  112. info = SERVICE_ACCOUNT_INFO.copy()
  113. scopes = ["email", "profile"]
  114. subject = "subject"
  115. additional_claims = {"meta": "data"}
  116. credentials = service_account.Credentials.from_service_account_file(
  117. SERVICE_ACCOUNT_JSON_FILE,
  118. subject=subject,
  119. scopes=scopes,
  120. additional_claims=additional_claims,
  121. )
  122. assert credentials.service_account_email == info["client_email"]
  123. assert credentials.project_id == info["project_id"]
  124. assert credentials._signer.key_id == info["private_key_id"]
  125. assert credentials._token_uri == info["token_uri"]
  126. assert credentials._scopes == scopes
  127. assert credentials._subject == subject
  128. assert credentials._additional_claims == additional_claims
  129. def test_default_state(self):
  130. credentials = self.make_credentials()
  131. assert not credentials.valid
  132. # Expiration hasn't been set yet
  133. assert not credentials.expired
  134. # Scopes haven't been specified yet
  135. assert credentials.requires_scopes
  136. def test_sign_bytes(self):
  137. credentials = self.make_credentials()
  138. to_sign = b"123"
  139. signature = credentials.sign_bytes(to_sign)
  140. assert crypt.verify_signature(to_sign, signature, PUBLIC_CERT_BYTES)
  141. def test_signer(self):
  142. credentials = self.make_credentials()
  143. assert isinstance(credentials.signer, crypt.Signer)
  144. def test_signer_email(self):
  145. credentials = self.make_credentials()
  146. assert credentials.signer_email == self.SERVICE_ACCOUNT_EMAIL
  147. def test_create_scoped(self):
  148. credentials = self.make_credentials()
  149. scopes = ["email", "profile"]
  150. credentials = credentials.with_scopes(scopes)
  151. assert credentials._scopes == scopes
  152. def test_with_claims(self):
  153. credentials = self.make_credentials()
  154. new_credentials = credentials.with_claims({"meep": "moop"})
  155. assert new_credentials._additional_claims == {"meep": "moop"}
  156. def test_with_quota_project(self):
  157. credentials = self.make_credentials()
  158. new_credentials = credentials.with_quota_project("new-project-456")
  159. assert new_credentials.quota_project_id == "new-project-456"
  160. hdrs = {}
  161. new_credentials.apply(hdrs, token="tok")
  162. assert "x-goog-user-project" in hdrs
  163. def test_with_token_uri(self):
  164. credentials = self.make_credentials()
  165. new_token_uri = "https://example2.com/oauth2/token"
  166. assert credentials._token_uri == self.TOKEN_URI
  167. creds_with_new_token_uri = credentials.with_token_uri(new_token_uri)
  168. assert creds_with_new_token_uri._token_uri == new_token_uri
  169. def test_with_universe_domain(self):
  170. credentials = self.make_credentials()
  171. new_credentials = credentials.with_universe_domain("dummy_universe.com")
  172. assert new_credentials.universe_domain == "dummy_universe.com"
  173. assert new_credentials._always_use_jwt_access
  174. new_credentials = credentials.with_universe_domain("googleapis.com")
  175. assert new_credentials.universe_domain == "googleapis.com"
  176. assert not new_credentials._always_use_jwt_access
  177. def test__with_always_use_jwt_access(self):
  178. credentials = self.make_credentials()
  179. assert not credentials._always_use_jwt_access
  180. new_credentials = credentials.with_always_use_jwt_access(True)
  181. assert new_credentials._always_use_jwt_access
  182. def test__with_always_use_jwt_access_non_default_universe_domain(self):
  183. credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN)
  184. with pytest.raises(exceptions.InvalidValue) as excinfo:
  185. credentials.with_always_use_jwt_access(False)
  186. assert excinfo.match(
  187. "always_use_jwt_access should be True for non-default universe domain"
  188. )
  189. def test__make_authorization_grant_assertion(self):
  190. credentials = self.make_credentials()
  191. token = credentials._make_authorization_grant_assertion()
  192. payload = jwt.decode(token, PUBLIC_CERT_BYTES)
  193. assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL
  194. assert payload["aud"] == service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT
  195. def test__make_authorization_grant_assertion_scoped(self):
  196. credentials = self.make_credentials()
  197. scopes = ["email", "profile"]
  198. credentials = credentials.with_scopes(scopes)
  199. token = credentials._make_authorization_grant_assertion()
  200. payload = jwt.decode(token, PUBLIC_CERT_BYTES)
  201. assert payload["scope"] == "email profile"
  202. def test__make_authorization_grant_assertion_subject(self):
  203. credentials = self.make_credentials()
  204. subject = "user@example.com"
  205. credentials = credentials.with_subject(subject)
  206. token = credentials._make_authorization_grant_assertion()
  207. payload = jwt.decode(token, PUBLIC_CERT_BYTES)
  208. assert payload["sub"] == subject
  209. def test_apply_with_quota_project_id(self):
  210. credentials = service_account.Credentials(
  211. SIGNER,
  212. self.SERVICE_ACCOUNT_EMAIL,
  213. self.TOKEN_URI,
  214. quota_project_id="quota-project-123",
  215. )
  216. headers = {}
  217. credentials.apply(headers, token="token")
  218. assert headers["x-goog-user-project"] == "quota-project-123"
  219. assert "token" in headers["authorization"]
  220. def test_apply_with_no_quota_project_id(self):
  221. credentials = service_account.Credentials(
  222. SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI
  223. )
  224. headers = {}
  225. credentials.apply(headers, token="token")
  226. assert "x-goog-user-project" not in headers
  227. assert "token" in headers["authorization"]
  228. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  229. def test__create_self_signed_jwt(self, jwt):
  230. credentials = service_account.Credentials(
  231. SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI
  232. )
  233. audience = "https://pubsub.googleapis.com"
  234. credentials._create_self_signed_jwt(audience)
  235. jwt.from_signing_credentials.assert_called_once_with(credentials, audience)
  236. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  237. def test__create_self_signed_jwt_with_user_scopes(self, jwt):
  238. credentials = service_account.Credentials(
  239. SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, scopes=["foo"]
  240. )
  241. audience = "https://pubsub.googleapis.com"
  242. credentials._create_self_signed_jwt(audience)
  243. # JWT should not be created if there are user-defined scopes
  244. jwt.from_signing_credentials.assert_not_called()
  245. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  246. def test__create_self_signed_jwt_always_use_jwt_access_with_audience(self, jwt):
  247. credentials = service_account.Credentials(
  248. SIGNER,
  249. self.SERVICE_ACCOUNT_EMAIL,
  250. self.TOKEN_URI,
  251. default_scopes=["bar", "foo"],
  252. always_use_jwt_access=True,
  253. )
  254. audience = "https://pubsub.googleapis.com"
  255. credentials._create_self_signed_jwt(audience)
  256. jwt.from_signing_credentials.assert_called_once_with(credentials, audience)
  257. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  258. def test__create_self_signed_jwt_always_use_jwt_access_with_audience_similar_jwt_is_reused(
  259. self, jwt
  260. ):
  261. credentials = service_account.Credentials(
  262. SIGNER,
  263. self.SERVICE_ACCOUNT_EMAIL,
  264. self.TOKEN_URI,
  265. default_scopes=["bar", "foo"],
  266. always_use_jwt_access=True,
  267. )
  268. audience = "https://pubsub.googleapis.com"
  269. credentials._create_self_signed_jwt(audience)
  270. credentials._jwt_credentials._audience = audience
  271. credentials._create_self_signed_jwt(audience)
  272. jwt.from_signing_credentials.assert_called_once_with(credentials, audience)
  273. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  274. def test__create_self_signed_jwt_always_use_jwt_access_with_scopes(self, jwt):
  275. credentials = service_account.Credentials(
  276. SIGNER,
  277. self.SERVICE_ACCOUNT_EMAIL,
  278. self.TOKEN_URI,
  279. scopes=["bar", "foo"],
  280. always_use_jwt_access=True,
  281. )
  282. audience = "https://pubsub.googleapis.com"
  283. credentials._create_self_signed_jwt(audience)
  284. jwt.from_signing_credentials.assert_called_once_with(
  285. credentials, None, additional_claims={"scope": "bar foo"}
  286. )
  287. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  288. def test__create_self_signed_jwt_always_use_jwt_access_with_scopes_similar_jwt_is_reused(
  289. self, jwt
  290. ):
  291. credentials = service_account.Credentials(
  292. SIGNER,
  293. self.SERVICE_ACCOUNT_EMAIL,
  294. self.TOKEN_URI,
  295. scopes=["bar", "foo"],
  296. always_use_jwt_access=True,
  297. )
  298. audience = "https://pubsub.googleapis.com"
  299. credentials._create_self_signed_jwt(audience)
  300. credentials._jwt_credentials.additional_claims = {"scope": "bar foo"}
  301. credentials._create_self_signed_jwt(audience)
  302. jwt.from_signing_credentials.assert_called_once_with(
  303. credentials, None, additional_claims={"scope": "bar foo"}
  304. )
  305. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  306. def test__create_self_signed_jwt_always_use_jwt_access_with_default_scopes(
  307. self, jwt
  308. ):
  309. credentials = service_account.Credentials(
  310. SIGNER,
  311. self.SERVICE_ACCOUNT_EMAIL,
  312. self.TOKEN_URI,
  313. default_scopes=["bar", "foo"],
  314. always_use_jwt_access=True,
  315. )
  316. credentials._create_self_signed_jwt(None)
  317. jwt.from_signing_credentials.assert_called_once_with(
  318. credentials, None, additional_claims={"scope": "bar foo"}
  319. )
  320. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  321. def test__create_self_signed_jwt_always_use_jwt_access_with_default_scopes_similar_jwt_is_reused(
  322. self, jwt
  323. ):
  324. credentials = service_account.Credentials(
  325. SIGNER,
  326. self.SERVICE_ACCOUNT_EMAIL,
  327. self.TOKEN_URI,
  328. default_scopes=["bar", "foo"],
  329. always_use_jwt_access=True,
  330. )
  331. credentials._create_self_signed_jwt(None)
  332. credentials._jwt_credentials.additional_claims = {"scope": "bar foo"}
  333. credentials._create_self_signed_jwt(None)
  334. jwt.from_signing_credentials.assert_called_once_with(
  335. credentials, None, additional_claims={"scope": "bar foo"}
  336. )
  337. @mock.patch("google.auth.jwt.Credentials", instance=True, autospec=True)
  338. def test__create_self_signed_jwt_always_use_jwt_access(self, jwt):
  339. credentials = service_account.Credentials(
  340. SIGNER,
  341. self.SERVICE_ACCOUNT_EMAIL,
  342. self.TOKEN_URI,
  343. always_use_jwt_access=True,
  344. )
  345. credentials._create_self_signed_jwt(None)
  346. jwt.from_signing_credentials.assert_not_called()
  347. def test_token_usage_metrics_assertion(self):
  348. credentials = service_account.Credentials(
  349. SIGNER,
  350. self.SERVICE_ACCOUNT_EMAIL,
  351. self.TOKEN_URI,
  352. always_use_jwt_access=False,
  353. )
  354. credentials.token = "token"
  355. credentials.expiry = None
  356. headers = {}
  357. credentials.before_request(mock.Mock(), None, None, headers)
  358. assert headers["authorization"] == "Bearer token"
  359. assert headers["x-goog-api-client"] == "cred-type/sa"
  360. def test_token_usage_metrics_self_signed_jwt(self):
  361. credentials = service_account.Credentials(
  362. SIGNER,
  363. self.SERVICE_ACCOUNT_EMAIL,
  364. self.TOKEN_URI,
  365. always_use_jwt_access=True,
  366. )
  367. credentials._create_self_signed_jwt("foo.googleapis.com")
  368. credentials.token = "token"
  369. credentials.expiry = None
  370. headers = {}
  371. credentials.before_request(mock.Mock(), None, None, headers)
  372. assert headers["authorization"] == "Bearer token"
  373. assert headers["x-goog-api-client"] == "cred-type/jwt"
  374. @mock.patch("google.oauth2._client.jwt_grant", autospec=True)
  375. def test_refresh_success(self, jwt_grant):
  376. credentials = self.make_credentials()
  377. token = "token"
  378. jwt_grant.return_value = (
  379. token,
  380. _helpers.utcnow() + datetime.timedelta(seconds=500),
  381. {},
  382. )
  383. request = mock.create_autospec(transport.Request, instance=True)
  384. # Refresh credentials
  385. credentials.refresh(request)
  386. # Check jwt grant call.
  387. assert jwt_grant.called
  388. called_request, token_uri, assertion = jwt_grant.call_args[0]
  389. assert called_request == request
  390. assert token_uri == credentials._token_uri
  391. assert jwt.decode(assertion, PUBLIC_CERT_BYTES)
  392. # No further assertion done on the token, as there are separate tests
  393. # for checking the authorization grant assertion.
  394. # Check that the credentials have the token.
  395. assert credentials.token == token
  396. # Check that the credentials are valid (have a token and are not
  397. # expired)
  398. assert credentials.valid
  399. @mock.patch("google.oauth2._client.jwt_grant", autospec=True)
  400. def test_before_request_refreshes(self, jwt_grant):
  401. credentials = self.make_credentials()
  402. token = "token"
  403. jwt_grant.return_value = (
  404. token,
  405. _helpers.utcnow() + datetime.timedelta(seconds=500),
  406. None,
  407. )
  408. request = mock.create_autospec(transport.Request, instance=True)
  409. # Credentials should start as invalid
  410. assert not credentials.valid
  411. # before_request should cause a refresh
  412. credentials.before_request(request, "GET", "http://example.com?a=1#3", {})
  413. # The refresh endpoint should've been called.
  414. assert jwt_grant.called
  415. # Credentials should now be valid.
  416. assert credentials.valid
  417. @mock.patch("google.auth.jwt.Credentials._make_jwt")
  418. def test_refresh_with_jwt_credentials(self, make_jwt):
  419. credentials = self.make_credentials()
  420. credentials._create_self_signed_jwt("https://pubsub.googleapis.com")
  421. request = mock.create_autospec(transport.Request, instance=True)
  422. token = "token"
  423. expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
  424. make_jwt.return_value = (b"token", expiry)
  425. # Credentials should start as invalid
  426. assert not credentials.valid
  427. # before_request should cause a refresh
  428. credentials.before_request(request, "GET", "http://example.com?a=1#3", {})
  429. # Credentials should now be valid.
  430. assert credentials.valid
  431. # Assert make_jwt was called
  432. assert make_jwt.call_count == 1
  433. assert credentials.token == token
  434. assert credentials.expiry == expiry
  435. def test_refresh_with_jwt_credentials_token_type_check(self):
  436. credentials = self.make_credentials()
  437. credentials._create_self_signed_jwt("https://pubsub.googleapis.com")
  438. credentials.refresh(mock.Mock())
  439. # Credentials token should be a JWT string.
  440. assert isinstance(credentials.token, str)
  441. payload = jwt.decode(credentials.token, verify=False)
  442. assert payload["aud"] == "https://pubsub.googleapis.com"
  443. @mock.patch("google.oauth2._client.jwt_grant", autospec=True)
  444. @mock.patch("google.auth.jwt.Credentials.refresh", autospec=True)
  445. def test_refresh_jwt_not_used_for_domain_wide_delegation(
  446. self, self_signed_jwt_refresh, jwt_grant
  447. ):
  448. # Create a domain wide delegation credentials by setting the subject.
  449. credentials = service_account.Credentials(
  450. SIGNER,
  451. self.SERVICE_ACCOUNT_EMAIL,
  452. self.TOKEN_URI,
  453. always_use_jwt_access=True,
  454. subject="subject",
  455. )
  456. credentials._create_self_signed_jwt("https://pubsub.googleapis.com")
  457. jwt_grant.return_value = (
  458. "token",
  459. _helpers.utcnow() + datetime.timedelta(seconds=500),
  460. {},
  461. )
  462. request = mock.create_autospec(transport.Request, instance=True)
  463. # Refresh credentials
  464. credentials.refresh(request)
  465. # Make sure we are using jwt_grant and not self signed JWT refresh
  466. # method to obtain the token.
  467. assert jwt_grant.called
  468. assert not self_signed_jwt_refresh.called
  469. def test_refresh_missing_jwt_credentials(self):
  470. credentials = self.make_credentials()
  471. credentials = credentials.with_scopes(["foo", "bar"])
  472. credentials = credentials.with_always_use_jwt_access(True)
  473. assert not credentials._jwt_credentials
  474. credentials.refresh(mock.Mock())
  475. # jwt credentials should have been automatically created with scopes
  476. assert credentials._jwt_credentials is not None
  477. def test_refresh_non_gdu_domain_wide_delegation_not_supported(self):
  478. credentials = self.make_credentials(universe_domain="foo")
  479. credentials._subject = "bar@example.com"
  480. credentials._create_self_signed_jwt("https://pubsub.googleapis.com")
  481. with pytest.raises(exceptions.RefreshError) as excinfo:
  482. credentials.refresh(None)
  483. assert excinfo.match("domain wide delegation is not supported")
  484. class TestIDTokenCredentials(object):
  485. SERVICE_ACCOUNT_EMAIL = "service-account@example.com"
  486. TOKEN_URI = "https://example.com/oauth2/token"
  487. TARGET_AUDIENCE = "https://example.com"
  488. @classmethod
  489. def make_credentials(cls, universe_domain=DEFAULT_UNIVERSE_DOMAIN):
  490. return service_account.IDTokenCredentials(
  491. SIGNER,
  492. cls.SERVICE_ACCOUNT_EMAIL,
  493. cls.TOKEN_URI,
  494. cls.TARGET_AUDIENCE,
  495. universe_domain=universe_domain,
  496. )
  497. def test_constructor_no_universe_domain(self):
  498. credentials = service_account.IDTokenCredentials(
  499. SIGNER,
  500. self.SERVICE_ACCOUNT_EMAIL,
  501. self.TOKEN_URI,
  502. self.TARGET_AUDIENCE,
  503. universe_domain=None,
  504. )
  505. assert credentials._universe_domain == DEFAULT_UNIVERSE_DOMAIN
  506. def test_from_service_account_info(self):
  507. credentials = service_account.IDTokenCredentials.from_service_account_info(
  508. SERVICE_ACCOUNT_INFO, target_audience=self.TARGET_AUDIENCE
  509. )
  510. assert credentials._signer.key_id == SERVICE_ACCOUNT_INFO["private_key_id"]
  511. assert credentials.service_account_email == SERVICE_ACCOUNT_INFO["client_email"]
  512. assert credentials._token_uri == SERVICE_ACCOUNT_INFO["token_uri"]
  513. assert credentials._target_audience == self.TARGET_AUDIENCE
  514. assert not credentials._use_iam_endpoint
  515. def test_from_service_account_info_non_gdu(self):
  516. credentials = service_account.IDTokenCredentials.from_service_account_info(
  517. SERVICE_ACCOUNT_INFO_NON_GDU, target_audience=self.TARGET_AUDIENCE
  518. )
  519. assert (
  520. credentials._signer.key_id == SERVICE_ACCOUNT_INFO_NON_GDU["private_key_id"]
  521. )
  522. assert (
  523. credentials.service_account_email
  524. == SERVICE_ACCOUNT_INFO_NON_GDU["client_email"]
  525. )
  526. assert credentials._token_uri == SERVICE_ACCOUNT_INFO_NON_GDU["token_uri"]
  527. assert credentials._target_audience == self.TARGET_AUDIENCE
  528. assert credentials._use_iam_endpoint
  529. def test_from_service_account_file(self):
  530. info = SERVICE_ACCOUNT_INFO.copy()
  531. credentials = service_account.IDTokenCredentials.from_service_account_file(
  532. SERVICE_ACCOUNT_JSON_FILE, target_audience=self.TARGET_AUDIENCE
  533. )
  534. assert credentials.service_account_email == info["client_email"]
  535. assert credentials._signer.key_id == info["private_key_id"]
  536. assert credentials._token_uri == info["token_uri"]
  537. assert credentials._target_audience == self.TARGET_AUDIENCE
  538. assert not credentials._use_iam_endpoint
  539. def test_from_service_account_file_non_gdu(self):
  540. info = SERVICE_ACCOUNT_INFO_NON_GDU.copy()
  541. credentials = service_account.IDTokenCredentials.from_service_account_file(
  542. SERVICE_ACCOUNT_NON_GDU_JSON_FILE, target_audience=self.TARGET_AUDIENCE
  543. )
  544. assert credentials.service_account_email == info["client_email"]
  545. assert credentials._signer.key_id == info["private_key_id"]
  546. assert credentials._token_uri == info["token_uri"]
  547. assert credentials._target_audience == self.TARGET_AUDIENCE
  548. assert credentials._use_iam_endpoint
  549. def test_default_state(self):
  550. credentials = self.make_credentials()
  551. assert not credentials.valid
  552. # Expiration hasn't been set yet
  553. assert not credentials.expired
  554. def test_sign_bytes(self):
  555. credentials = self.make_credentials()
  556. to_sign = b"123"
  557. signature = credentials.sign_bytes(to_sign)
  558. assert crypt.verify_signature(to_sign, signature, PUBLIC_CERT_BYTES)
  559. def test_signer(self):
  560. credentials = self.make_credentials()
  561. assert isinstance(credentials.signer, crypt.Signer)
  562. def test_signer_email(self):
  563. credentials = self.make_credentials()
  564. assert credentials.signer_email == self.SERVICE_ACCOUNT_EMAIL
  565. def test_with_target_audience(self):
  566. credentials = self.make_credentials()
  567. new_credentials = credentials.with_target_audience("https://new.example.com")
  568. assert new_credentials._target_audience == "https://new.example.com"
  569. def test__with_use_iam_endpoint(self):
  570. credentials = self.make_credentials()
  571. new_credentials = credentials._with_use_iam_endpoint(True)
  572. assert new_credentials._use_iam_endpoint
  573. def test__with_use_iam_endpoint_non_default_universe_domain(self):
  574. credentials = self.make_credentials(universe_domain=FAKE_UNIVERSE_DOMAIN)
  575. with pytest.raises(exceptions.InvalidValue) as excinfo:
  576. credentials._with_use_iam_endpoint(False)
  577. assert excinfo.match(
  578. "use_iam_endpoint should be True for non-default universe domain"
  579. )
  580. def test_with_quota_project(self):
  581. credentials = self.make_credentials()
  582. new_credentials = credentials.with_quota_project("project-foo")
  583. assert new_credentials._quota_project_id == "project-foo"
  584. def test_with_token_uri(self):
  585. credentials = self.make_credentials()
  586. new_token_uri = "https://example2.com/oauth2/token"
  587. assert credentials._token_uri == self.TOKEN_URI
  588. creds_with_new_token_uri = credentials.with_token_uri(new_token_uri)
  589. assert creds_with_new_token_uri._token_uri == new_token_uri
  590. def test__make_authorization_grant_assertion(self):
  591. credentials = self.make_credentials()
  592. token = credentials._make_authorization_grant_assertion()
  593. payload = jwt.decode(token, PUBLIC_CERT_BYTES)
  594. assert payload["iss"] == self.SERVICE_ACCOUNT_EMAIL
  595. assert payload["aud"] == service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT
  596. assert payload["target_audience"] == self.TARGET_AUDIENCE
  597. @mock.patch("google.oauth2._client.id_token_jwt_grant", autospec=True)
  598. def test_refresh_success(self, id_token_jwt_grant):
  599. credentials = self.make_credentials()
  600. token = "token"
  601. id_token_jwt_grant.return_value = (
  602. token,
  603. _helpers.utcnow() + datetime.timedelta(seconds=500),
  604. {},
  605. )
  606. request = mock.create_autospec(transport.Request, instance=True)
  607. # Refresh credentials
  608. credentials.refresh(request)
  609. # Check jwt grant call.
  610. assert id_token_jwt_grant.called
  611. called_request, token_uri, assertion = id_token_jwt_grant.call_args[0]
  612. assert called_request == request
  613. assert token_uri == credentials._token_uri
  614. assert jwt.decode(assertion, PUBLIC_CERT_BYTES)
  615. # No further assertion done on the token, as there are separate tests
  616. # for checking the authorization grant assertion.
  617. # Check that the credentials have the token.
  618. assert credentials.token == token
  619. # Check that the credentials are valid (have a token and are not
  620. # expired)
  621. assert credentials.valid
  622. @mock.patch(
  623. "google.oauth2._client.call_iam_generate_id_token_endpoint", autospec=True
  624. )
  625. def test_refresh_iam_flow(self, call_iam_generate_id_token_endpoint):
  626. credentials = self.make_credentials()
  627. credentials._use_iam_endpoint = True
  628. token = "id_token"
  629. call_iam_generate_id_token_endpoint.return_value = (
  630. token,
  631. _helpers.utcnow() + datetime.timedelta(seconds=500),
  632. )
  633. request = mock.Mock()
  634. credentials.refresh(request)
  635. req, signer_email, target_audience, access_token = call_iam_generate_id_token_endpoint.call_args[
  636. 0
  637. ]
  638. assert req == request
  639. assert signer_email == "service-account@example.com"
  640. assert target_audience == "https://example.com"
  641. decoded_access_token = jwt.decode(access_token, verify=False)
  642. assert decoded_access_token["scope"] == "https://www.googleapis.com/auth/iam"
  643. @mock.patch("google.oauth2._client.id_token_jwt_grant", autospec=True)
  644. def test_before_request_refreshes(self, id_token_jwt_grant):
  645. credentials = self.make_credentials()
  646. token = "token"
  647. id_token_jwt_grant.return_value = (
  648. token,
  649. _helpers.utcnow() + datetime.timedelta(seconds=500),
  650. None,
  651. )
  652. request = mock.create_autospec(transport.Request, instance=True)
  653. # Credentials should start as invalid
  654. assert not credentials.valid
  655. # before_request should cause a refresh
  656. credentials.before_request(request, "GET", "http://example.com?a=1#3", {})
  657. # The refresh endpoint should've been called.
  658. assert id_token_jwt_grant.called
  659. # Credentials should now be valid.
  660. assert credentials.valid