Пример #1
0
def AddQuotaProjectToADC(quota_project):
  """Adds the quota project to the existing ADC file.

  Quota project is only added to ADC when the credentials have the
  "serviceusage.services.use" permission on the project.

  Args:
    quota_project: str, The project id of a valid GCP project to add to ADC.

  Raises:
    MissingPermissionOnQuotaProjectError: If the credentials do not have the
      "serviceusage.services.use" permission.
  """
  AssertADCExists()
  if not ADCIsUserAccount():
    raise c_exc.BadFileException(
        'The application default credentials are not user credentials, quota '
        'project cannot be added.')
  if not AdcHasGivenPermissionOnProject(
      quota_project, permissions=[SERVICEUSAGE_PERMISSION]):
    raise MissingPermissionOnQuotaProjectError(
        'Cannot add the project "{}" to application default credentials (ADC) '
        'as a quota project because the account in ADC does not have the '
        '"{}" permission on this project.'.format(quota_project,
                                                  SERVICEUSAGE_PERMISSION))
  credentials, _ = c_creds.GetGoogleAuthDefault().load_credentials_from_file(
      config.ADCFilePath())
  adc_path = c_creds.ADC(credentials).DumpExtendedADCToFile(
      quota_project=quota_project)
  LogADCIsWritten(adc_path)
  LogQuotaProjectAdded(quota_project)
Пример #2
0
def ADCIsUserAccount():
  """Returns whether the ADC credentials correspond to a user account or not."""
  cred_file = config.ADCFilePath()
  creds, _ = c_creds.GetGoogleAuthDefault().load_credentials_from_file(
      cred_file)
  return (c_creds.IsUserAccountCredentials(creds) or
          c_creds.IsExternalAccountUserCredentials(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
    def Run(self, args):
        """Revoke Application Default Credentials."""

        cred_file = config.ADCFilePath()
        if not os.path.isfile(cred_file):
            log.status.Print(
                'Application Default Credentials have not been set up, '
                'nothing to revoke.')
            return

        creds, _ = c_creds.GetGoogleAuthDefault().load_credentials_from_file(
            cred_file)
        if not (c_creds.IsUserAccountCredentials(creds)
                or c_creds.IsExternalAccountCredentials(creds)
                or c_creds.IsExternalAccountUserCredentials(creds)):
            raise c_exc.BadFileException(
                'The given credential file is a service account credential, and '
                'cannot be revoked.')
        if isinstance(creds, google_auth_creds.Credentials):
            creds = c_google_auth.Credentials.FromGoogleAuthUserCredentials(
                creds)

        console_io.PromptContinue(
            'You are about to revoke the credentials stored in: [{file}]'.
            format(file=cred_file),
            throw_if_unattended=True,
            cancel_on_no=True)

        try:
            c_store.RevokeCredentials(creds)
            os.remove(cred_file)
            log.status.Print('Credentials revoked.')
        except c_store.RevokeError:
            os.remove(cred_file)
            log.warning(
                'The credentials stored in: [{file}] are not revocable from the '
                'server but have been deleted from the file system.'.format(
                    file=cred_file))
Пример #5
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