blob: 58e1bab069704ce722e09010de819b68182794b6 [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
31import json
32
33import six
34from six.moves import http_client
35
36from google.auth import _helpers
37from google.auth import credentials
38from google.auth import exceptions
salrashid1237a8641a2019-08-07 14:31:33 -070039from google.auth import jwt
40from google.auth.transport.requests import AuthorizedSession
salrashid1231fbc6792018-11-09 11:05:34 -080041
42_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
43
Bu Sun Kim9eec0912019-10-21 17:04:21 -070044_IAM_SCOPE = ["https://www.googleapis.com/auth/iam"]
salrashid1231fbc6792018-11-09 11:05:34 -080045
Bu Sun Kim9eec0912019-10-21 17:04:21 -070046_IAM_ENDPOINT = (
47 "https://iamcredentials.googleapis.com/v1/projects/-"
48 + "/serviceAccounts/{}:generateAccessToken"
49)
salrashid1231fbc6792018-11-09 11:05:34 -080050
Bu Sun Kim9eec0912019-10-21 17:04:21 -070051_IAM_SIGN_ENDPOINT = (
52 "https://iamcredentials.googleapis.com/v1/projects/-"
53 + "/serviceAccounts/{}:signBlob"
54)
salrashid1237a8641a2019-08-07 14:31:33 -070055
Bu Sun Kim9eec0912019-10-21 17:04:21 -070056_IAM_IDTOKEN_ENDPOINT = (
57 "https://iamcredentials.googleapis.com/v1/"
58 + "projects/-/serviceAccounts/{}:generateIdToken"
59)
salrashid1237a8641a2019-08-07 14:31:33 -070060
Bu Sun Kim9eec0912019-10-21 17:04:21 -070061_REFRESH_ERROR = "Unable to acquire impersonated credentials"
salrashid1231fbc6792018-11-09 11:05:34 -080062
salrashid1237a8641a2019-08-07 14:31:33 -070063_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
64
Bu Sun Kim9eec0912019-10-21 17:04:21 -070065_DEFAULT_TOKEN_URI = "https://oauth2.googleapis.com/token"
salrashid1237a8641a2019-08-07 14:31:33 -070066
salrashid1231fbc6792018-11-09 11:05:34 -080067
68def _make_iam_token_request(request, principal, headers, body):
69 """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.
76
77 Raises:
arithmetic17289d5a9a92020-06-03 10:47:36 -070078 google.auth.exceptions.TransportError: Raised if there is an underlying
79 HTTP connection error
80 google.auth.exceptions.RefreshError: Raised if the impersonated
81 credentials are not available. Common reasons are
82 `iamcredentials.googleapis.com` is not enabled or the
83 `Service Account Token Creator` is not assigned
salrashid1231fbc6792018-11-09 11:05:34 -080084 """
85 iam_endpoint = _IAM_ENDPOINT.format(principal)
86
Bu Sun Kima57a7702020-01-10 13:17:34 -080087 body = json.dumps(body).encode("utf-8")
salrashid1231fbc6792018-11-09 11:05:34 -080088
Bu Sun Kim9eec0912019-10-21 17:04:21 -070089 response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
salrashid1231fbc6792018-11-09 11:05:34 -080090
arithmetic17289b7228e2020-05-06 17:11:01 -070091 # support both string and bytes type response.data
arithmetic1728e115bae2020-05-06 16:00:17 -070092 response_body = (
93 response.data.decode("utf-8")
94 if hasattr(response.data, "decode")
95 else response.data
96 )
salrashid1231fbc6792018-11-09 11:05:34 -080097
98 if response.status != http_client.OK:
99 exceptions.RefreshError(_REFRESH_ERROR, response_body)
100
101 try:
arithmetic1728e115bae2020-05-06 16:00:17 -0700102 token_response = json.loads(response_body)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700103 token = token_response["accessToken"]
104 expiry = datetime.strptime(token_response["expireTime"], "%Y-%m-%dT%H:%M:%SZ")
salrashid1231fbc6792018-11-09 11:05:34 -0800105
106 return token, expiry
107
108 except (KeyError, ValueError) as caught_exc:
109 new_exc = exceptions.RefreshError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700110 "{}: No access token or invalid expiration in response.".format(
111 _REFRESH_ERROR
112 ),
113 response_body,
114 )
salrashid1231fbc6792018-11-09 11:05:34 -0800115 six.raise_from(new_exc, caught_exc)
116
117
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700118class Credentials(credentials.Credentials, credentials.Signing):
salrashid1231fbc6792018-11-09 11:05:34 -0800119 """This module defines impersonated credentials which are essentially
120 impersonated identities.
121
122 Impersonated Credentials allows credentials issued to a user or
123 service account to impersonate another. The target service account must
124 grant the originating credential principal the
125 `Service Account Token Creator`_ IAM role:
126
127 For more information about Token Creator IAM role and
128 IAMCredentials API, see
129 `Creating Short-Lived Service Account Credentials`_.
130
131 .. _Service Account Token Creator:
132 https://cloud.google.com/iam/docs/service-accounts#the_service_account_token_creator_role
133
134 .. _Creating Short-Lived Service Account Credentials:
135 https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
136
137 Usage:
138
139 First grant source_credentials the `Service Account Token Creator`
140 role on the target account to impersonate. In this example, the
141 service account represented by svc_account.json has the
142 token creator role on
143 `impersonated-account@_project_.iam.gserviceaccount.com`.
144
salrashid123b29f2622018-11-12 09:49:16 -0800145 Enable the IAMCredentials API on the source project:
146 `gcloud services enable iamcredentials.googleapis.com`.
147
salrashid1231fbc6792018-11-09 11:05:34 -0800148 Initialize a source credential which does not have access to
149 list bucket::
150
151 from google.oauth2 import service_acccount
152
153 target_scopes = [
154 'https://www.googleapis.com/auth/devstorage.read_only']
155
156 source_credentials = (
157 service_account.Credentials.from_service_account_file(
158 '/path/to/svc_account.json',
159 scopes=target_scopes))
160
161 Now use the source credentials to acquire credentials to impersonate
162 another service account::
163
164 from google.auth import impersonated_credentials
165
166 target_credentials = impersonated_credentials.Credentials(
167 source_credentials=source_credentials,
168 target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
169 target_scopes = target_scopes,
170 lifetime=500)
171
172 Resource access is granted::
173
174 client = storage.Client(credentials=target_credentials)
175 buckets = client.list_buckets(project='your_project')
176 for bucket in buckets:
salrashid1237a8641a2019-08-07 14:31:33 -0700177 print(bucket.name)
salrashid1231fbc6792018-11-09 11:05:34 -0800178 """
179
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700180 def __init__(
181 self,
182 source_credentials,
183 target_principal,
184 target_scopes,
185 delegates=None,
186 lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
187 ):
salrashid1231fbc6792018-11-09 11:05:34 -0800188 """
189 Args:
190 source_credentials (google.auth.Credentials): The source credential
191 used as to acquire the impersonated credentials.
192 target_principal (str): The service account to impersonate.
193 target_scopes (Sequence[str]): Scopes to request during the
194 authorization grant.
195 delegates (Sequence[str]): The chained list of delegates required
196 to grant the final access_token. If set, the sequence of
197 identities must have "Service Account Token Creator" capability
198 granted to the prceeding identity. For example, if set to
199 [serviceAccountB, serviceAccountC], the source_credential
200 must have the Token Creator role on serviceAccountB.
salrashid1237a8641a2019-08-07 14:31:33 -0700201 serviceAccountB must have the Token Creator on
202 serviceAccountC.
salrashid1231fbc6792018-11-09 11:05:34 -0800203 Finally, C must have Token Creator on target_principal.
204 If left unset, source_credential must have that role on
205 target_principal.
206 lifetime (int): Number of seconds the delegated credential should
salrashid123b29f2622018-11-12 09:49:16 -0800207 be valid for (upto 3600).
salrashid1231fbc6792018-11-09 11:05:34 -0800208 """
209
210 super(Credentials, self).__init__()
211
212 self._source_credentials = copy.copy(source_credentials)
Bu Sun Kim82e224b2020-03-13 13:21:18 -0700213 # Service account source credentials must have the _IAM_SCOPE
214 # added to refresh correctly. User credentials cannot have
215 # their original scopes modified.
216 if isinstance(self._source_credentials, credentials.Scoped):
217 self._source_credentials = self._source_credentials.with_scopes(_IAM_SCOPE)
salrashid1231fbc6792018-11-09 11:05:34 -0800218 self._target_principal = target_principal
219 self._target_scopes = target_scopes
220 self._delegates = delegates
221 self._lifetime = lifetime
222 self.token = None
223 self.expiry = _helpers.utcnow()
224
225 @_helpers.copy_docstring(credentials.Credentials)
226 def refresh(self, request):
salrashid1231fbc6792018-11-09 11:05:34 -0800227 self._update_token(request)
228
salrashid1231fbc6792018-11-09 11:05:34 -0800229 def _update_token(self, request):
230 """Updates credentials with a new access_token representing
231 the impersonated account.
232
233 Args:
234 request (google.auth.transport.requests.Request): Request object
235 to use for refreshing credentials.
236 """
237
arithmetic1728eb7be3f2020-05-28 11:01:24 -0700238 # Refresh our source credentials if it is not valid.
239 if not self._source_credentials.valid:
240 self._source_credentials.refresh(request)
salrashid1231fbc6792018-11-09 11:05:34 -0800241
salrashid1231fbc6792018-11-09 11:05:34 -0800242 body = {
243 "delegates": self._delegates,
244 "scope": self._target_scopes,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700245 "lifetime": str(self._lifetime) + "s",
salrashid1231fbc6792018-11-09 11:05:34 -0800246 }
247
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700248 headers = {"Content-Type": "application/json"}
salrashid1231fbc6792018-11-09 11:05:34 -0800249
250 # Apply the source credentials authentication info.
251 self._source_credentials.apply(headers)
252
253 self.token, self.expiry = _make_iam_token_request(
254 request=request,
255 principal=self._target_principal,
256 headers=headers,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700257 body=body,
258 )
salrashid1237a8641a2019-08-07 14:31:33 -0700259
260 def sign_bytes(self, message):
261
262 iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)
263
Aniruddha Maruca8d98a2020-05-15 14:52:50 -0700264 body = {
265 "payload": base64.b64encode(message).decode("utf-8"),
266 "delegates": self._delegates,
267 }
salrashid1237a8641a2019-08-07 14:31:33 -0700268
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700269 headers = {"Content-Type": "application/json"}
salrashid1237a8641a2019-08-07 14:31:33 -0700270
271 authed_session = AuthorizedSession(self._source_credentials)
272
273 response = authed_session.post(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700274 url=iam_sign_endpoint, headers=headers, json=body
275 )
salrashid1237a8641a2019-08-07 14:31:33 -0700276
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700277 return base64.b64decode(response.json()["signedBlob"])
salrashid1237a8641a2019-08-07 14:31:33 -0700278
279 @property
280 def signer_email(self):
281 return self._target_principal
282
283 @property
284 def service_account_email(self):
285 return self._target_principal
286
287 @property
288 def signer(self):
289 return self
290
291
292class IDTokenCredentials(credentials.Credentials):
293 """Open ID Connect ID Token-based service account credentials.
294
295 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700296
297 def __init__(self, target_credentials, target_audience=None, include_email=False):
salrashid1237a8641a2019-08-07 14:31:33 -0700298 """
299 Args:
300 target_credentials (google.auth.Credentials): The target
301 credential used as to acquire the id tokens for.
302 target_audience (string): Audience to issue the token for.
303 include_email (bool): Include email in IdToken
304 """
305 super(IDTokenCredentials, self).__init__()
306
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700307 if not isinstance(target_credentials, Credentials):
308 raise exceptions.GoogleAuthError(
309 "Provided Credential must be " "impersonated_credentials"
310 )
salrashid1237a8641a2019-08-07 14:31:33 -0700311 self._target_credentials = target_credentials
312 self._target_audience = target_audience
313 self._include_email = include_email
314
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700315 def from_credentials(self, target_credentials, target_audience=None):
salrashid1237a8641a2019-08-07 14:31:33 -0700316 return self.__class__(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700317 target_credentials=self._target_credentials, target_audience=target_audience
318 )
salrashid1237a8641a2019-08-07 14:31:33 -0700319
320 def with_target_audience(self, target_audience):
321 return self.__class__(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700322 target_credentials=self._target_credentials, target_audience=target_audience
323 )
salrashid1237a8641a2019-08-07 14:31:33 -0700324
325 def with_include_email(self, include_email):
326 return self.__class__(
327 target_credentials=self._target_credentials,
328 target_audience=self._target_audience,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700329 include_email=include_email,
330 )
salrashid1237a8641a2019-08-07 14:31:33 -0700331
332 @_helpers.copy_docstring(credentials.Credentials)
333 def refresh(self, request):
334
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700335 iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(
336 self._target_credentials.signer_email
337 )
salrashid1237a8641a2019-08-07 14:31:33 -0700338
339 body = {
340 "audience": self._target_audience,
341 "delegates": self._target_credentials._delegates,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700342 "includeEmail": self._include_email,
salrashid1237a8641a2019-08-07 14:31:33 -0700343 }
344
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700345 headers = {"Content-Type": "application/json"}
salrashid1237a8641a2019-08-07 14:31:33 -0700346
arithmetic1728eb7be3f2020-05-28 11:01:24 -0700347 authed_session = AuthorizedSession(
348 self._target_credentials._source_credentials, auth_request=request
349 )
salrashid1237a8641a2019-08-07 14:31:33 -0700350
351 response = authed_session.post(
352 url=iam_sign_endpoint,
353 headers=headers,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700354 data=json.dumps(body).encode("utf-8"),
355 )
salrashid1237a8641a2019-08-07 14:31:33 -0700356
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700357 id_token = response.json()["token"]
salrashid1237a8641a2019-08-07 14:31:33 -0700358 self.token = id_token
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700359 self.expiry = datetime.fromtimestamp(jwt.decode(id_token, verify=False)["exp"])