impersonated_credentials.py 17 KB

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