service_account.py 31 KB

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