1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
|
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Google Cloud Impersonated credentials.
This module provides authentication for applications where local credentials
impersonates a remote service account using `IAM Credentials API`_.
This class can be used to impersonate a service account as long as the original
Credential object has the "Service Account Token Creator" role on the target
service account.
.. _IAM Credentials API:
https://cloud.google.com/iam/credentials/reference/rest/
"""
import base64
import copy
from datetime import datetime
import http.client as http_client
import json
from google.auth import _exponential_backoff
from google.auth import _helpers
from google.auth import credentials
from google.auth import exceptions
from google.auth import iam
from google.auth import jwt
from google.auth import metrics
from google.oauth2 import _client
_REFRESH_ERROR = "Unable to acquire impersonated credentials"
_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
_TRUST_BOUNDARY_LOOKUP_ENDPOINT = (
"https://iamcredentials.{}/v1/projects/-/serviceAccounts/{}/allowedLocations"
)
_SOURCE_CREDENTIAL_AUTHORIZED_USER_TYPE = "authorized_user"
_SOURCE_CREDENTIAL_SERVICE_ACCOUNT_TYPE = "service_account"
_SOURCE_CREDENTIAL_EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = (
"external_account_authorized_user"
)
def _make_iam_token_request(
request,
principal,
headers,
body,
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
iam_endpoint_override=None,
):
"""Makes a request to the Google Cloud IAM service for an access token.
Args:
request (Request): The Request object to use.
principal (str): The principal to request an access token for.
headers (Mapping[str, str]): Map of headers to transmit.
body (Mapping[str, str]): JSON Payload body for the iamcredentials
API call.
iam_endpoint_override (Optiona[str]): The full IAM endpoint override
with the target_principal embedded. This is useful when supporting
impersonation with regional endpoints.
Raises:
google.auth.exceptions.TransportError: Raised if there is an underlying
HTTP connection error
google.auth.exceptions.RefreshError: Raised if the impersonated
credentials are not available. Common reasons are
`iamcredentials.googleapis.com` is not enabled or the
`Service Account Token Creator` is not assigned
"""
iam_endpoint = iam_endpoint_override or iam._IAM_ENDPOINT.replace(
credentials.DEFAULT_UNIVERSE_DOMAIN, universe_domain
).format(principal)
body = json.dumps(body).encode("utf-8")
response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
# support both string and bytes type response.data
response_body = (
response.data.decode("utf-8")
if hasattr(response.data, "decode")
else response.data
)
if response.status != http_client.OK:
raise exceptions.RefreshError(_REFRESH_ERROR, response_body)
try:
token_response = json.loads(response_body)
token = token_response["accessToken"]
expiry = datetime.strptime(token_response["expireTime"], "%Y-%m-%dT%H:%M:%SZ")
return token, expiry
except (KeyError, ValueError) as caught_exc:
new_exc = exceptions.RefreshError(
"{}: No access token or invalid expiration in response.".format(
_REFRESH_ERROR
),
response_body,
)
raise new_exc from caught_exc
class Credentials(
credentials.Scoped,
credentials.CredentialsWithQuotaProject,
credentials.Signing,
credentials.CredentialsWithTrustBoundary,
):
"""This module defines impersonated credentials which are essentially
impersonated identities.
Impersonated Credentials allows credentials issued to a user or
service account to impersonate another. The target service account must
grant the originating credential principal the
`Service Account Token Creator`_ IAM role:
For more information about Token Creator IAM role and
IAMCredentials API, see
`Creating Short-Lived Service Account Credentials`_.
.. _Service Account Token Creator:
https://cloud.google.com/iam/docs/service-accounts#the_service_account_token_creator_role
.. _Creating Short-Lived Service Account Credentials:
https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
Usage:
First grant source_credentials the `Service Account Token Creator`
role on the target account to impersonate. In this example, the
service account represented by svc_account.json has the
token creator role on
`impersonated-account@_project_.iam.gserviceaccount.com`.
Enable the IAMCredentials API on the source project:
`gcloud services enable iamcredentials.googleapis.com`.
Initialize a source credential which does not have access to
list bucket::
from google.oauth2 import service_account
target_scopes = [
'https://www.googleapis.com/auth/devstorage.read_only']
source_credentials = (
service_account.Credentials.from_service_account_file(
'/path/to/svc_account.json',
scopes=target_scopes))
Now use the source credentials to acquire credentials to impersonate
another service account::
from google.auth import impersonated_credentials
target_credentials = impersonated_credentials.Credentials(
source_credentials=source_credentials,
target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
target_scopes = target_scopes,
lifetime=500)
Resource access is granted::
client = storage.Client(credentials=target_credentials)
buckets = client.list_buckets(project='your_project')
for bucket in buckets:
print(bucket.name)
**IMPORTANT**:
This class does not validate the credential configuration. A security
risk occurs when a credential configuration configured with malicious urls
is used.
When the credential configuration is accepted from an
untrusted source, you should validate it before using.
Refer https://cloud.google.com/docs/authentication/external/externally-sourced-credentials for more details.
"""
def __init__(
self,
source_credentials,
target_principal,
target_scopes,
delegates=None,
subject=None,
lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
quota_project_id=None,
iam_endpoint_override=None,
trust_boundary=None,
):
"""
Args:
source_credentials (google.auth.Credentials): The source credential
used as to acquire the impersonated credentials.
target_principal (str): The service account to impersonate.
target_scopes (Sequence[str]): Scopes to request during the
authorization grant.
delegates (Sequence[str]): The chained list of delegates required
to grant the final access_token. If set, the sequence of
identities must have "Service Account Token Creator" capability
granted to the prceeding identity. For example, if set to
[serviceAccountB, serviceAccountC], the source_credential
must have the Token Creator role on serviceAccountB.
serviceAccountB must have the Token Creator on
serviceAccountC.
Finally, C must have Token Creator on target_principal.
If left unset, source_credential must have that role on
target_principal.
lifetime (int): Number of seconds the delegated credential should
be valid for (upto 3600).
quota_project_id (Optional[str]): The project ID used for quota and billing.
This project may be different from the project used to
create the credentials.
iam_endpoint_override (Optional[str]): The full IAM endpoint override
with the target_principal embedded. This is useful when supporting
impersonation with regional endpoints.
subject (Optional[str]): sub field of a JWT. This field should only be set
if you wish to impersonate as a user. This feature is useful when
using domain wide delegation.
trust_boundary (Mapping[str,str]): A credential trust boundary.
"""
super(Credentials, self).__init__()
self._source_credentials = copy.copy(source_credentials)
# Service account source credentials must have the _IAM_SCOPE
# added to refresh correctly. User credentials cannot have
# their original scopes modified.
if isinstance(self._source_credentials, credentials.Scoped):
self._source_credentials = self._source_credentials.with_scopes(
iam._IAM_SCOPE
)
# If the source credential is service account and self signed jwt
# is needed, we need to create a jwt credential inside it
if (
hasattr(self._source_credentials, "_create_self_signed_jwt")
and self._source_credentials._always_use_jwt_access
):
self._source_credentials._create_self_signed_jwt(None)
self._universe_domain = source_credentials.universe_domain
self._target_principal = target_principal
self._target_scopes = target_scopes
self._delegates = delegates
self._subject = subject
self._lifetime = lifetime or _DEFAULT_TOKEN_LIFETIME_SECS
self.token = None
self.expiry = _helpers.utcnow()
self._quota_project_id = quota_project_id
self._iam_endpoint_override = iam_endpoint_override
self._cred_file_path = None
self._trust_boundary = trust_boundary
def _metric_header_for_usage(self):
return metrics.CRED_TYPE_SA_IMPERSONATE
def _perform_refresh_token(self, request):
"""Updates credentials with a new access_token representing
the impersonated account.
Args:
request (google.auth.transport.requests.Request): Request object
to use for refreshing credentials.
"""
# Refresh our source credentials if it is not valid.
if (
self._source_credentials.token_state == credentials.TokenState.STALE
or self._source_credentials.token_state == credentials.TokenState.INVALID
):
self._source_credentials.refresh(request)
body = {
"delegates": self._delegates,
"scope": self._target_scopes,
"lifetime": str(self._lifetime) + "s",
}
headers = {
"Content-Type": "application/json",
metrics.API_CLIENT_HEADER: metrics.token_request_access_token_impersonate(),
}
# Apply the source credentials authentication info.
self._source_credentials.apply(headers)
# If a subject is specified a domain-wide delegation auth-flow is initiated
# to impersonate as the provided subject (user).
if self._subject:
if self.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
raise exceptions.GoogleAuthError(
"Domain-wide delegation is not supported in universes other "
+ "than googleapis.com"
)
now = _helpers.utcnow()
payload = {
"iss": self._target_principal,
"scope": _helpers.scopes_to_string(self._target_scopes or ()),
"sub": self._subject,
"aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
"iat": _helpers.datetime_to_secs(now),
"exp": _helpers.datetime_to_secs(now) + _DEFAULT_TOKEN_LIFETIME_SECS,
}
assertion = _sign_jwt_request(
request=request,
principal=self._target_principal,
headers=headers,
payload=payload,
delegates=self._delegates,
)
self.token, self.expiry, _ = _client.jwt_grant(
request, _GOOGLE_OAUTH2_TOKEN_ENDPOINT, assertion
)
return
self.token, self.expiry = _make_iam_token_request(
request=request,
principal=self._target_principal,
headers=headers,
body=body,
universe_domain=self.universe_domain,
iam_endpoint_override=self._iam_endpoint_override,
)
def _build_trust_boundary_lookup_url(self):
"""Builds and returns the URL for the trust boundary lookup API.
This method constructs the specific URL for the IAM Credentials API's
`allowedLocations` endpoint, using the credential's universe domain
and service account email.
Raises:
ValueError: If `self.service_account_email` is None or an empty
string, as it's required to form the URL.
Returns:
str: The URL for the trust boundary lookup endpoint.
"""
if not self.service_account_email:
raise ValueError(
"Service account email is required to build the trust boundary lookup URL."
)
return _TRUST_BOUNDARY_LOOKUP_ENDPOINT.format(
self.universe_domain, self.service_account_email
)
def sign_bytes(self, message):
from google.auth.transport.requests import AuthorizedSession
iam_sign_endpoint = iam._IAM_SIGN_ENDPOINT.replace(
credentials.DEFAULT_UNIVERSE_DOMAIN, self.universe_domain
).format(self._target_principal)
body = {
"payload": base64.b64encode(message).decode("utf-8"),
"delegates": self._delegates,
}
headers = {"Content-Type": "application/json"}
authed_session = AuthorizedSession(self._source_credentials)
try:
retries = _exponential_backoff.ExponentialBackoff()
for _ in retries:
response = authed_session.post(
url=iam_sign_endpoint, headers=headers, json=body
)
if response.status_code in iam.IAM_RETRY_CODES:
continue
if response.status_code != http_client.OK:
raise exceptions.TransportError(
"Error calling sign_bytes: {}".format(response.json())
)
return base64.b64decode(response.json()["signedBlob"])
finally:
authed_session.close()
raise exceptions.TransportError("exhausted signBlob endpoint retries")
@property
def signer_email(self):
return self._target_principal
@property
def service_account_email(self):
return self._target_principal
@property
def signer(self):
return self
@property
def requires_scopes(self):
return not self._target_scopes
@_helpers.copy_docstring(credentials.Credentials)
def get_cred_info(self):
if self._cred_file_path:
return {
"credential_source": self._cred_file_path,
"credential_type": "impersonated credentials",
"principal": self._target_principal,
}
return None
def _make_copy(self):
cred = self.__class__(
self._source_credentials,
target_principal=self._target_principal,
target_scopes=self._target_scopes,
delegates=self._delegates,
lifetime=self._lifetime,
quota_project_id=self._quota_project_id,
iam_endpoint_override=self._iam_endpoint_override,
trust_boundary=self._trust_boundary,
)
cred._cred_file_path = self._cred_file_path
return cred
@_helpers.copy_docstring(credentials.CredentialsWithTrustBoundary)
def with_trust_boundary(self, trust_boundary):
cred = self._make_copy()
cred._trust_boundary = trust_boundary
return cred
@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
def with_quota_project(self, quota_project_id):
cred = self._make_copy()
cred._quota_project_id = quota_project_id
return cred
@_helpers.copy_docstring(credentials.Scoped)
def with_scopes(self, scopes, default_scopes=None):
cred = self._make_copy()
cred._target_scopes = scopes or default_scopes
return cred
@classmethod
def from_impersonated_service_account_info(cls, info, scopes=None):
"""Creates a Credentials instance from parsed impersonated service account credentials info.
**IMPORTANT**:
This method does not validate the credential configuration. A security
risk occurs when a credential configuration configured with malicious urls
is used.
When the credential configuration is accepted from an
untrusted source, you should validate it before using with this method.
Refer https://cloud.google.com/docs/authentication/external/externally-sourced-credentials for more details.
Args:
info (Mapping[str, str]): The impersonated service account credentials info in Google
format.
scopes (Sequence[str]): Optional list of scopes to include in the
credentials.
Returns:
google.oauth2.credentials.Credentials: The constructed
credentials.
Raises:
InvalidType: If the info["source_credentials"] are not a supported impersonation type
InvalidValue: If the info["service_account_impersonation_url"] is not in the expected format.
ValueError: If the info is not in the expected format.
"""
source_credentials_info = info.get("source_credentials")
source_credentials_type = source_credentials_info.get("type")
if source_credentials_type == _SOURCE_CREDENTIAL_AUTHORIZED_USER_TYPE:
from google.oauth2 import credentials
source_credentials = credentials.Credentials.from_authorized_user_info(
source_credentials_info
)
elif source_credentials_type == _SOURCE_CREDENTIAL_SERVICE_ACCOUNT_TYPE:
from google.oauth2 import service_account
source_credentials = service_account.Credentials.from_service_account_info(
source_credentials_info
)
elif (
source_credentials_type
== _SOURCE_CREDENTIAL_EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE
):
from google.auth import external_account_authorized_user
source_credentials = external_account_authorized_user.Credentials.from_info(
source_credentials_info
)
else:
raise exceptions.InvalidType(
"source credential of type {} is not supported.".format(
source_credentials_type
)
)
impersonation_url = info.get("service_account_impersonation_url")
start_index = impersonation_url.rfind("/")
end_index = impersonation_url.find(":generateAccessToken")
if start_index == -1 or end_index == -1 or start_index > end_index:
raise exceptions.InvalidValue(
"Cannot extract target principal from {}".format(impersonation_url)
)
target_principal = impersonation_url[start_index + 1 : end_index]
delegates = info.get("delegates")
quota_project_id = info.get("quota_project_id")
scopes = scopes or info.get("scopes")
trust_boundary = info.get("trust_boundary")
return cls(
source_credentials,
target_principal,
scopes,
delegates,
quota_project_id=quota_project_id,
trust_boundary=trust_boundary,
)
class IDTokenCredentials(credentials.CredentialsWithQuotaProject):
"""Open ID Connect ID Token-based service account credentials."""
def __init__(
self,
target_credentials,
target_audience=None,
include_email=False,
quota_project_id=None,
):
"""
Args:
target_credentials (google.auth.Credentials): The target
credential used as to acquire the id tokens for.
target_audience (string): Audience to issue the token for.
include_email (bool): Include email in IdToken
quota_project_id (Optional[str]): The project ID used for
quota and billing.
"""
super(IDTokenCredentials, self).__init__()
if not isinstance(target_credentials, Credentials):
raise exceptions.GoogleAuthError(
"Provided Credential must be " "impersonated_credentials"
)
self._target_credentials = target_credentials
self._target_audience = target_audience
self._include_email = include_email
self._quota_project_id = quota_project_id
def from_credentials(self, target_credentials, target_audience=None):
return self.__class__(
target_credentials=target_credentials,
target_audience=target_audience,
include_email=self._include_email,
quota_project_id=self._quota_project_id,
)
def with_target_audience(self, target_audience):
return self.__class__(
target_credentials=self._target_credentials,
target_audience=target_audience,
include_email=self._include_email,
quota_project_id=self._quota_project_id,
)
def with_include_email(self, include_email):
return self.__class__(
target_credentials=self._target_credentials,
target_audience=self._target_audience,
include_email=include_email,
quota_project_id=self._quota_project_id,
)
@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
def with_quota_project(self, quota_project_id):
return self.__class__(
target_credentials=self._target_credentials,
target_audience=self._target_audience,
include_email=self._include_email,
quota_project_id=quota_project_id,
)
@_helpers.copy_docstring(credentials.Credentials)
def refresh(self, request):
from google.auth.transport.requests import AuthorizedSession
iam_sign_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace(
credentials.DEFAULT_UNIVERSE_DOMAIN,
self._target_credentials.universe_domain,
).format(self._target_credentials.signer_email)
body = {
"audience": self._target_audience,
"delegates": self._target_credentials._delegates,
"includeEmail": self._include_email,
}
headers = {
"Content-Type": "application/json",
metrics.API_CLIENT_HEADER: metrics.token_request_id_token_impersonate(),
}
authed_session = AuthorizedSession(
self._target_credentials._source_credentials, auth_request=request
)
try:
response = authed_session.post(
url=iam_sign_endpoint,
headers=headers,
data=json.dumps(body).encode("utf-8"),
)
finally:
authed_session.close()
if response.status_code != http_client.OK:
raise exceptions.RefreshError(
"Error getting ID token: {}".format(response.json())
)
try:
id_token = response.json()["token"]
except (KeyError, ValueError) as caught_exc:
new_exc = exceptions.RefreshError(
"No ID token in response.", response.json()
)
raise new_exc from caught_exc
self.token = id_token
self.expiry = _helpers.utcfromtimestamp(
jwt.decode(id_token, verify=False)["exp"]
)
def _sign_jwt_request(request, principal, headers, payload, delegates=[]):
"""Makes a request to the Google Cloud IAM service to sign a JWT using a
service account's system-managed private key.
Args:
request (Request): The Request object to use.
principal (str): The principal to request an access token for.
headers (Mapping[str, str]): Map of headers to transmit.
payload (Mapping[str, str]): The JWT payload to sign. Must be a
serialized JSON object that contains a JWT Claims Set.
delegates (Sequence[str]): The chained list of delegates required
to grant the final access_token. If set, the sequence of
identities must have "Service Account Token Creator" capability
granted to the prceeding identity. For example, if set to
[serviceAccountB, serviceAccountC], the source_credential
must have the Token Creator role on serviceAccountB.
serviceAccountB must have the Token Creator on
serviceAccountC.
Finally, C must have Token Creator on target_principal.
If left unset, source_credential must have that role on
target_principal.
Raises:
google.auth.exceptions.TransportError: Raised if there is an underlying
HTTP connection error
google.auth.exceptions.RefreshError: Raised if the impersonated
credentials are not available. Common reasons are
`iamcredentials.googleapis.com` is not enabled or the
`Service Account Token Creator` is not assigned
"""
iam_endpoint = iam._IAM_SIGNJWT_ENDPOINT.format(principal)
body = {"delegates": delegates, "payload": json.dumps(payload)}
body = json.dumps(body).encode("utf-8")
response = request(url=iam_endpoint, method="POST", headers=headers, body=body)
# support both string and bytes type response.data
response_body = (
response.data.decode("utf-8")
if hasattr(response.data, "decode")
else response.data
)
if response.status != http_client.OK:
raise exceptions.RefreshError(_REFRESH_ERROR, response_body)
try:
jwt_response = json.loads(response_body)
signed_jwt = jwt_response["signedJwt"]
return signed_jwt
except (KeyError, ValueError) as caught_exc:
new_exc = exceptions.RefreshError(
"{}: No signed JWT in response.".format(_REFRESH_ERROR), response_body
)
raise new_exc from caught_exc
|