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