blob: 2704bfdd242c1fd1f73809677a7f1ff1cabaa016 [file] [log] [blame]
salrashid1231fbc6792018-11-09 11:05:34 -08001# 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
15"""Google Cloud Impersonated credentials.
16
17This module provides authentication for applications where local credentials
18impersonates a remote service account using `IAM Credentials API`_.
19
20This class can be used to impersonate a service account as long as the original
21Credential object has the "Service Account Token Creator" role on the target
22service account.
23
24 .. _IAM Credentials API:
25 https://cloud.google.com/iam/credentials/reference/rest/
26"""
27
salrashid1237a8641a2019-08-07 14:31:33 -070028import base64
salrashid1231fbc6792018-11-09 11:05:34 -080029import copy
30from datetime import datetime
Tres Seaver560cf1e2021-08-03 16:35:54 -040031import http.client
salrashid1231fbc6792018-11-09 11:05:34 -080032import json
33
salrashid1231fbc6792018-11-09 11:05:34 -080034from google.auth import _helpers
35from google.auth import credentials
36from google.auth import exceptions
salrashid1237a8641a2019-08-07 14:31:33 -070037from google.auth import jwt
38from google.auth.transport.requests import AuthorizedSession
salrashid1231fbc6792018-11-09 11:05:34 -080039
40_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
41
Bu Sun Kim9eec0912019-10-21 17:04:21 -070042_IAM_SCOPE = ["https://www.googleapis.com/auth/iam"]
salrashid1231fbc6792018-11-09 11:05:34 -080043
Bu Sun Kim9eec0912019-10-21 17:04:21 -070044_IAM_ENDPOINT = (
45 "https://iamcredentials.googleapis.com/v1/projects/-"
46 + "/serviceAccounts/{}:generateAccessToken"
47)
salrashid1231fbc6792018-11-09 11:05:34 -080048
Bu Sun Kim9eec0912019-10-21 17:04:21 -070049_IAM_SIGN_ENDPOINT = (
50 "https://iamcredentials.googleapis.com/v1/projects/-"
51 + "/serviceAccounts/{}:signBlob"
52)
salrashid1237a8641a2019-08-07 14:31:33 -070053
Bu Sun Kim9eec0912019-10-21 17:04:21 -070054_IAM_IDTOKEN_ENDPOINT = (
55 "https://iamcredentials.googleapis.com/v1/"
56 + "projects/-/serviceAccounts/{}:generateIdToken"
57)
salrashid1237a8641a2019-08-07 14:31:33 -070058
Bu Sun Kim9eec0912019-10-21 17:04:21 -070059_REFRESH_ERROR = "Unable to acquire impersonated credentials"
salrashid1231fbc6792018-11-09 11:05:34 -080060
salrashid1237a8641a2019-08-07 14:31:33 -070061_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
62
Bu Sun Kim9eec0912019-10-21 17:04:21 -070063_DEFAULT_TOKEN_URI = "https://oauth2.googleapis.com/token"
salrashid1237a8641a2019-08-07 14:31:33 -070064
salrashid1231fbc6792018-11-09 11:05:34 -080065
bojeil-googled4d7f382021-02-16 12:33:20 -080066def _make_iam_token_request(
67 request, principal, headers, body, iam_endpoint_override=None
68):
salrashid1231fbc6792018-11-09 11:05:34 -080069 """Makes a request to the Google Cloud IAM service for an access token.
70 Args:
71 request (Request): The Request object to use.
72 principal (str): The principal to request an access token for.
73 headers (Mapping[str, str]): Map of headers to transmit.
74 body (Mapping[str, str]): JSON Payload body for the iamcredentials
75 API call.
bojeil-googled4d7f382021-02-16 12:33:20 -080076 iam_endpoint_override (Optiona[str]): The full IAM endpoint override
77 with the target_principal embedded. This is useful when supporting
78 impersonation with regional endpoints.
salrashid1231fbc6792018-11-09 11:05:34 -080079
80 Raises:
arithmetic17289d5a9a92020-06-03 10:47:36 -070081 google.auth.exceptions.TransportError: Raised if there is an underlying
82 HTTP connection error
83 google.auth.exceptions.RefreshError: Raised if the impersonated
84 credentials are not available. Common reasons are
85 `iamcredentials.googleapis.com` is not enabled or the
86 `Service Account Token Creator` is not assigned
salrashid1231fbc6792018-11-09 11:05:34 -080087 """
bojeil-googled4d7f382021-02-16 12:33:20 -080088 iam_endpoint = iam_endpoint_override or _IAM_ENDPOINT.format(principal)
salrashid1231fbc6792018-11-09 11:05:34 -080089
Bu Sun Kima57a7702020-01-10 13:17:34 -080090 body = json.dumps(body).encode("utf-8")
salrashid1231fbc6792018-11-09 11:05:34 -080091
Bu Sun Kim9eec0912019-10-21 17:04:21 -070092 response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
salrashid1231fbc6792018-11-09 11:05:34 -080093
arithmetic17289b7228e2020-05-06 17:11:01 -070094 # support both string and bytes type response.data
arithmetic1728e115bae2020-05-06 16:00:17 -070095 response_body = (
96 response.data.decode("utf-8")
97 if hasattr(response.data, "decode")
98 else response.data
99 )
salrashid1231fbc6792018-11-09 11:05:34 -0800100
Tres Seaver560cf1e2021-08-03 16:35:54 -0400101 if response.status != http.client.OK:
salrashid1231fbc6792018-11-09 11:05:34 -0800102 exceptions.RefreshError(_REFRESH_ERROR, response_body)
103
104 try:
arithmetic1728e115bae2020-05-06 16:00:17 -0700105 token_response = json.loads(response_body)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700106 token = token_response["accessToken"]
107 expiry = datetime.strptime(token_response["expireTime"], "%Y-%m-%dT%H:%M:%SZ")
salrashid1231fbc6792018-11-09 11:05:34 -0800108
109 return token, expiry
110
111 except (KeyError, ValueError) as caught_exc:
112 new_exc = exceptions.RefreshError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700113 "{}: No access token or invalid expiration in response.".format(
114 _REFRESH_ERROR
115 ),
116 response_body,
117 )
Tres Seaver560cf1e2021-08-03 16:35:54 -0400118 raise new_exc from caught_exc
salrashid1231fbc6792018-11-09 11:05:34 -0800119
120
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600121class Credentials(credentials.CredentialsWithQuotaProject, credentials.Signing):
salrashid1231fbc6792018-11-09 11:05:34 -0800122 """This module defines impersonated credentials which are essentially
123 impersonated identities.
124
125 Impersonated Credentials allows credentials issued to a user or
126 service account to impersonate another. The target service account must
127 grant the originating credential principal the
128 `Service Account Token Creator`_ IAM role:
129
130 For more information about Token Creator IAM role and
131 IAMCredentials API, see
132 `Creating Short-Lived Service Account Credentials`_.
133
134 .. _Service Account Token Creator:
135 https://cloud.google.com/iam/docs/service-accounts#the_service_account_token_creator_role
136
137 .. _Creating Short-Lived Service Account Credentials:
138 https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
139
140 Usage:
141
142 First grant source_credentials the `Service Account Token Creator`
143 role on the target account to impersonate. In this example, the
144 service account represented by svc_account.json has the
145 token creator role on
146 `impersonated-account@_project_.iam.gserviceaccount.com`.
147
salrashid123b29f2622018-11-12 09:49:16 -0800148 Enable the IAMCredentials API on the source project:
149 `gcloud services enable iamcredentials.googleapis.com`.
150
salrashid1231fbc6792018-11-09 11:05:34 -0800151 Initialize a source credential which does not have access to
152 list bucket::
153
Bu Sun Kim3319ea82020-12-07 11:00:03 -0700154 from google.oauth2 import service_account
salrashid1231fbc6792018-11-09 11:05:34 -0800155
156 target_scopes = [
157 'https://www.googleapis.com/auth/devstorage.read_only']
158
159 source_credentials = (
160 service_account.Credentials.from_service_account_file(
161 '/path/to/svc_account.json',
162 scopes=target_scopes))
163
164 Now use the source credentials to acquire credentials to impersonate
165 another service account::
166
167 from google.auth import impersonated_credentials
168
169 target_credentials = impersonated_credentials.Credentials(
170 source_credentials=source_credentials,
171 target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
172 target_scopes = target_scopes,
173 lifetime=500)
174
175 Resource access is granted::
176
177 client = storage.Client(credentials=target_credentials)
178 buckets = client.list_buckets(project='your_project')
179 for bucket in buckets:
salrashid1237a8641a2019-08-07 14:31:33 -0700180 print(bucket.name)
salrashid1231fbc6792018-11-09 11:05:34 -0800181 """
182
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700183 def __init__(
184 self,
185 source_credentials,
186 target_principal,
187 target_scopes,
188 delegates=None,
189 lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700190 quota_project_id=None,
bojeil-googled4d7f382021-02-16 12:33:20 -0800191 iam_endpoint_override=None,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700192 ):
salrashid1231fbc6792018-11-09 11:05:34 -0800193 """
194 Args:
195 source_credentials (google.auth.Credentials): The source credential
196 used as to acquire the impersonated credentials.
197 target_principal (str): The service account to impersonate.
198 target_scopes (Sequence[str]): Scopes to request during the
199 authorization grant.
200 delegates (Sequence[str]): The chained list of delegates required
201 to grant the final access_token. If set, the sequence of
202 identities must have "Service Account Token Creator" capability
203 granted to the prceeding identity. For example, if set to
204 [serviceAccountB, serviceAccountC], the source_credential
205 must have the Token Creator role on serviceAccountB.
salrashid1237a8641a2019-08-07 14:31:33 -0700206 serviceAccountB must have the Token Creator on
207 serviceAccountC.
salrashid1231fbc6792018-11-09 11:05:34 -0800208 Finally, C must have Token Creator on target_principal.
209 If left unset, source_credential must have that role on
210 target_principal.
211 lifetime (int): Number of seconds the delegated credential should
salrashid123b29f2622018-11-12 09:49:16 -0800212 be valid for (upto 3600).
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700213 quota_project_id (Optional[str]): The project ID used for quota and billing.
214 This project may be different from the project used to
215 create the credentials.
bojeil-googled4d7f382021-02-16 12:33:20 -0800216 iam_endpoint_override (Optiona[str]): The full IAM endpoint override
217 with the target_principal embedded. This is useful when supporting
218 impersonation with regional endpoints.
salrashid1231fbc6792018-11-09 11:05:34 -0800219 """
220
221 super(Credentials, self).__init__()
222
223 self._source_credentials = copy.copy(source_credentials)
Bu Sun Kim82e224b2020-03-13 13:21:18 -0700224 # Service account source credentials must have the _IAM_SCOPE
225 # added to refresh correctly. User credentials cannot have
226 # their original scopes modified.
227 if isinstance(self._source_credentials, credentials.Scoped):
228 self._source_credentials = self._source_credentials.with_scopes(_IAM_SCOPE)
salrashid1231fbc6792018-11-09 11:05:34 -0800229 self._target_principal = target_principal
230 self._target_scopes = target_scopes
231 self._delegates = delegates
232 self._lifetime = lifetime
233 self.token = None
234 self.expiry = _helpers.utcnow()
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700235 self._quota_project_id = quota_project_id
bojeil-googled4d7f382021-02-16 12:33:20 -0800236 self._iam_endpoint_override = iam_endpoint_override
salrashid1231fbc6792018-11-09 11:05:34 -0800237
238 @_helpers.copy_docstring(credentials.Credentials)
239 def refresh(self, request):
salrashid1231fbc6792018-11-09 11:05:34 -0800240 self._update_token(request)
241
salrashid1231fbc6792018-11-09 11:05:34 -0800242 def _update_token(self, request):
243 """Updates credentials with a new access_token representing
244 the impersonated account.
245
246 Args:
247 request (google.auth.transport.requests.Request): Request object
248 to use for refreshing credentials.
249 """
250
arithmetic1728eb7be3f2020-05-28 11:01:24 -0700251 # Refresh our source credentials if it is not valid.
252 if not self._source_credentials.valid:
253 self._source_credentials.refresh(request)
salrashid1231fbc6792018-11-09 11:05:34 -0800254
salrashid1231fbc6792018-11-09 11:05:34 -0800255 body = {
256 "delegates": self._delegates,
257 "scope": self._target_scopes,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700258 "lifetime": str(self._lifetime) + "s",
salrashid1231fbc6792018-11-09 11:05:34 -0800259 }
260
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700261 headers = {"Content-Type": "application/json"}
salrashid1231fbc6792018-11-09 11:05:34 -0800262
263 # Apply the source credentials authentication info.
264 self._source_credentials.apply(headers)
265
266 self.token, self.expiry = _make_iam_token_request(
267 request=request,
268 principal=self._target_principal,
269 headers=headers,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700270 body=body,
bojeil-googled4d7f382021-02-16 12:33:20 -0800271 iam_endpoint_override=self._iam_endpoint_override,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700272 )
salrashid1237a8641a2019-08-07 14:31:33 -0700273
274 def sign_bytes(self, message):
275
276 iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)
277
Aniruddha Maruca8d98a2020-05-15 14:52:50 -0700278 body = {
279 "payload": base64.b64encode(message).decode("utf-8"),
280 "delegates": self._delegates,
281 }
salrashid1237a8641a2019-08-07 14:31:33 -0700282
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700283 headers = {"Content-Type": "application/json"}
salrashid1237a8641a2019-08-07 14:31:33 -0700284
285 authed_session = AuthorizedSession(self._source_credentials)
286
287 response = authed_session.post(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700288 url=iam_sign_endpoint, headers=headers, json=body
289 )
salrashid1237a8641a2019-08-07 14:31:33 -0700290
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700291 return base64.b64decode(response.json()["signedBlob"])
salrashid1237a8641a2019-08-07 14:31:33 -0700292
293 @property
294 def signer_email(self):
295 return self._target_principal
296
297 @property
298 def service_account_email(self):
299 return self._target_principal
300
301 @property
302 def signer(self):
303 return self
304
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600305 @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700306 def with_quota_project(self, quota_project_id):
307 return self.__class__(
308 self._source_credentials,
309 target_principal=self._target_principal,
310 target_scopes=self._target_scopes,
311 delegates=self._delegates,
312 lifetime=self._lifetime,
313 quota_project_id=quota_project_id,
bojeil-googled4d7f382021-02-16 12:33:20 -0800314 iam_endpoint_override=self._iam_endpoint_override,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700315 )
316
salrashid1237a8641a2019-08-07 14:31:33 -0700317
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600318class IDTokenCredentials(credentials.CredentialsWithQuotaProject):
salrashid1237a8641a2019-08-07 14:31:33 -0700319 """Open ID Connect ID Token-based service account credentials.
320
321 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700322
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700323 def __init__(
324 self,
325 target_credentials,
326 target_audience=None,
327 include_email=False,
328 quota_project_id=None,
329 ):
salrashid1237a8641a2019-08-07 14:31:33 -0700330 """
331 Args:
332 target_credentials (google.auth.Credentials): The target
333 credential used as to acquire the id tokens for.
334 target_audience (string): Audience to issue the token for.
335 include_email (bool): Include email in IdToken
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700336 quota_project_id (Optional[str]): The project ID used for
337 quota and billing.
salrashid1237a8641a2019-08-07 14:31:33 -0700338 """
339 super(IDTokenCredentials, self).__init__()
340
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700341 if not isinstance(target_credentials, Credentials):
342 raise exceptions.GoogleAuthError(
343 "Provided Credential must be " "impersonated_credentials"
344 )
salrashid1237a8641a2019-08-07 14:31:33 -0700345 self._target_credentials = target_credentials
346 self._target_audience = target_audience
347 self._include_email = include_email
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700348 self._quota_project_id = quota_project_id
salrashid1237a8641a2019-08-07 14:31:33 -0700349
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700350 def from_credentials(self, target_credentials, target_audience=None):
salrashid1237a8641a2019-08-07 14:31:33 -0700351 return self.__class__(
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700352 target_credentials=self._target_credentials,
353 target_audience=target_audience,
Pietro De Nicolaofd9b5b12020-12-11 20:00:30 +0100354 include_email=self._include_email,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700355 quota_project_id=self._quota_project_id,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700356 )
salrashid1237a8641a2019-08-07 14:31:33 -0700357
358 def with_target_audience(self, target_audience):
359 return self.__class__(
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700360 target_credentials=self._target_credentials,
361 target_audience=target_audience,
Pietro De Nicolaofd9b5b12020-12-11 20:00:30 +0100362 include_email=self._include_email,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700363 quota_project_id=self._quota_project_id,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700364 )
salrashid1237a8641a2019-08-07 14:31:33 -0700365
366 def with_include_email(self, include_email):
367 return self.__class__(
368 target_credentials=self._target_credentials,
369 target_audience=self._target_audience,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700370 include_email=include_email,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700371 quota_project_id=self._quota_project_id,
372 )
373
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600374 @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700375 def with_quota_project(self, quota_project_id):
376 return self.__class__(
377 target_credentials=self._target_credentials,
378 target_audience=self._target_audience,
379 include_email=self._include_email,
380 quota_project_id=quota_project_id,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700381 )
salrashid1237a8641a2019-08-07 14:31:33 -0700382
383 @_helpers.copy_docstring(credentials.Credentials)
384 def refresh(self, request):
385
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700386 iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(
387 self._target_credentials.signer_email
388 )
salrashid1237a8641a2019-08-07 14:31:33 -0700389
390 body = {
391 "audience": self._target_audience,
392 "delegates": self._target_credentials._delegates,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700393 "includeEmail": self._include_email,
salrashid1237a8641a2019-08-07 14:31:33 -0700394 }
395
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700396 headers = {"Content-Type": "application/json"}
salrashid1237a8641a2019-08-07 14:31:33 -0700397
arithmetic1728eb7be3f2020-05-28 11:01:24 -0700398 authed_session = AuthorizedSession(
399 self._target_credentials._source_credentials, auth_request=request
400 )
salrashid1237a8641a2019-08-07 14:31:33 -0700401
402 response = authed_session.post(
403 url=iam_sign_endpoint,
404 headers=headers,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700405 data=json.dumps(body).encode("utf-8"),
406 )
salrashid1237a8641a2019-08-07 14:31:33 -0700407
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700408 id_token = response.json()["token"]
salrashid1237a8641a2019-08-07 14:31:33 -0700409 self.token = id_token
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700410 self.expiry = datetime.fromtimestamp(jwt.decode(id_token, verify=False)["exp"])