impersonated_credentials.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. # Copyright 2018 Google Inc.
  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. """Google Cloud Impersonated credentials.
  15. This module provides authentication for applications where local credentials
  16. impersonates a remote service account using `IAM Credentials API`_.
  17. This class can be used to impersonate a service account as long as the original
  18. Credential object has the "Service Account Token Creator" role on the target
  19. service account.
  20. .. _IAM Credentials API:
  21. https://cloud.google.com/iam/credentials/reference/rest/
  22. """
  23. import base64
  24. import copy
  25. from datetime import datetime
  26. import http.client as http_client
  27. import json
  28. from google.auth import _helpers
  29. from google.auth import credentials
  30. from google.auth import exceptions
  31. from google.auth import iam
  32. from google.auth import jwt
  33. from google.auth import metrics
  34. _REFRESH_ERROR = "Unable to acquire impersonated credentials"
  35. _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
  36. def _make_iam_token_request(
  37. request, principal, headers, body, iam_endpoint_override=None
  38. ):
  39. """Makes a request to the Google Cloud IAM service for an access token.
  40. Args:
  41. request (Request): The Request object to use.
  42. principal (str): The principal to request an access token for.
  43. headers (Mapping[str, str]): Map of headers to transmit.
  44. body (Mapping[str, str]): JSON Payload body for the iamcredentials
  45. API call.
  46. iam_endpoint_override (Optiona[str]): The full IAM endpoint override
  47. with the target_principal embedded. This is useful when supporting
  48. impersonation with regional endpoints.
  49. Raises:
  50. google.auth.exceptions.TransportError: Raised if there is an underlying
  51. HTTP connection error
  52. google.auth.exceptions.RefreshError: Raised if the impersonated
  53. credentials are not available. Common reasons are
  54. `iamcredentials.googleapis.com` is not enabled or the
  55. `Service Account Token Creator` is not assigned
  56. """
  57. iam_endpoint = iam_endpoint_override or iam._IAM_ENDPOINT.format(principal)
  58. body = json.dumps(body).encode("utf-8")
  59. response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
  60. # support both string and bytes type response.data
  61. response_body = (
  62. response.data.decode("utf-8")
  63. if hasattr(response.data, "decode")
  64. else response.data
  65. )
  66. if response.status != http_client.OK:
  67. raise exceptions.RefreshError(_REFRESH_ERROR, response_body)
  68. try:
  69. token_response = json.loads(response_body)
  70. token = token_response["accessToken"]
  71. expiry = datetime.strptime(token_response["expireTime"], "%Y-%m-%dT%H:%M:%SZ")
  72. return token, expiry
  73. except (KeyError, ValueError) as caught_exc:
  74. new_exc = exceptions.RefreshError(
  75. "{}: No access token or invalid expiration in response.".format(
  76. _REFRESH_ERROR
  77. ),
  78. response_body,
  79. )
  80. raise new_exc from caught_exc
  81. class Credentials(
  82. credentials.Scoped, credentials.CredentialsWithQuotaProject, credentials.Signing
  83. ):
  84. """This module defines impersonated credentials which are essentially
  85. impersonated identities.
  86. Impersonated Credentials allows credentials issued to a user or
  87. service account to impersonate another. The target service account must
  88. grant the originating credential principal the
  89. `Service Account Token Creator`_ IAM role:
  90. For more information about Token Creator IAM role and
  91. IAMCredentials API, see
  92. `Creating Short-Lived Service Account Credentials`_.
  93. .. _Service Account Token Creator:
  94. https://cloud.google.com/iam/docs/service-accounts#the_service_account_token_creator_role
  95. .. _Creating Short-Lived Service Account Credentials:
  96. https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
  97. Usage:
  98. First grant source_credentials the `Service Account Token Creator`
  99. role on the target account to impersonate. In this example, the
  100. service account represented by svc_account.json has the
  101. token creator role on
  102. `impersonated-account@_project_.iam.gserviceaccount.com`.
  103. Enable the IAMCredentials API on the source project:
  104. `gcloud services enable iamcredentials.googleapis.com`.
  105. Initialize a source credential which does not have access to
  106. list bucket::
  107. from google.oauth2 import service_account
  108. target_scopes = [
  109. 'https://www.googleapis.com/auth/devstorage.read_only']
  110. source_credentials = (
  111. service_account.Credentials.from_service_account_file(
  112. '/path/to/svc_account.json',
  113. scopes=target_scopes))
  114. Now use the source credentials to acquire credentials to impersonate
  115. another service account::
  116. from google.auth import impersonated_credentials
  117. target_credentials = impersonated_credentials.Credentials(
  118. source_credentials=source_credentials,
  119. target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
  120. target_scopes = target_scopes,
  121. lifetime=500)
  122. Resource access is granted::
  123. client = storage.Client(credentials=target_credentials)
  124. buckets = client.list_buckets(project='your_project')
  125. for bucket in buckets:
  126. print(bucket.name)
  127. """
  128. def __init__(
  129. self,
  130. source_credentials,
  131. target_principal,
  132. target_scopes,
  133. delegates=None,
  134. lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
  135. quota_project_id=None,
  136. iam_endpoint_override=None,
  137. ):
  138. """
  139. Args:
  140. source_credentials (google.auth.Credentials): The source credential
  141. used as to acquire the impersonated credentials.
  142. target_principal (str): The service account to impersonate.
  143. target_scopes (Sequence[str]): Scopes to request during the
  144. authorization grant.
  145. delegates (Sequence[str]): The chained list of delegates required
  146. to grant the final access_token. If set, the sequence of
  147. identities must have "Service Account Token Creator" capability
  148. granted to the prceeding identity. For example, if set to
  149. [serviceAccountB, serviceAccountC], the source_credential
  150. must have the Token Creator role on serviceAccountB.
  151. serviceAccountB must have the Token Creator on
  152. serviceAccountC.
  153. Finally, C must have Token Creator on target_principal.
  154. If left unset, source_credential must have that role on
  155. target_principal.
  156. lifetime (int): Number of seconds the delegated credential should
  157. be valid for (upto 3600).
  158. quota_project_id (Optional[str]): The project ID used for quota and billing.
  159. This project may be different from the project used to
  160. create the credentials.
  161. iam_endpoint_override (Optiona[str]): The full IAM endpoint override
  162. with the target_principal embedded. This is useful when supporting
  163. impersonation with regional endpoints.
  164. """
  165. super(Credentials, self).__init__()
  166. self._source_credentials = copy.copy(source_credentials)
  167. # Service account source credentials must have the _IAM_SCOPE
  168. # added to refresh correctly. User credentials cannot have
  169. # their original scopes modified.
  170. if isinstance(self._source_credentials, credentials.Scoped):
  171. self._source_credentials = self._source_credentials.with_scopes(
  172. iam._IAM_SCOPE
  173. )
  174. # If the source credential is service account and self signed jwt
  175. # is needed, we need to create a jwt credential inside it
  176. if (
  177. hasattr(self._source_credentials, "_create_self_signed_jwt")
  178. and self._source_credentials._always_use_jwt_access
  179. ):
  180. self._source_credentials._create_self_signed_jwt(None)
  181. self._target_principal = target_principal
  182. self._target_scopes = target_scopes
  183. self._delegates = delegates
  184. self._lifetime = lifetime or _DEFAULT_TOKEN_LIFETIME_SECS
  185. self.token = None
  186. self.expiry = _helpers.utcnow()
  187. self._quota_project_id = quota_project_id
  188. self._iam_endpoint_override = iam_endpoint_override
  189. def _metric_header_for_usage(self):
  190. return metrics.CRED_TYPE_SA_IMPERSONATE
  191. @_helpers.copy_docstring(credentials.Credentials)
  192. def refresh(self, request):
  193. self._update_token(request)
  194. def _update_token(self, request):
  195. """Updates credentials with a new access_token representing
  196. the impersonated account.
  197. Args:
  198. request (google.auth.transport.requests.Request): Request object
  199. to use for refreshing credentials.
  200. """
  201. # Refresh our source credentials if it is not valid.
  202. if (
  203. self._source_credentials.token_state == credentials.TokenState.STALE
  204. or self._source_credentials.token_state == credentials.TokenState.INVALID
  205. ):
  206. self._source_credentials.refresh(request)
  207. body = {
  208. "delegates": self._delegates,
  209. "scope": self._target_scopes,
  210. "lifetime": str(self._lifetime) + "s",
  211. }
  212. headers = {
  213. "Content-Type": "application/json",
  214. metrics.API_CLIENT_HEADER: metrics.token_request_access_token_impersonate(),
  215. }
  216. # Apply the source credentials authentication info.
  217. self._source_credentials.apply(headers)
  218. self.token, self.expiry = _make_iam_token_request(
  219. request=request,
  220. principal=self._target_principal,
  221. headers=headers,
  222. body=body,
  223. iam_endpoint_override=self._iam_endpoint_override,
  224. )
  225. def sign_bytes(self, message):
  226. from google.auth.transport.requests import AuthorizedSession
  227. iam_sign_endpoint = iam._IAM_SIGN_ENDPOINT.format(self._target_principal)
  228. body = {
  229. "payload": base64.b64encode(message).decode("utf-8"),
  230. "delegates": self._delegates,
  231. }
  232. headers = {"Content-Type": "application/json"}
  233. authed_session = AuthorizedSession(self._source_credentials)
  234. try:
  235. response = authed_session.post(
  236. url=iam_sign_endpoint, headers=headers, json=body
  237. )
  238. finally:
  239. authed_session.close()
  240. if response.status_code != http_client.OK:
  241. raise exceptions.TransportError(
  242. "Error calling sign_bytes: {}".format(response.json())
  243. )
  244. return base64.b64decode(response.json()["signedBlob"])
  245. @property
  246. def signer_email(self):
  247. return self._target_principal
  248. @property
  249. def service_account_email(self):
  250. return self._target_principal
  251. @property
  252. def signer(self):
  253. return self
  254. @property
  255. def requires_scopes(self):
  256. return not self._target_scopes
  257. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  258. def with_quota_project(self, quota_project_id):
  259. return self.__class__(
  260. self._source_credentials,
  261. target_principal=self._target_principal,
  262. target_scopes=self._target_scopes,
  263. delegates=self._delegates,
  264. lifetime=self._lifetime,
  265. quota_project_id=quota_project_id,
  266. iam_endpoint_override=self._iam_endpoint_override,
  267. )
  268. @_helpers.copy_docstring(credentials.Scoped)
  269. def with_scopes(self, scopes, default_scopes=None):
  270. return self.__class__(
  271. self._source_credentials,
  272. target_principal=self._target_principal,
  273. target_scopes=scopes or default_scopes,
  274. delegates=self._delegates,
  275. lifetime=self._lifetime,
  276. quota_project_id=self._quota_project_id,
  277. iam_endpoint_override=self._iam_endpoint_override,
  278. )
  279. class IDTokenCredentials(credentials.CredentialsWithQuotaProject):
  280. """Open ID Connect ID Token-based service account credentials.
  281. """
  282. def __init__(
  283. self,
  284. target_credentials,
  285. target_audience=None,
  286. include_email=False,
  287. quota_project_id=None,
  288. ):
  289. """
  290. Args:
  291. target_credentials (google.auth.Credentials): The target
  292. credential used as to acquire the id tokens for.
  293. target_audience (string): Audience to issue the token for.
  294. include_email (bool): Include email in IdToken
  295. quota_project_id (Optional[str]): The project ID used for
  296. quota and billing.
  297. """
  298. super(IDTokenCredentials, self).__init__()
  299. if not isinstance(target_credentials, Credentials):
  300. raise exceptions.GoogleAuthError(
  301. "Provided Credential must be " "impersonated_credentials"
  302. )
  303. self._target_credentials = target_credentials
  304. self._target_audience = target_audience
  305. self._include_email = include_email
  306. self._quota_project_id = quota_project_id
  307. def from_credentials(self, target_credentials, target_audience=None):
  308. return self.__class__(
  309. target_credentials=target_credentials,
  310. target_audience=target_audience,
  311. include_email=self._include_email,
  312. quota_project_id=self._quota_project_id,
  313. )
  314. def with_target_audience(self, target_audience):
  315. return self.__class__(
  316. target_credentials=self._target_credentials,
  317. target_audience=target_audience,
  318. include_email=self._include_email,
  319. quota_project_id=self._quota_project_id,
  320. )
  321. def with_include_email(self, include_email):
  322. return self.__class__(
  323. target_credentials=self._target_credentials,
  324. target_audience=self._target_audience,
  325. include_email=include_email,
  326. quota_project_id=self._quota_project_id,
  327. )
  328. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  329. def with_quota_project(self, quota_project_id):
  330. return self.__class__(
  331. target_credentials=self._target_credentials,
  332. target_audience=self._target_audience,
  333. include_email=self._include_email,
  334. quota_project_id=quota_project_id,
  335. )
  336. @_helpers.copy_docstring(credentials.Credentials)
  337. def refresh(self, request):
  338. from google.auth.transport.requests import AuthorizedSession
  339. iam_sign_endpoint = iam._IAM_IDTOKEN_ENDPOINT.format(
  340. self._target_credentials.signer_email
  341. )
  342. body = {
  343. "audience": self._target_audience,
  344. "delegates": self._target_credentials._delegates,
  345. "includeEmail": self._include_email,
  346. }
  347. headers = {
  348. "Content-Type": "application/json",
  349. metrics.API_CLIENT_HEADER: metrics.token_request_id_token_impersonate(),
  350. }
  351. authed_session = AuthorizedSession(
  352. self._target_credentials._source_credentials, auth_request=request
  353. )
  354. try:
  355. response = authed_session.post(
  356. url=iam_sign_endpoint,
  357. headers=headers,
  358. data=json.dumps(body).encode("utf-8"),
  359. )
  360. finally:
  361. authed_session.close()
  362. if response.status_code != http_client.OK:
  363. raise exceptions.RefreshError(
  364. "Error getting ID token: {}".format(response.json())
  365. )
  366. id_token = response.json()["token"]
  367. self.token = id_token
  368. self.expiry = datetime.utcfromtimestamp(
  369. jwt.decode(id_token, verify=False)["exp"]
  370. )