blob: c2351e7f71e94ff76439f6adce7cd7b4b3491bbd [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:
78 TransportError: Raised if there is an underlying HTTP connection
79 Error
80 DefaultCredentialsError: Raised if the impersonated credentials
81 are not available. Common reasons are
82 `iamcredentials.googleapis.com` is not enabled or the
83 `Service Account Token Creator` is not assigned
84 """
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
arithmetic1728e115bae2020-05-06 16:00:17 -070091 response_body = (
92 response.data.decode("utf-8")
93 if hasattr(response.data, "decode")
94 else response.data
95 )
salrashid1231fbc6792018-11-09 11:05:34 -080096
97 if response.status != http_client.OK:
98 exceptions.RefreshError(_REFRESH_ERROR, response_body)
99
100 try:
arithmetic1728e115bae2020-05-06 16:00:17 -0700101 token_response = json.loads(response_body)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700102 token = token_response["accessToken"]
103 expiry = datetime.strptime(token_response["expireTime"], "%Y-%m-%dT%H:%M:%SZ")
salrashid1231fbc6792018-11-09 11:05:34 -0800104
105 return token, expiry
106
107 except (KeyError, ValueError) as caught_exc:
108 new_exc = exceptions.RefreshError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700109 "{}: No access token or invalid expiration in response.".format(
110 _REFRESH_ERROR
111 ),
112 response_body,
113 )
salrashid1231fbc6792018-11-09 11:05:34 -0800114 six.raise_from(new_exc, caught_exc)
115
116
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700117class Credentials(credentials.Credentials, credentials.Signing):
salrashid1231fbc6792018-11-09 11:05:34 -0800118 """This module defines impersonated credentials which are essentially
119 impersonated identities.
120
121 Impersonated Credentials allows credentials issued to a user or
122 service account to impersonate another. The target service account must
123 grant the originating credential principal the
124 `Service Account Token Creator`_ IAM role:
125
126 For more information about Token Creator IAM role and
127 IAMCredentials API, see
128 `Creating Short-Lived Service Account Credentials`_.
129
130 .. _Service Account Token Creator:
131 https://cloud.google.com/iam/docs/service-accounts#the_service_account_token_creator_role
132
133 .. _Creating Short-Lived Service Account Credentials:
134 https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
135
136 Usage:
137
138 First grant source_credentials the `Service Account Token Creator`
139 role on the target account to impersonate. In this example, the
140 service account represented by svc_account.json has the
141 token creator role on
142 `impersonated-account@_project_.iam.gserviceaccount.com`.
143
salrashid123b29f2622018-11-12 09:49:16 -0800144 Enable the IAMCredentials API on the source project:
145 `gcloud services enable iamcredentials.googleapis.com`.
146
salrashid1231fbc6792018-11-09 11:05:34 -0800147 Initialize a source credential which does not have access to
148 list bucket::
149
150 from google.oauth2 import service_acccount
151
152 target_scopes = [
153 'https://www.googleapis.com/auth/devstorage.read_only']
154
155 source_credentials = (
156 service_account.Credentials.from_service_account_file(
157 '/path/to/svc_account.json',
158 scopes=target_scopes))
159
160 Now use the source credentials to acquire credentials to impersonate
161 another service account::
162
163 from google.auth import impersonated_credentials
164
165 target_credentials = impersonated_credentials.Credentials(
166 source_credentials=source_credentials,
167 target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
168 target_scopes = target_scopes,
169 lifetime=500)
170
171 Resource access is granted::
172
173 client = storage.Client(credentials=target_credentials)
174 buckets = client.list_buckets(project='your_project')
175 for bucket in buckets:
salrashid1237a8641a2019-08-07 14:31:33 -0700176 print(bucket.name)
salrashid1231fbc6792018-11-09 11:05:34 -0800177 """
178
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700179 def __init__(
180 self,
181 source_credentials,
182 target_principal,
183 target_scopes,
184 delegates=None,
185 lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
186 ):
salrashid1231fbc6792018-11-09 11:05:34 -0800187 """
188 Args:
189 source_credentials (google.auth.Credentials): The source credential
190 used as to acquire the impersonated credentials.
191 target_principal (str): The service account to impersonate.
192 target_scopes (Sequence[str]): Scopes to request during the
193 authorization grant.
194 delegates (Sequence[str]): The chained list of delegates required
195 to grant the final access_token. If set, the sequence of
196 identities must have "Service Account Token Creator" capability
197 granted to the prceeding identity. For example, if set to
198 [serviceAccountB, serviceAccountC], the source_credential
199 must have the Token Creator role on serviceAccountB.
salrashid1237a8641a2019-08-07 14:31:33 -0700200 serviceAccountB must have the Token Creator on
201 serviceAccountC.
salrashid1231fbc6792018-11-09 11:05:34 -0800202 Finally, C must have Token Creator on target_principal.
203 If left unset, source_credential must have that role on
204 target_principal.
205 lifetime (int): Number of seconds the delegated credential should
salrashid123b29f2622018-11-12 09:49:16 -0800206 be valid for (upto 3600).
salrashid1231fbc6792018-11-09 11:05:34 -0800207 """
208
209 super(Credentials, self).__init__()
210
211 self._source_credentials = copy.copy(source_credentials)
Bu Sun Kim82e224b2020-03-13 13:21:18 -0700212 # Service account source credentials must have the _IAM_SCOPE
213 # added to refresh correctly. User credentials cannot have
214 # their original scopes modified.
215 if isinstance(self._source_credentials, credentials.Scoped):
216 self._source_credentials = self._source_credentials.with_scopes(_IAM_SCOPE)
salrashid1231fbc6792018-11-09 11:05:34 -0800217 self._target_principal = target_principal
218 self._target_scopes = target_scopes
219 self._delegates = delegates
220 self._lifetime = lifetime
221 self.token = None
222 self.expiry = _helpers.utcnow()
223
224 @_helpers.copy_docstring(credentials.Credentials)
225 def refresh(self, request):
salrashid1231fbc6792018-11-09 11:05:34 -0800226 self._update_token(request)
227
228 @property
229 def expired(self):
230 return _helpers.utcnow() >= self.expiry
231
232 def _update_token(self, request):
233 """Updates credentials with a new access_token representing
234 the impersonated account.
235
236 Args:
237 request (google.auth.transport.requests.Request): Request object
238 to use for refreshing credentials.
239 """
240
241 # Refresh our source credentials.
242 self._source_credentials.refresh(request)
243
salrashid1231fbc6792018-11-09 11:05:34 -0800244 body = {
245 "delegates": self._delegates,
246 "scope": self._target_scopes,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700247 "lifetime": str(self._lifetime) + "s",
salrashid1231fbc6792018-11-09 11:05:34 -0800248 }
249
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700250 headers = {"Content-Type": "application/json"}
salrashid1231fbc6792018-11-09 11:05:34 -0800251
252 # Apply the source credentials authentication info.
253 self._source_credentials.apply(headers)
254
255 self.token, self.expiry = _make_iam_token_request(
256 request=request,
257 principal=self._target_principal,
258 headers=headers,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700259 body=body,
260 )
salrashid1237a8641a2019-08-07 14:31:33 -0700261
262 def sign_bytes(self, message):
263
264 iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal)
265
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700266 body = {"payload": base64.b64encode(message), "delegates": self._delegates}
salrashid1237a8641a2019-08-07 14:31:33 -0700267
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700268 headers = {"Content-Type": "application/json"}
salrashid1237a8641a2019-08-07 14:31:33 -0700269
270 authed_session = AuthorizedSession(self._source_credentials)
271
272 response = authed_session.post(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700273 url=iam_sign_endpoint, headers=headers, json=body
274 )
salrashid1237a8641a2019-08-07 14:31:33 -0700275
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700276 return base64.b64decode(response.json()["signedBlob"])
salrashid1237a8641a2019-08-07 14:31:33 -0700277
278 @property
279 def signer_email(self):
280 return self._target_principal
281
282 @property
283 def service_account_email(self):
284 return self._target_principal
285
286 @property
287 def signer(self):
288 return self
289
290
291class IDTokenCredentials(credentials.Credentials):
292 """Open ID Connect ID Token-based service account credentials.
293
294 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700295
296 def __init__(self, target_credentials, target_audience=None, include_email=False):
salrashid1237a8641a2019-08-07 14:31:33 -0700297 """
298 Args:
299 target_credentials (google.auth.Credentials): The target
300 credential used as to acquire the id tokens for.
301 target_audience (string): Audience to issue the token for.
302 include_email (bool): Include email in IdToken
303 """
304 super(IDTokenCredentials, self).__init__()
305
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700306 if not isinstance(target_credentials, Credentials):
307 raise exceptions.GoogleAuthError(
308 "Provided Credential must be " "impersonated_credentials"
309 )
salrashid1237a8641a2019-08-07 14:31:33 -0700310 self._target_credentials = target_credentials
311 self._target_audience = target_audience
312 self._include_email = include_email
313
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700314 def from_credentials(self, target_credentials, target_audience=None):
salrashid1237a8641a2019-08-07 14:31:33 -0700315 return self.__class__(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700316 target_credentials=self._target_credentials, target_audience=target_audience
317 )
salrashid1237a8641a2019-08-07 14:31:33 -0700318
319 def with_target_audience(self, target_audience):
320 return self.__class__(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700321 target_credentials=self._target_credentials, target_audience=target_audience
322 )
salrashid1237a8641a2019-08-07 14:31:33 -0700323
324 def with_include_email(self, include_email):
325 return self.__class__(
326 target_credentials=self._target_credentials,
327 target_audience=self._target_audience,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700328 include_email=include_email,
329 )
salrashid1237a8641a2019-08-07 14:31:33 -0700330
331 @_helpers.copy_docstring(credentials.Credentials)
332 def refresh(self, request):
333
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700334 iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format(
335 self._target_credentials.signer_email
336 )
salrashid1237a8641a2019-08-07 14:31:33 -0700337
338 body = {
339 "audience": self._target_audience,
340 "delegates": self._target_credentials._delegates,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700341 "includeEmail": self._include_email,
salrashid1237a8641a2019-08-07 14:31:33 -0700342 }
343
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700344 headers = {"Content-Type": "application/json"}
salrashid1237a8641a2019-08-07 14:31:33 -0700345
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700346 authed_session = AuthorizedSession(self._target_credentials._source_credentials)
salrashid1237a8641a2019-08-07 14:31:33 -0700347
348 response = authed_session.post(
349 url=iam_sign_endpoint,
350 headers=headers,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700351 data=json.dumps(body).encode("utf-8"),
352 )
salrashid1237a8641a2019-08-07 14:31:33 -0700353
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700354 id_token = response.json()["token"]
salrashid1237a8641a2019-08-07 14:31:33 -0700355 self.token = id_token
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700356 self.expiry = datetime.fromtimestamp(jwt.decode(id_token, verify=False)["exp"])