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 | |
Bu Sun Kim | a57a770 | 2020-01-10 13:17:34 -0800 | [diff] [blame] | 87 | body = json.dumps(body).encode("utf-8") |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 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 | |
arithmetic1728 | e115bae | 2020-05-06 16:00:17 -0700 | [diff] [blame^] | 91 | response_body = ( |
| 92 | response.data.decode("utf-8") |
| 93 | if hasattr(response.data, "decode") |
| 94 | else response.data |
| 95 | ) |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 96 | |
| 97 | if response.status != http_client.OK: |
| 98 | exceptions.RefreshError(_REFRESH_ERROR, response_body) |
| 99 | |
| 100 | try: |
arithmetic1728 | e115bae | 2020-05-06 16:00:17 -0700 | [diff] [blame^] | 101 | token_response = json.loads(response_body) |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 102 | token = token_response["accessToken"] |
| 103 | expiry = datetime.strptime(token_response["expireTime"], "%Y-%m-%dT%H:%M:%SZ") |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 104 | |
| 105 | return token, expiry |
| 106 | |
| 107 | except (KeyError, ValueError) as caught_exc: |
| 108 | new_exc = exceptions.RefreshError( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 109 | "{}: No access token or invalid expiration in response.".format( |
| 110 | _REFRESH_ERROR |
| 111 | ), |
| 112 | response_body, |
| 113 | ) |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 114 | six.raise_from(new_exc, caught_exc) |
| 115 | |
| 116 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 117 | class Credentials(credentials.Credentials, credentials.Signing): |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 118 | """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 | |
salrashid123 | b29f262 | 2018-11-12 09:49:16 -0800 | [diff] [blame] | 144 | Enable the IAMCredentials API on the source project: |
| 145 | `gcloud services enable iamcredentials.googleapis.com`. |
| 146 | |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 147 | 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: |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 176 | print(bucket.name) |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 177 | """ |
| 178 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 179 | def __init__( |
| 180 | self, |
| 181 | source_credentials, |
| 182 | target_principal, |
| 183 | target_scopes, |
| 184 | delegates=None, |
| 185 | lifetime=_DEFAULT_TOKEN_LIFETIME_SECS, |
| 186 | ): |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 187 | """ |
| 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. |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 200 | serviceAccountB must have the Token Creator on |
| 201 | serviceAccountC. |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 202 | 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 |
salrashid123 | b29f262 | 2018-11-12 09:49:16 -0800 | [diff] [blame] | 206 | be valid for (upto 3600). |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 207 | """ |
| 208 | |
| 209 | super(Credentials, self).__init__() |
| 210 | |
| 211 | self._source_credentials = copy.copy(source_credentials) |
Bu Sun Kim | 82e224b | 2020-03-13 13:21:18 -0700 | [diff] [blame] | 212 | # 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) |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 217 | 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): |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 226 | 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 | |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 244 | body = { |
| 245 | "delegates": self._delegates, |
| 246 | "scope": self._target_scopes, |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 247 | "lifetime": str(self._lifetime) + "s", |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 248 | } |
| 249 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 250 | headers = {"Content-Type": "application/json"} |
salrashid123 | 1fbc679 | 2018-11-09 11:05:34 -0800 | [diff] [blame] | 251 | |
| 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 259 | body=body, |
| 260 | ) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 261 | |
| 262 | def sign_bytes(self, message): |
| 263 | |
| 264 | iam_sign_endpoint = _IAM_SIGN_ENDPOINT.format(self._target_principal) |
| 265 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 266 | body = {"payload": base64.b64encode(message), "delegates": self._delegates} |
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 | headers = {"Content-Type": "application/json"} |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 269 | |
| 270 | authed_session = AuthorizedSession(self._source_credentials) |
| 271 | |
| 272 | response = authed_session.post( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 273 | url=iam_sign_endpoint, headers=headers, json=body |
| 274 | ) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 275 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 276 | return base64.b64decode(response.json()["signedBlob"]) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 277 | |
| 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 | |
| 291 | class IDTokenCredentials(credentials.Credentials): |
| 292 | """Open ID Connect ID Token-based service account credentials. |
| 293 | |
| 294 | """ |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 295 | |
| 296 | def __init__(self, target_credentials, target_audience=None, include_email=False): |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 297 | """ |
| 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 306 | if not isinstance(target_credentials, Credentials): |
| 307 | raise exceptions.GoogleAuthError( |
| 308 | "Provided Credential must be " "impersonated_credentials" |
| 309 | ) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 310 | self._target_credentials = target_credentials |
| 311 | self._target_audience = target_audience |
| 312 | self._include_email = include_email |
| 313 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 314 | def from_credentials(self, target_credentials, target_audience=None): |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 315 | return self.__class__( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 316 | target_credentials=self._target_credentials, target_audience=target_audience |
| 317 | ) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 318 | |
| 319 | def with_target_audience(self, target_audience): |
| 320 | return self.__class__( |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 321 | target_credentials=self._target_credentials, target_audience=target_audience |
| 322 | ) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 323 | |
| 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 328 | include_email=include_email, |
| 329 | ) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 330 | |
| 331 | @_helpers.copy_docstring(credentials.Credentials) |
| 332 | def refresh(self, request): |
| 333 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 334 | iam_sign_endpoint = _IAM_IDTOKEN_ENDPOINT.format( |
| 335 | self._target_credentials.signer_email |
| 336 | ) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 337 | |
| 338 | body = { |
| 339 | "audience": self._target_audience, |
| 340 | "delegates": self._target_credentials._delegates, |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 341 | "includeEmail": self._include_email, |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 342 | } |
| 343 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 344 | headers = {"Content-Type": "application/json"} |
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 | authed_session = AuthorizedSession(self._target_credentials._source_credentials) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 347 | |
| 348 | response = authed_session.post( |
| 349 | url=iam_sign_endpoint, |
| 350 | headers=headers, |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 351 | data=json.dumps(body).encode("utf-8"), |
| 352 | ) |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 353 | |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 354 | id_token = response.json()["token"] |
salrashid123 | 7a8641a | 2019-08-07 14:31:33 -0700 | [diff] [blame] | 355 | self.token = id_token |
Bu Sun Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 356 | self.expiry = datetime.fromtimestamp(jwt.decode(id_token, verify=False)["exp"]) |