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(http.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
Example #3
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