service_account.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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 jwt
  65. from google.oauth2 import _client
  66. _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
  67. _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
  68. class Credentials(
  69. credentials.Signing, credentials.Scoped, credentials.CredentialsWithQuotaProject
  70. ):
  71. """Service account credentials
  72. Usually, you'll create these credentials with one of the helper
  73. constructors. To create credentials using a Google service account
  74. private key JSON file::
  75. credentials = service_account.Credentials.from_service_account_file(
  76. 'service-account.json')
  77. Or if you already have the service account file loaded::
  78. service_account_info = json.load(open('service_account.json'))
  79. credentials = service_account.Credentials.from_service_account_info(
  80. service_account_info)
  81. Both helper methods pass on arguments to the constructor, so you can
  82. specify additional scopes and a subject if necessary::
  83. credentials = service_account.Credentials.from_service_account_file(
  84. 'service-account.json',
  85. scopes=['email'],
  86. subject='user@example.com')
  87. The credentials are considered immutable. If you want to modify the scopes
  88. or the subject used for delegation, use :meth:`with_scopes` or
  89. :meth:`with_subject`::
  90. scoped_credentials = credentials.with_scopes(['email'])
  91. delegated_credentials = credentials.with_subject(subject)
  92. To add a quota project, use :meth:`with_quota_project`::
  93. credentials = credentials.with_quota_project('myproject-123')
  94. """
  95. def __init__(
  96. self,
  97. signer,
  98. service_account_email,
  99. token_uri,
  100. scopes=None,
  101. default_scopes=None,
  102. subject=None,
  103. project_id=None,
  104. quota_project_id=None,
  105. additional_claims=None,
  106. always_use_jwt_access=False,
  107. ):
  108. """
  109. Args:
  110. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  111. service_account_email (str): The service account's email.
  112. scopes (Sequence[str]): User-defined scopes to request during the
  113. authorization grant.
  114. default_scopes (Sequence[str]): Default scopes passed by a
  115. Google client library. Use 'scopes' for user-defined scopes.
  116. token_uri (str): The OAuth 2.0 Token URI.
  117. subject (str): For domain-wide delegation, the email address of the
  118. user to for which to request delegated access.
  119. project_id (str): Project ID associated with the service account
  120. credential.
  121. quota_project_id (Optional[str]): The project ID used for quota and
  122. billing.
  123. additional_claims (Mapping[str, str]): Any additional claims for
  124. the JWT assertion used in the authorization grant.
  125. always_use_jwt_access (Optional[bool]): Whether self signed JWT should
  126. be always used.
  127. .. note:: Typically one of the helper constructors
  128. :meth:`from_service_account_file` or
  129. :meth:`from_service_account_info` are used instead of calling the
  130. constructor directly.
  131. """
  132. super(Credentials, self).__init__()
  133. self._scopes = scopes
  134. self._default_scopes = default_scopes
  135. self._signer = signer
  136. self._service_account_email = service_account_email
  137. self._subject = subject
  138. self._project_id = project_id
  139. self._quota_project_id = quota_project_id
  140. self._token_uri = token_uri
  141. self._always_use_jwt_access = always_use_jwt_access
  142. self._jwt_credentials = None
  143. if additional_claims is not None:
  144. self._additional_claims = additional_claims
  145. else:
  146. self._additional_claims = {}
  147. @classmethod
  148. def _from_signer_and_info(cls, signer, info, **kwargs):
  149. """Creates a Credentials instance from a signer and service account
  150. info.
  151. Args:
  152. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  153. info (Mapping[str, str]): The service account info.
  154. kwargs: Additional arguments to pass to the constructor.
  155. Returns:
  156. google.auth.jwt.Credentials: The constructed credentials.
  157. Raises:
  158. ValueError: If the info is not in the expected format.
  159. """
  160. return cls(
  161. signer,
  162. service_account_email=info["client_email"],
  163. token_uri=info["token_uri"],
  164. project_id=info.get("project_id"),
  165. **kwargs
  166. )
  167. @classmethod
  168. def from_service_account_info(cls, info, **kwargs):
  169. """Creates a Credentials instance from parsed service account info.
  170. Args:
  171. info (Mapping[str, str]): The service account info in Google
  172. format.
  173. kwargs: Additional arguments to pass to the constructor.
  174. Returns:
  175. google.auth.service_account.Credentials: The constructed
  176. credentials.
  177. Raises:
  178. ValueError: If the info is not in the expected format.
  179. """
  180. signer = _service_account_info.from_dict(
  181. info, require=["client_email", "token_uri"]
  182. )
  183. return cls._from_signer_and_info(signer, info, **kwargs)
  184. @classmethod
  185. def from_service_account_file(cls, filename, **kwargs):
  186. """Creates a Credentials instance from a service account json file.
  187. Args:
  188. filename (str): The path to the service account json file.
  189. kwargs: Additional arguments to pass to the constructor.
  190. Returns:
  191. google.auth.service_account.Credentials: The constructed
  192. credentials.
  193. """
  194. info, signer = _service_account_info.from_filename(
  195. filename, require=["client_email", "token_uri"]
  196. )
  197. return cls._from_signer_and_info(signer, info, **kwargs)
  198. @property
  199. def service_account_email(self):
  200. """The service account email."""
  201. return self._service_account_email
  202. @property
  203. def project_id(self):
  204. """Project ID associated with this credential."""
  205. return self._project_id
  206. @property
  207. def requires_scopes(self):
  208. """Checks if the credentials requires scopes.
  209. Returns:
  210. bool: True if there are no scopes set otherwise False.
  211. """
  212. return True if not self._scopes else False
  213. @_helpers.copy_docstring(credentials.Scoped)
  214. def with_scopes(self, scopes, default_scopes=None):
  215. return self.__class__(
  216. self._signer,
  217. service_account_email=self._service_account_email,
  218. scopes=scopes,
  219. default_scopes=default_scopes,
  220. token_uri=self._token_uri,
  221. subject=self._subject,
  222. project_id=self._project_id,
  223. quota_project_id=self._quota_project_id,
  224. additional_claims=self._additional_claims.copy(),
  225. always_use_jwt_access=self._always_use_jwt_access,
  226. )
  227. def with_always_use_jwt_access(self, always_use_jwt_access):
  228. """Create a copy of these credentials with the specified always_use_jwt_access value.
  229. Args:
  230. always_use_jwt_access (bool): Whether always use self signed JWT or not.
  231. Returns:
  232. google.auth.service_account.Credentials: A new credentials
  233. instance.
  234. """
  235. return self.__class__(
  236. self._signer,
  237. service_account_email=self._service_account_email,
  238. scopes=self._scopes,
  239. default_scopes=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=always_use_jwt_access,
  246. )
  247. def with_subject(self, subject):
  248. """Create a copy of these credentials with the specified subject.
  249. Args:
  250. subject (str): The subject claim.
  251. Returns:
  252. google.auth.service_account.Credentials: A new credentials
  253. instance.
  254. """
  255. return self.__class__(
  256. self._signer,
  257. service_account_email=self._service_account_email,
  258. scopes=self._scopes,
  259. default_scopes=self._default_scopes,
  260. token_uri=self._token_uri,
  261. subject=subject,
  262. project_id=self._project_id,
  263. quota_project_id=self._quota_project_id,
  264. additional_claims=self._additional_claims.copy(),
  265. always_use_jwt_access=self._always_use_jwt_access,
  266. )
  267. def with_claims(self, additional_claims):
  268. """Returns a copy of these credentials with modified claims.
  269. Args:
  270. additional_claims (Mapping[str, str]): Any additional claims for
  271. the JWT payload. This will be merged with the current
  272. additional claims.
  273. Returns:
  274. google.auth.service_account.Credentials: A new credentials
  275. instance.
  276. """
  277. new_additional_claims = copy.deepcopy(self._additional_claims)
  278. new_additional_claims.update(additional_claims or {})
  279. return self.__class__(
  280. self._signer,
  281. service_account_email=self._service_account_email,
  282. scopes=self._scopes,
  283. default_scopes=self._default_scopes,
  284. token_uri=self._token_uri,
  285. subject=self._subject,
  286. project_id=self._project_id,
  287. quota_project_id=self._quota_project_id,
  288. additional_claims=new_additional_claims,
  289. always_use_jwt_access=self._always_use_jwt_access,
  290. )
  291. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  292. def with_quota_project(self, quota_project_id):
  293. return self.__class__(
  294. self._signer,
  295. service_account_email=self._service_account_email,
  296. default_scopes=self._default_scopes,
  297. scopes=self._scopes,
  298. token_uri=self._token_uri,
  299. subject=self._subject,
  300. project_id=self._project_id,
  301. quota_project_id=quota_project_id,
  302. additional_claims=self._additional_claims.copy(),
  303. always_use_jwt_access=self._always_use_jwt_access,
  304. )
  305. def _make_authorization_grant_assertion(self):
  306. """Create the OAuth 2.0 assertion.
  307. This assertion is used during the OAuth 2.0 grant to acquire an
  308. access token.
  309. Returns:
  310. bytes: The authorization grant assertion.
  311. """
  312. now = _helpers.utcnow()
  313. lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
  314. expiry = now + lifetime
  315. payload = {
  316. "iat": _helpers.datetime_to_secs(now),
  317. "exp": _helpers.datetime_to_secs(expiry),
  318. # The issuer must be the service account email.
  319. "iss": self._service_account_email,
  320. # The audience must be the auth token endpoint's URI
  321. "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
  322. "scope": _helpers.scopes_to_string(self._scopes or ()),
  323. }
  324. payload.update(self._additional_claims)
  325. # The subject can be a user email for domain-wide delegation.
  326. if self._subject:
  327. payload.setdefault("sub", self._subject)
  328. token = jwt.encode(self._signer, payload)
  329. return token
  330. @_helpers.copy_docstring(credentials.Credentials)
  331. def refresh(self, request):
  332. if self._jwt_credentials is not None:
  333. self._jwt_credentials.refresh(request)
  334. self.token = self._jwt_credentials.token
  335. self.expiry = self._jwt_credentials.expiry
  336. else:
  337. assertion = self._make_authorization_grant_assertion()
  338. access_token, expiry, _ = _client.jwt_grant(
  339. request, self._token_uri, assertion
  340. )
  341. self.token = access_token
  342. self.expiry = expiry
  343. def _create_self_signed_jwt(self, audience):
  344. """Create a self-signed JWT from the credentials if requirements are met.
  345. Args:
  346. audience (str): The service URL. ``https://[API_ENDPOINT]/``
  347. """
  348. # https://google.aip.dev/auth/4111
  349. if self._always_use_jwt_access:
  350. if self._scopes:
  351. self._jwt_credentials = jwt.Credentials.from_signing_credentials(
  352. self, None, additional_claims={"scope": " ".join(self._scopes)}
  353. )
  354. elif audience:
  355. self._jwt_credentials = jwt.Credentials.from_signing_credentials(
  356. self, audience
  357. )
  358. elif self._default_scopes:
  359. self._jwt_credentials = jwt.Credentials.from_signing_credentials(
  360. self,
  361. None,
  362. additional_claims={"scope": " ".join(self._default_scopes)},
  363. )
  364. elif not self._scopes and audience:
  365. self._jwt_credentials = jwt.Credentials.from_signing_credentials(
  366. self, audience
  367. )
  368. @_helpers.copy_docstring(credentials.Signing)
  369. def sign_bytes(self, message):
  370. return self._signer.sign(message)
  371. @property
  372. @_helpers.copy_docstring(credentials.Signing)
  373. def signer(self):
  374. return self._signer
  375. @property
  376. @_helpers.copy_docstring(credentials.Signing)
  377. def signer_email(self):
  378. return self._service_account_email
  379. class IDTokenCredentials(credentials.Signing, credentials.CredentialsWithQuotaProject):
  380. """Open ID Connect ID Token-based service account credentials.
  381. These credentials are largely similar to :class:`.Credentials`, but instead
  382. of using an OAuth 2.0 Access Token as the bearer token, they use an Open
  383. ID Connect ID Token as the bearer token. These credentials are useful when
  384. communicating to services that require ID Tokens and can not accept access
  385. tokens.
  386. Usually, you'll create these credentials with one of the helper
  387. constructors. To create credentials using a Google service account
  388. private key JSON file::
  389. credentials = (
  390. service_account.IDTokenCredentials.from_service_account_file(
  391. 'service-account.json'))
  392. Or if you already have the service account file loaded::
  393. service_account_info = json.load(open('service_account.json'))
  394. credentials = (
  395. service_account.IDTokenCredentials.from_service_account_info(
  396. service_account_info))
  397. Both helper methods pass on arguments to the constructor, so you can
  398. specify additional scopes and a subject if necessary::
  399. credentials = (
  400. service_account.IDTokenCredentials.from_service_account_file(
  401. 'service-account.json',
  402. scopes=['email'],
  403. subject='user@example.com'))
  404. The credentials are considered immutable. If you want to modify the scopes
  405. or the subject used for delegation, use :meth:`with_scopes` or
  406. :meth:`with_subject`::
  407. scoped_credentials = credentials.with_scopes(['email'])
  408. delegated_credentials = credentials.with_subject(subject)
  409. """
  410. def __init__(
  411. self,
  412. signer,
  413. service_account_email,
  414. token_uri,
  415. target_audience,
  416. additional_claims=None,
  417. quota_project_id=None,
  418. ):
  419. """
  420. Args:
  421. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  422. service_account_email (str): The service account's email.
  423. token_uri (str): The OAuth 2.0 Token URI.
  424. target_audience (str): The intended audience for these credentials,
  425. used when requesting the ID Token. The ID Token's ``aud`` claim
  426. will be set to this string.
  427. additional_claims (Mapping[str, str]): Any additional claims for
  428. the JWT assertion used in the authorization grant.
  429. quota_project_id (Optional[str]): The project ID used for quota and billing.
  430. .. note:: Typically one of the helper constructors
  431. :meth:`from_service_account_file` or
  432. :meth:`from_service_account_info` are used instead of calling the
  433. constructor directly.
  434. """
  435. super(IDTokenCredentials, self).__init__()
  436. self._signer = signer
  437. self._service_account_email = service_account_email
  438. self._token_uri = token_uri
  439. self._target_audience = target_audience
  440. self._quota_project_id = quota_project_id
  441. if additional_claims is not None:
  442. self._additional_claims = additional_claims
  443. else:
  444. self._additional_claims = {}
  445. @classmethod
  446. def _from_signer_and_info(cls, signer, info, **kwargs):
  447. """Creates a credentials instance from a signer and service account
  448. info.
  449. Args:
  450. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  451. info (Mapping[str, str]): The service account info.
  452. kwargs: Additional arguments to pass to the constructor.
  453. Returns:
  454. google.auth.jwt.IDTokenCredentials: The constructed credentials.
  455. Raises:
  456. ValueError: If the info is not in the expected format.
  457. """
  458. kwargs.setdefault("service_account_email", info["client_email"])
  459. kwargs.setdefault("token_uri", info["token_uri"])
  460. return cls(signer, **kwargs)
  461. @classmethod
  462. def from_service_account_info(cls, info, **kwargs):
  463. """Creates a credentials instance from parsed service account info.
  464. Args:
  465. info (Mapping[str, str]): The service account info in Google
  466. format.
  467. kwargs: Additional arguments to pass to the constructor.
  468. Returns:
  469. google.auth.service_account.IDTokenCredentials: The constructed
  470. credentials.
  471. Raises:
  472. ValueError: If the info is not in the expected format.
  473. """
  474. signer = _service_account_info.from_dict(
  475. info, require=["client_email", "token_uri"]
  476. )
  477. return cls._from_signer_and_info(signer, info, **kwargs)
  478. @classmethod
  479. def from_service_account_file(cls, filename, **kwargs):
  480. """Creates a credentials instance from a service account json file.
  481. Args:
  482. filename (str): The path to the service account json file.
  483. kwargs: Additional arguments to pass to the constructor.
  484. Returns:
  485. google.auth.service_account.IDTokenCredentials: The constructed
  486. credentials.
  487. """
  488. info, signer = _service_account_info.from_filename(
  489. filename, require=["client_email", "token_uri"]
  490. )
  491. return cls._from_signer_and_info(signer, info, **kwargs)
  492. def with_target_audience(self, target_audience):
  493. """Create a copy of these credentials with the specified target
  494. audience.
  495. Args:
  496. target_audience (str): The intended audience for these credentials,
  497. used when requesting the ID Token.
  498. Returns:
  499. google.auth.service_account.IDTokenCredentials: A new credentials
  500. instance.
  501. """
  502. return self.__class__(
  503. self._signer,
  504. service_account_email=self._service_account_email,
  505. token_uri=self._token_uri,
  506. target_audience=target_audience,
  507. additional_claims=self._additional_claims.copy(),
  508. quota_project_id=self.quota_project_id,
  509. )
  510. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  511. def with_quota_project(self, quota_project_id):
  512. return self.__class__(
  513. self._signer,
  514. service_account_email=self._service_account_email,
  515. token_uri=self._token_uri,
  516. target_audience=self._target_audience,
  517. additional_claims=self._additional_claims.copy(),
  518. quota_project_id=quota_project_id,
  519. )
  520. def _make_authorization_grant_assertion(self):
  521. """Create the OAuth 2.0 assertion.
  522. This assertion is used during the OAuth 2.0 grant to acquire an
  523. ID token.
  524. Returns:
  525. bytes: The authorization grant assertion.
  526. """
  527. now = _helpers.utcnow()
  528. lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
  529. expiry = now + lifetime
  530. payload = {
  531. "iat": _helpers.datetime_to_secs(now),
  532. "exp": _helpers.datetime_to_secs(expiry),
  533. # The issuer must be the service account email.
  534. "iss": self.service_account_email,
  535. # The audience must be the auth token endpoint's URI
  536. "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
  537. # The target audience specifies which service the ID token is
  538. # intended for.
  539. "target_audience": self._target_audience,
  540. }
  541. payload.update(self._additional_claims)
  542. token = jwt.encode(self._signer, payload)
  543. return token
  544. @_helpers.copy_docstring(credentials.Credentials)
  545. def refresh(self, request):
  546. assertion = self._make_authorization_grant_assertion()
  547. access_token, expiry, _ = _client.id_token_jwt_grant(
  548. request, self._token_uri, assertion
  549. )
  550. self.token = access_token
  551. self.expiry = expiry
  552. @property
  553. def service_account_email(self):
  554. """The service account email."""
  555. return self._service_account_email
  556. @_helpers.copy_docstring(credentials.Signing)
  557. def sign_bytes(self, message):
  558. return self._signer.sign(message)
  559. @property
  560. @_helpers.copy_docstring(credentials.Signing)
  561. def signer(self):
  562. return self._signer
  563. @property
  564. @_helpers.copy_docstring(credentials.Signing)
  565. def signer_email(self):
  566. return self._service_account_email