service_account.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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. """Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0
  15. This module implements the JWT Profile for OAuth 2.0 Authorization Grants
  16. as defined by `RFC 7523`_ with particular support for how this RFC is
  17. implemented in Google's infrastructure. Google refers to these credentials
  18. as *Service Accounts*.
  19. Service accounts are used for server-to-server communication, such as
  20. interactions between a web application server and a Google service. The
  21. service account belongs to your application instead of to an individual end
  22. user. In contrast to other OAuth 2.0 profiles, no users are involved and your
  23. application "acts" as the service account.
  24. Typically an application uses a service account when the application uses
  25. Google APIs to work with its own data rather than a user's data. For example,
  26. an application that uses Google Cloud Datastore for data persistence would use
  27. a service account to authenticate its calls to the Google Cloud Datastore API.
  28. However, an application that needs to access a user's Drive documents would
  29. use the normal OAuth 2.0 profile.
  30. Additionally, Google Apps domain administrators can grant service accounts
  31. `domain-wide delegation`_ authority to access user data on behalf of users in
  32. the domain.
  33. This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used
  34. in place of the usual authorization token returned during the standard
  35. OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as
  36. the acquired access token is used as the bearer token when making requests
  37. using these credentials.
  38. This profile differs from normal OAuth 2.0 profile because no user consent
  39. step is required. The use of the private key allows this profile to assert
  40. identity directly.
  41. This profile also differs from the :mod:`google.auth.jwt` authentication
  42. because the JWT credentials use the JWT directly as the bearer token. This
  43. profile instead only uses the JWT to obtain an OAuth 2.0 access token. The
  44. obtained OAuth 2.0 access token is used as the bearer token.
  45. Domain-wide delegation
  46. ----------------------
  47. Domain-wide delegation allows a service account to access user data on
  48. behalf of any user in a Google Apps domain without consent from the user.
  49. For example, an application that uses the Google Calendar API to add events to
  50. the calendars of all users in a Google Apps domain would use a service account
  51. to access the Google Calendar API on behalf of users.
  52. The Google Apps administrator must explicitly authorize the service account to
  53. do this. This authorization step is referred to as "delegating domain-wide
  54. authority" to a service account.
  55. You can use domain-wise delegation by creating a set of credentials with a
  56. specific subject using :meth:`~Credentials.with_subject`.
  57. .. _RFC 7523: https://tools.ietf.org/html/rfc7523
  58. """
  59. import copy
  60. import datetime
  61. from google.auth import _helpers
  62. from google.auth import _service_account_info
  63. from google.auth import credentials
  64. from google.auth import exceptions
  65. from google.auth import jwt
  66. from google.auth import metrics
  67. from google.oauth2 import _client
  68. _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
  69. _DEFAULT_UNIVERSE_DOMAIN = "googleapis.com"
  70. _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
  71. class Credentials(
  72. credentials.Signing,
  73. credentials.Scoped,
  74. credentials.CredentialsWithQuotaProject,
  75. credentials.CredentialsWithTokenUri,
  76. ):
  77. """Service account credentials
  78. Usually, you'll create these credentials with one of the helper
  79. constructors. To create credentials using a Google service account
  80. private key JSON file::
  81. credentials = service_account.Credentials.from_service_account_file(
  82. 'service-account.json')
  83. Or if you already have the service account file loaded::
  84. service_account_info = json.load(open('service_account.json'))
  85. credentials = service_account.Credentials.from_service_account_info(
  86. service_account_info)
  87. Both helper methods pass on arguments to the constructor, so you can
  88. specify additional scopes and a subject if necessary::
  89. credentials = service_account.Credentials.from_service_account_file(
  90. 'service-account.json',
  91. scopes=['email'],
  92. subject='user@example.com')
  93. The credentials are considered immutable. If you want to modify the scopes
  94. or the subject used for delegation, use :meth:`with_scopes` or
  95. :meth:`with_subject`::
  96. scoped_credentials = credentials.with_scopes(['email'])
  97. delegated_credentials = credentials.with_subject(subject)
  98. To add a quota project, use :meth:`with_quota_project`::
  99. credentials = credentials.with_quota_project('myproject-123')
  100. """
  101. def __init__(
  102. self,
  103. signer,
  104. service_account_email,
  105. token_uri,
  106. scopes=None,
  107. default_scopes=None,
  108. subject=None,
  109. project_id=None,
  110. quota_project_id=None,
  111. additional_claims=None,
  112. always_use_jwt_access=False,
  113. universe_domain=_DEFAULT_UNIVERSE_DOMAIN,
  114. trust_boundary=None,
  115. ):
  116. """
  117. Args:
  118. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  119. service_account_email (str): The service account's email.
  120. scopes (Sequence[str]): User-defined scopes to request during the
  121. authorization grant.
  122. default_scopes (Sequence[str]): Default scopes passed by a
  123. Google client library. Use 'scopes' for user-defined scopes.
  124. token_uri (str): The OAuth 2.0 Token URI.
  125. subject (str): For domain-wide delegation, the email address of the
  126. user to for which to request delegated access.
  127. project_id (str): Project ID associated with the service account
  128. credential.
  129. quota_project_id (Optional[str]): The project ID used for quota and
  130. billing.
  131. additional_claims (Mapping[str, str]): Any additional claims for
  132. the JWT assertion used in the authorization grant.
  133. always_use_jwt_access (Optional[bool]): Whether self signed JWT should
  134. be always used.
  135. universe_domain (str): The universe domain. The default
  136. universe domain is googleapis.com. For default value self
  137. signed jwt is used for token refresh.
  138. trust_boundary (str): String representation of trust boundary meta.
  139. .. note:: Typically one of the helper constructors
  140. :meth:`from_service_account_file` or
  141. :meth:`from_service_account_info` are used instead of calling the
  142. constructor directly.
  143. """
  144. super(Credentials, self).__init__()
  145. self._scopes = scopes
  146. self._default_scopes = default_scopes
  147. self._signer = signer
  148. self._service_account_email = service_account_email
  149. self._subject = subject
  150. self._project_id = project_id
  151. self._quota_project_id = quota_project_id
  152. self._token_uri = token_uri
  153. self._always_use_jwt_access = always_use_jwt_access
  154. self._universe_domain = universe_domain or _DEFAULT_UNIVERSE_DOMAIN
  155. if universe_domain != _DEFAULT_UNIVERSE_DOMAIN:
  156. self._always_use_jwt_access = True
  157. self._jwt_credentials = None
  158. if additional_claims is not None:
  159. self._additional_claims = additional_claims
  160. else:
  161. self._additional_claims = {}
  162. self._trust_boundary = {"locations": [], "encoded_locations": "0x0"}
  163. @classmethod
  164. def _from_signer_and_info(cls, signer, info, **kwargs):
  165. """Creates a Credentials instance from a signer and service account
  166. info.
  167. Args:
  168. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  169. info (Mapping[str, str]): The service account info.
  170. kwargs: Additional arguments to pass to the constructor.
  171. Returns:
  172. google.auth.jwt.Credentials: The constructed credentials.
  173. Raises:
  174. ValueError: If the info is not in the expected format.
  175. """
  176. return cls(
  177. signer,
  178. service_account_email=info["client_email"],
  179. token_uri=info["token_uri"],
  180. project_id=info.get("project_id"),
  181. universe_domain=info.get("universe_domain", _DEFAULT_UNIVERSE_DOMAIN),
  182. trust_boundary=info.get("trust_boundary"),
  183. **kwargs
  184. )
  185. @classmethod
  186. def from_service_account_info(cls, info, **kwargs):
  187. """Creates a Credentials instance from parsed service account info.
  188. Args:
  189. info (Mapping[str, str]): The service account info in Google
  190. format.
  191. kwargs: Additional arguments to pass to the constructor.
  192. Returns:
  193. google.auth.service_account.Credentials: The constructed
  194. credentials.
  195. Raises:
  196. ValueError: If the info is not in the expected format.
  197. """
  198. signer = _service_account_info.from_dict(
  199. info, require=["client_email", "token_uri"]
  200. )
  201. return cls._from_signer_and_info(signer, info, **kwargs)
  202. @classmethod
  203. def from_service_account_file(cls, filename, **kwargs):
  204. """Creates a Credentials instance from a service account json file.
  205. Args:
  206. filename (str): The path to the service account json file.
  207. kwargs: Additional arguments to pass to the constructor.
  208. Returns:
  209. google.auth.service_account.Credentials: The constructed
  210. credentials.
  211. """
  212. info, signer = _service_account_info.from_filename(
  213. filename, require=["client_email", "token_uri"]
  214. )
  215. return cls._from_signer_and_info(signer, info, **kwargs)
  216. @property
  217. def service_account_email(self):
  218. """The service account email."""
  219. return self._service_account_email
  220. @property
  221. def project_id(self):
  222. """Project ID associated with this credential."""
  223. return self._project_id
  224. @property
  225. def requires_scopes(self):
  226. """Checks if the credentials requires scopes.
  227. Returns:
  228. bool: True if there are no scopes set otherwise False.
  229. """
  230. return True if not self._scopes else False
  231. def _make_copy(self):
  232. cred = self.__class__(
  233. self._signer,
  234. service_account_email=self._service_account_email,
  235. scopes=copy.copy(self._scopes),
  236. default_scopes=copy.copy(self._default_scopes),
  237. token_uri=self._token_uri,
  238. subject=self._subject,
  239. project_id=self._project_id,
  240. quota_project_id=self._quota_project_id,
  241. additional_claims=self._additional_claims.copy(),
  242. always_use_jwt_access=self._always_use_jwt_access,
  243. universe_domain=self._universe_domain,
  244. )
  245. return cred
  246. @_helpers.copy_docstring(credentials.Scoped)
  247. def with_scopes(self, scopes, default_scopes=None):
  248. cred = self._make_copy()
  249. cred._scopes = scopes
  250. cred._default_scopes = default_scopes
  251. return cred
  252. def with_always_use_jwt_access(self, always_use_jwt_access):
  253. """Create a copy of these credentials with the specified always_use_jwt_access value.
  254. Args:
  255. always_use_jwt_access (bool): Whether always use self signed JWT or not.
  256. Returns:
  257. google.auth.service_account.Credentials: A new credentials
  258. instance.
  259. Raises:
  260. google.auth.exceptions.InvalidValue: If the universe domain is not
  261. default and always_use_jwt_access is False.
  262. """
  263. cred = self._make_copy()
  264. if (
  265. cred._universe_domain != _DEFAULT_UNIVERSE_DOMAIN
  266. and not always_use_jwt_access
  267. ):
  268. raise exceptions.InvalidValue(
  269. "always_use_jwt_access should be True for non-default universe domain"
  270. )
  271. cred._always_use_jwt_access = always_use_jwt_access
  272. return cred
  273. @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
  274. def with_universe_domain(self, universe_domain):
  275. cred = self._make_copy()
  276. cred._universe_domain = universe_domain
  277. if universe_domain != _DEFAULT_UNIVERSE_DOMAIN:
  278. cred._always_use_jwt_access = True
  279. return cred
  280. def with_subject(self, subject):
  281. """Create a copy of these credentials with the specified subject.
  282. Args:
  283. subject (str): The subject claim.
  284. Returns:
  285. google.auth.service_account.Credentials: A new credentials
  286. instance.
  287. """
  288. cred = self._make_copy()
  289. cred._subject = subject
  290. return cred
  291. def with_claims(self, additional_claims):
  292. """Returns a copy of these credentials with modified claims.
  293. Args:
  294. additional_claims (Mapping[str, str]): Any additional claims for
  295. the JWT payload. This will be merged with the current
  296. additional claims.
  297. Returns:
  298. google.auth.service_account.Credentials: A new credentials
  299. instance.
  300. """
  301. new_additional_claims = copy.deepcopy(self._additional_claims)
  302. new_additional_claims.update(additional_claims or {})
  303. cred = self._make_copy()
  304. cred._additional_claims = new_additional_claims
  305. return cred
  306. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  307. def with_quota_project(self, quota_project_id):
  308. cred = self._make_copy()
  309. cred._quota_project_id = quota_project_id
  310. return cred
  311. @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
  312. def with_token_uri(self, token_uri):
  313. cred = self._make_copy()
  314. cred._token_uri = token_uri
  315. return cred
  316. def _make_authorization_grant_assertion(self):
  317. """Create the OAuth 2.0 assertion.
  318. This assertion is used during the OAuth 2.0 grant to acquire an
  319. access token.
  320. Returns:
  321. bytes: The authorization grant assertion.
  322. """
  323. now = _helpers.utcnow()
  324. lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
  325. expiry = now + lifetime
  326. payload = {
  327. "iat": _helpers.datetime_to_secs(now),
  328. "exp": _helpers.datetime_to_secs(expiry),
  329. # The issuer must be the service account email.
  330. "iss": self._service_account_email,
  331. # The audience must be the auth token endpoint's URI
  332. "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
  333. "scope": _helpers.scopes_to_string(self._scopes or ()),
  334. }
  335. payload.update(self._additional_claims)
  336. # The subject can be a user email for domain-wide delegation.
  337. if self._subject:
  338. payload.setdefault("sub", self._subject)
  339. token = jwt.encode(self._signer, payload)
  340. return token
  341. def _use_self_signed_jwt(self):
  342. # Since domain wide delegation doesn't work with self signed JWT. If
  343. # subject exists, then we should not use self signed JWT.
  344. return self._subject is None and self._jwt_credentials is not None
  345. def _metric_header_for_usage(self):
  346. if self._use_self_signed_jwt():
  347. return metrics.CRED_TYPE_SA_JWT
  348. return metrics.CRED_TYPE_SA_ASSERTION
  349. @_helpers.copy_docstring(credentials.Credentials)
  350. def refresh(self, request):
  351. if self._always_use_jwt_access and not self._jwt_credentials:
  352. # If self signed jwt should be used but jwt credential is not
  353. # created, try to create one with scopes
  354. self._create_self_signed_jwt(None)
  355. if self._universe_domain != _DEFAULT_UNIVERSE_DOMAIN and self._subject:
  356. raise exceptions.RefreshError(
  357. "domain wide delegation is not supported for non-default universe domain"
  358. )
  359. if self._use_self_signed_jwt():
  360. self._jwt_credentials.refresh(request)
  361. self.token = self._jwt_credentials.token.decode()
  362. self.expiry = self._jwt_credentials.expiry
  363. else:
  364. assertion = self._make_authorization_grant_assertion()
  365. access_token, expiry, _ = _client.jwt_grant(
  366. request, self._token_uri, assertion
  367. )
  368. self.token = access_token
  369. self.expiry = expiry
  370. def _create_self_signed_jwt(self, audience):
  371. """Create a self-signed JWT from the credentials if requirements are met.
  372. Args:
  373. audience (str): The service URL. ``https://[API_ENDPOINT]/``
  374. """
  375. # https://google.aip.dev/auth/4111
  376. if self._always_use_jwt_access:
  377. if self._scopes:
  378. additional_claims = {"scope": " ".join(self._scopes)}
  379. if (
  380. self._jwt_credentials is None
  381. or self._jwt_credentials.additional_claims != additional_claims
  382. ):
  383. self._jwt_credentials = jwt.Credentials.from_signing_credentials(
  384. self, None, additional_claims=additional_claims
  385. )
  386. elif audience:
  387. if (
  388. self._jwt_credentials is None
  389. or self._jwt_credentials._audience != audience
  390. ):
  391. self._jwt_credentials = jwt.Credentials.from_signing_credentials(
  392. self, audience
  393. )
  394. elif self._default_scopes:
  395. additional_claims = {"scope": " ".join(self._default_scopes)}
  396. if (
  397. self._jwt_credentials is None
  398. or additional_claims != self._jwt_credentials.additional_claims
  399. ):
  400. self._jwt_credentials = jwt.Credentials.from_signing_credentials(
  401. self, None, additional_claims=additional_claims
  402. )
  403. elif not self._scopes and audience:
  404. self._jwt_credentials = jwt.Credentials.from_signing_credentials(
  405. self, audience
  406. )
  407. @_helpers.copy_docstring(credentials.Signing)
  408. def sign_bytes(self, message):
  409. return self._signer.sign(message)
  410. @property # type: ignore
  411. @_helpers.copy_docstring(credentials.Signing)
  412. def signer(self):
  413. return self._signer
  414. @property # type: ignore
  415. @_helpers.copy_docstring(credentials.Signing)
  416. def signer_email(self):
  417. return self._service_account_email
  418. class IDTokenCredentials(
  419. credentials.Signing,
  420. credentials.CredentialsWithQuotaProject,
  421. credentials.CredentialsWithTokenUri,
  422. ):
  423. """Open ID Connect ID Token-based service account credentials.
  424. These credentials are largely similar to :class:`.Credentials`, but instead
  425. of using an OAuth 2.0 Access Token as the bearer token, they use an Open
  426. ID Connect ID Token as the bearer token. These credentials are useful when
  427. communicating to services that require ID Tokens and can not accept access
  428. tokens.
  429. Usually, you'll create these credentials with one of the helper
  430. constructors. To create credentials using a Google service account
  431. private key JSON file::
  432. credentials = (
  433. service_account.IDTokenCredentials.from_service_account_file(
  434. 'service-account.json'))
  435. Or if you already have the service account file loaded::
  436. service_account_info = json.load(open('service_account.json'))
  437. credentials = (
  438. service_account.IDTokenCredentials.from_service_account_info(
  439. service_account_info))
  440. Both helper methods pass on arguments to the constructor, so you can
  441. specify additional scopes and a subject if necessary::
  442. credentials = (
  443. service_account.IDTokenCredentials.from_service_account_file(
  444. 'service-account.json',
  445. scopes=['email'],
  446. subject='user@example.com'))
  447. The credentials are considered immutable. If you want to modify the scopes
  448. or the subject used for delegation, use :meth:`with_scopes` or
  449. :meth:`with_subject`::
  450. scoped_credentials = credentials.with_scopes(['email'])
  451. delegated_credentials = credentials.with_subject(subject)
  452. """
  453. def __init__(
  454. self,
  455. signer,
  456. service_account_email,
  457. token_uri,
  458. target_audience,
  459. additional_claims=None,
  460. quota_project_id=None,
  461. universe_domain=_DEFAULT_UNIVERSE_DOMAIN,
  462. ):
  463. """
  464. Args:
  465. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  466. service_account_email (str): The service account's email.
  467. token_uri (str): The OAuth 2.0 Token URI.
  468. target_audience (str): The intended audience for these credentials,
  469. used when requesting the ID Token. The ID Token's ``aud`` claim
  470. will be set to this string.
  471. additional_claims (Mapping[str, str]): Any additional claims for
  472. the JWT assertion used in the authorization grant.
  473. quota_project_id (Optional[str]): The project ID used for quota and billing.
  474. universe_domain (str): The universe domain. The default
  475. universe domain is googleapis.com. For default value IAM ID
  476. token endponint is used for token refresh. Note that
  477. iam.serviceAccountTokenCreator role is required to use the IAM
  478. endpoint.
  479. .. note:: Typically one of the helper constructors
  480. :meth:`from_service_account_file` or
  481. :meth:`from_service_account_info` are used instead of calling the
  482. constructor directly.
  483. """
  484. super(IDTokenCredentials, self).__init__()
  485. self._signer = signer
  486. self._service_account_email = service_account_email
  487. self._token_uri = token_uri
  488. self._target_audience = target_audience
  489. self._quota_project_id = quota_project_id
  490. self._use_iam_endpoint = False
  491. if not universe_domain:
  492. self._universe_domain = _DEFAULT_UNIVERSE_DOMAIN
  493. else:
  494. self._universe_domain = universe_domain
  495. if universe_domain != _DEFAULT_UNIVERSE_DOMAIN:
  496. self._use_iam_endpoint = True
  497. if additional_claims is not None:
  498. self._additional_claims = additional_claims
  499. else:
  500. self._additional_claims = {}
  501. @classmethod
  502. def _from_signer_and_info(cls, signer, info, **kwargs):
  503. """Creates a credentials instance from a signer and service account
  504. info.
  505. Args:
  506. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  507. info (Mapping[str, str]): The service account info.
  508. kwargs: Additional arguments to pass to the constructor.
  509. Returns:
  510. google.auth.jwt.IDTokenCredentials: The constructed credentials.
  511. Raises:
  512. ValueError: If the info is not in the expected format.
  513. """
  514. kwargs.setdefault("service_account_email", info["client_email"])
  515. kwargs.setdefault("token_uri", info["token_uri"])
  516. if "universe_domain" in info:
  517. kwargs["universe_domain"] = info["universe_domain"]
  518. return cls(signer, **kwargs)
  519. @classmethod
  520. def from_service_account_info(cls, info, **kwargs):
  521. """Creates a credentials instance from parsed service account info.
  522. Args:
  523. info (Mapping[str, str]): The service account info in Google
  524. format.
  525. kwargs: Additional arguments to pass to the constructor.
  526. Returns:
  527. google.auth.service_account.IDTokenCredentials: The constructed
  528. credentials.
  529. Raises:
  530. ValueError: If the info is not in the expected format.
  531. """
  532. signer = _service_account_info.from_dict(
  533. info, require=["client_email", "token_uri"]
  534. )
  535. return cls._from_signer_and_info(signer, info, **kwargs)
  536. @classmethod
  537. def from_service_account_file(cls, filename, **kwargs):
  538. """Creates a credentials instance from a service account json file.
  539. Args:
  540. filename (str): The path to the service account json file.
  541. kwargs: Additional arguments to pass to the constructor.
  542. Returns:
  543. google.auth.service_account.IDTokenCredentials: The constructed
  544. credentials.
  545. """
  546. info, signer = _service_account_info.from_filename(
  547. filename, require=["client_email", "token_uri"]
  548. )
  549. return cls._from_signer_and_info(signer, info, **kwargs)
  550. def _make_copy(self):
  551. cred = self.__class__(
  552. self._signer,
  553. service_account_email=self._service_account_email,
  554. token_uri=self._token_uri,
  555. target_audience=self._target_audience,
  556. additional_claims=self._additional_claims.copy(),
  557. quota_project_id=self.quota_project_id,
  558. universe_domain=self._universe_domain,
  559. )
  560. # _use_iam_endpoint is not exposed in the constructor
  561. cred._use_iam_endpoint = self._use_iam_endpoint
  562. return cred
  563. def with_target_audience(self, target_audience):
  564. """Create a copy of these credentials with the specified target
  565. audience.
  566. Args:
  567. target_audience (str): The intended audience for these credentials,
  568. used when requesting the ID Token.
  569. Returns:
  570. google.auth.service_account.IDTokenCredentials: A new credentials
  571. instance.
  572. """
  573. cred = self._make_copy()
  574. cred._target_audience = target_audience
  575. return cred
  576. def _with_use_iam_endpoint(self, use_iam_endpoint):
  577. """Create a copy of these credentials with the use_iam_endpoint value.
  578. Args:
  579. use_iam_endpoint (bool): If True, IAM generateIdToken endpoint will
  580. be used instead of the token_uri. Note that
  581. iam.serviceAccountTokenCreator role is required to use the IAM
  582. endpoint. The default value is False. This feature is currently
  583. experimental and subject to change without notice.
  584. Returns:
  585. google.auth.service_account.IDTokenCredentials: A new credentials
  586. instance.
  587. Raises:
  588. google.auth.exceptions.InvalidValue: If the universe domain is not
  589. default and use_iam_endpoint is False.
  590. """
  591. cred = self._make_copy()
  592. if cred._universe_domain != _DEFAULT_UNIVERSE_DOMAIN and not use_iam_endpoint:
  593. raise exceptions.InvalidValue(
  594. "use_iam_endpoint should be True for non-default universe domain"
  595. )
  596. cred._use_iam_endpoint = use_iam_endpoint
  597. return cred
  598. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  599. def with_quota_project(self, quota_project_id):
  600. cred = self._make_copy()
  601. cred._quota_project_id = quota_project_id
  602. return cred
  603. @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
  604. def with_token_uri(self, token_uri):
  605. cred = self._make_copy()
  606. cred._token_uri = token_uri
  607. return cred
  608. def _make_authorization_grant_assertion(self):
  609. """Create the OAuth 2.0 assertion.
  610. This assertion is used during the OAuth 2.0 grant to acquire an
  611. ID token.
  612. Returns:
  613. bytes: The authorization grant assertion.
  614. """
  615. now = _helpers.utcnow()
  616. lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
  617. expiry = now + lifetime
  618. payload = {
  619. "iat": _helpers.datetime_to_secs(now),
  620. "exp": _helpers.datetime_to_secs(expiry),
  621. # The issuer must be the service account email.
  622. "iss": self.service_account_email,
  623. # The audience must be the auth token endpoint's URI
  624. "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
  625. # The target audience specifies which service the ID token is
  626. # intended for.
  627. "target_audience": self._target_audience,
  628. }
  629. payload.update(self._additional_claims)
  630. token = jwt.encode(self._signer, payload)
  631. return token
  632. def _refresh_with_iam_endpoint(self, request):
  633. """Use IAM generateIdToken endpoint to obtain an ID token.
  634. It works as follows:
  635. 1. First we create a self signed jwt with
  636. https://www.googleapis.com/auth/iam being the scope.
  637. 2. Next we use the self signed jwt as the access token, and make a POST
  638. request to IAM generateIdToken endpoint. The request body is:
  639. {
  640. "audience": self._target_audience,
  641. "includeEmail": "true",
  642. "useEmailAzp": "true",
  643. }
  644. If the request is succesfully, it will return {"token":"the ID token"},
  645. and we can extract the ID token and compute its expiry.
  646. """
  647. jwt_credentials = jwt.Credentials.from_signing_credentials(
  648. self,
  649. None,
  650. additional_claims={"scope": "https://www.googleapis.com/auth/iam"},
  651. )
  652. jwt_credentials.refresh(request)
  653. self.token, self.expiry = _client.call_iam_generate_id_token_endpoint(
  654. request,
  655. self.signer_email,
  656. self._target_audience,
  657. jwt_credentials.token.decode(),
  658. )
  659. @_helpers.copy_docstring(credentials.Credentials)
  660. def refresh(self, request):
  661. if self._use_iam_endpoint:
  662. self._refresh_with_iam_endpoint(request)
  663. else:
  664. assertion = self._make_authorization_grant_assertion()
  665. access_token, expiry, _ = _client.id_token_jwt_grant(
  666. request, self._token_uri, assertion
  667. )
  668. self.token = access_token
  669. self.expiry = expiry
  670. @property
  671. def service_account_email(self):
  672. """The service account email."""
  673. return self._service_account_email
  674. @_helpers.copy_docstring(credentials.Signing)
  675. def sign_bytes(self, message):
  676. return self._signer.sign(message)
  677. @property # type: ignore
  678. @_helpers.copy_docstring(credentials.Signing)
  679. def signer(self):
  680. return self._signer
  681. @property # type: ignore
  682. @_helpers.copy_docstring(credentials.Signing)
  683. def signer_email(self):
  684. return self._service_account_email