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