Exemplo n.º 1
0
 def GetElevationAccessTokenGoogleAuth(self, source_credentials,
                                       service_account_id, scopes):
     """Creates a fresh impersonation credential using google-auth library."""
     request_client = core_requests.GoogleAuthRequest()
     # google-auth makes a shadow copy of the source_credentials and refresh
     # the copy instead of the original source_credentials. During the copying,
     # the monkey patch
     # (creds.CredentialStoreWithCache._WrapCredentialsRefreshWithAutoCaching)
     # is lost. Here, before passing to google-auth, we refresh
     # source_credentials.
     source_credentials.refresh(request_client)
     # Import only when necessary to decrease the startup time. Move it to
     # global once google-auth is ready to replace oauth2client.
     # pylint: disable=g-import-not-at-top
     from google.auth import impersonated_credentials as google_auth_impersonated_creds
     # pylint: enable=g-import-not-at-top
     cred = google_auth_impersonated_creds.Credentials(
         source_credentials, service_account_id, scopes)
     try:
         cred.refresh(request_client)
     except google_auth_exceptions.RefreshError:
         raise ImpersonatedCredGoogleAuthRefreshError(
             'Failed to impersonate [{service_acc}]. Make sure the '
             'account that\'s trying to impersonate it has access to the service '
             'account itself and the "roles/iam.serviceAccountTokenCreator" '
             'role.'.format(service_acc=service_account_id))
     return cred
def GetExternalAccountId(creds):
    """Returns the external account credentials' identifier.

  This requires basic client authentication and only works with external
  account credentials that have not been impersonated. The returned username
  field is used for the account ID.

  Args:
    creds (google.auth.external_account.Credentials): The external account
      credentials whose account ID is to be determined.

  Returns:
    Optional(str): The account ID string if determinable.

  Raises:
    InactiveCredentialsError: If the credentials are invalid or expired.
    TokenIntrospectionError: If an error is encountered while calling the
      token introspection endpoint.
  """
    # Use basic client authentication.
    client_authentication = oauth2_utils.ClientAuthentication(
        oauth2_utils.ClientAuthType.basic, config.CLOUDSDK_CLIENT_ID,
        config.CLOUDSDK_CLIENT_NOTSOSECRET)
    oauth_introspection = IntrospectionClient(
        token_introspect_endpoint=_EXTERNAL_ACCT_TOKEN_INTROSPECT_ENDPOINT,
        client_authentication=client_authentication)
    request = core_requests.GoogleAuthRequest()
    if not creds.valid:
        creds.refresh(request)
    token_info = oauth_introspection.introspect(request, creds.token)
    # User friendly identifier is stored in username.
    return token_info.get('username')
Exemplo n.º 3
0
  def Run(self, args):
    """Run the helper command."""
    impersonate_service_account = (
        properties.VALUES.auth.impersonate_service_account.Get())
    if impersonate_service_account:
      log.warning(
          "Impersonate service account '{}' is detected. This command cannot be"
          ' used to print the access token for an impersonate account. The '
          "token below is still the application default credentials' access "
          'token.'.format(impersonate_service_account))

    try:
      creds, _ = google_auth_default.default(
          scopes=[auth_util.CLOUD_PLATFORM_SCOPE])
    except google_auth_exceptions.DefaultCredentialsError as e:
      log.debug(e, exc_info=True)
      raise c_exc.ToolException(six.text_type(e))

    # Converts the user credentials so that it can handle reauth during refresh.
    if isinstance(creds, google_auth_creds.Credentials):
      creds = c_google_auth.UserCredWithReauth.FromGoogleAuthUserCredentials(
          creds)
    with c_store.HandleGoogleAuthCredentialsRefreshError(for_adc=True):
      creds.refresh(requests.GoogleAuthRequest())
    return creds
    def Run(self, args):
        """Run the helper command."""
        impersonate_service_account = (
            properties.VALUES.auth.impersonate_service_account.Get())
        if impersonate_service_account:
            log.warning(
                "Impersonate service account '{}' is detected. This command cannot be"
                ' used to print the access token for an impersonate account. The '
                "token below is still the application default credentials' access "
                'token.'.format(impersonate_service_account))

        try:
            creds, _ = c_creds.GetGoogleAuthDefault().default(
                scopes=args.scopes or [auth_util.CLOUD_PLATFORM_SCOPE])
        except google_auth_exceptions.DefaultCredentialsError as e:
            log.debug(e, exc_info=True)
            raise c_exc.ToolException(six.text_type(e))

        if args.scopes:
            cred_type = c_creds.CredentialTypeGoogleAuth.FromCredentials(creds)
            if cred_type not in [
                    c_creds.CredentialTypeGoogleAuth.USER_ACCOUNT,
                    c_creds.CredentialTypeGoogleAuth.SERVICE_ACCOUNT
            ]:
                # TODO(b/223649175): Add support for other credential types(e.g GCE).
                log.warning(
                    '`--scopes` flag may not working as expected and will be ignored '
                    'for account type {}.'.format(cred_type.key))
            scopes = args.scopes + [
                auth_util.OPENID, auth_util.USER_EMAIL_SCOPE
            ]

            # non user account credential types
            # pylint:disable=protected-access
            if isinstance(creds, credentials.Scoped):
                creds = creds.with_scopes(scopes)
            else:
                creds._scopes = scopes

        # Converts the user credentials so that it can handle reauth during refresh.
        if isinstance(creds, google_auth_creds.Credentials):
            creds = c_google_auth.Credentials.FromGoogleAuthUserCredentials(
                creds)
        try:
            with c_store.HandleGoogleAuthCredentialsRefreshError(for_adc=True):
                creds.refresh(requests.GoogleAuthRequest())
            return creds
        except creds_exceptions.TokenRefreshError as e:
            if args.scopes:
                raise c_exc.InvalidArgumentException(
                    '--scopes',
                    'Invalid scopes value. Please make sure the scopes are from [{0}], '
                    'or the scopes previously specified through '
                    '`gcloud auth application-default login --scopes`.'.format(
                        ', '.join(map('`{}`'.format,
                                      auth_util.DEFAULT_SCOPES))))
            else:
                raise e
Exemplo n.º 5
0
 def GetElevationIdTokenGoogleAuth(self,
                                   google_auth_impersonation_credentials,
                                   audience, include_email):
     """Creates an ID token credentials for impersonated credentials."""
     # Import only when necessary to decrease the startup time. Move it to
     # global once google-auth is ready to replace oauth2client.
     # pylint: disable=g-import-not-at-top
     from google.auth import impersonated_credentials as google_auth_impersonated_creds
     # pylint: enable=g-import-not-at-top
     cred = google_auth_impersonated_creds.IDTokenCredentials(
         google_auth_impersonation_credentials,
         target_audience=audience,
         include_email=include_email)
     request_client = core_requests.GoogleAuthRequest()
     cred.refresh(request_client)
     return cred
Exemplo n.º 6
0
def generate_login_token_from_adc(scopes):
    """Genearete a down-coped access token with given scopes for IAM DB authentication from application default credentials.

  Args:
    scopes: scopes to be included in the down-scoped token.

  Returns:
    Down-scoped access token.
  """
    try:
        creds, _ = c_creds.GetGoogleAuthDefault().default(scopes=scopes)
    except google_auth_exceptions.DefaultCredentialsError as e:
        log.debug(e, exc_info=True)
        raise c_exc.ToolException(six.text_type(e))

    creds = _downscope_credential(creds, scopes)

    # Converts the user credentials so that it can handle reauth during refresh.
    if isinstance(creds, google_auth_creds.Credentials):
        creds = c_google_auth.Credentials.FromGoogleAuthUserCredentials(creds)

    with c_store.HandleGoogleAuthCredentialsRefreshError(for_adc=True):
        creds.refresh(requests.GoogleAuthRequest())
    return creds
Exemplo n.º 7
0
 def WrappedRefresh(request):
     del request  # unused
     return original_refresh(requests.GoogleAuthRequest())