service_account.py 31 KB

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