Beispiel #1
0
    def RunCommand(self):
        """Command entry point for the version command."""
        long_form = False
        if self.sub_opts:
            for o, _ in self.sub_opts:
                if o == '-l':
                    long_form = True

        config_paths = ', '.join(GetFriendlyConfigFilePaths())

        shipped_checksum = gslib.CHECKSUM
        try:
            cur_checksum = self._ComputeCodeChecksum()
        except IOError:
            cur_checksum = 'MISSING FILES'
        if shipped_checksum == cur_checksum:
            checksum_ok_str = 'OK'
        else:
            checksum_ok_str = '!= %s' % shipped_checksum

        sys.stdout.write('gsutil version: %s\n' % gslib.VERSION)

        if long_form:

            long_form_output = (
                'checksum: {checksum} ({checksum_ok})\n'
                'boto version: {boto_version}\n'
                'python version: {python_version}\n'
                'OS: {os_version}\n'
                'multiprocessing available: {multiprocessing_available}\n'
                'using cloud sdk: {cloud_sdk}\n'
                'pass cloud sdk credentials to gsutil: {cloud_sdk_credentials}\n'
                'config path(s): {config_paths}\n'
                'gsutil path: {gsutil_path}\n'
                'compiled crcmod: {compiled_crcmod}\n'
                'installed via package manager: {is_package_install}\n'
                'editable install: {is_editable_install}\n')

            sys.stdout.write(
                long_form_output.format(
                    checksum=cur_checksum,
                    checksum_ok=checksum_ok_str,
                    boto_version=boto.__version__,
                    python_version=sys.version.replace('\n', ''),
                    os_version='%s %s' %
                    (platform.system(), platform.release()),
                    multiprocessing_available=(
                        CheckMultiprocessingAvailableAndInit().is_available),
                    cloud_sdk=system_util.InvokedViaCloudSdk(),
                    cloud_sdk_credentials=system_util.
                    CloudSdkCredPassingEnabled(),
                    config_paths=config_paths,
                    gsutil_path=GetCloudSdkGsutilWrapperScriptPath()
                    or gslib.GSUTIL_PATH,
                    compiled_crcmod=UsingCrcmodExtension(crcmod),
                    is_package_install=gslib.IS_PACKAGE_INSTALL,
                    is_editable_install=gslib.IS_EDITABLE_INSTALL,
                ))

        return 0
Beispiel #2
0
def _CheckAndGetCredentials(logger):
    """Returns credentials from the configuration file, if any are present.

  Args:
    logger: logging.Logger instance for outputting messages.

  Returns:
    OAuth2Credentials object if any valid ones are found, otherwise None.
  """
    configured_cred_types = []
    failed_cred_type = None
    try:
        if _HasOauth2UserAccountCreds():
            configured_cred_types.append(CredTypes.OAUTH2_USER_ACCOUNT)
        if _HasOauth2ServiceAccountCreds():
            configured_cred_types.append(CredTypes.OAUTH2_SERVICE_ACCOUNT)
        if len(configured_cred_types) > 1:
            # We only allow one set of configured credentials. Otherwise, we're
            # choosing one arbitrarily, which can be very confusing to the user
            # (e.g., if only one is authorized to perform some action) and can
            # also mask errors.
            # Because boto merges config files, GCE credentials show up by default
            # for GCE VMs. We don't want to fail when a user creates a boto file
            # with their own credentials, so in this case we'll use the OAuth2
            # user credentials.
            raise CommandException((
                'You have multiple types of configured credentials (%s), which is '
                'not supported. One common way this happens is if you run gsutil '
                'config to create credentials and later run gcloud auth, and '
                'create a second set of credentials. Your boto config path is: '
                '%s. For more help, see "gsutil help creds".') %
                                   (configured_cred_types,
                                    GetFriendlyConfigFilePaths()))

        failed_cred_type = CredTypes.OAUTH2_USER_ACCOUNT
        user_creds = _GetOauth2UserAccountCredentials()
        failed_cred_type = CredTypes.OAUTH2_SERVICE_ACCOUNT
        service_account_creds = _GetOauth2ServiceAccountCredentials()
        failed_cred_type = CredTypes.EXTERNAL_ACCOUNT
        external_account_creds = _GetExternalAccountCredentials()
        failed_cred_type = CredTypes.GCE
        gce_creds = _GetGceCreds()
        failed_cred_type = CredTypes.DEVSHELL
        devshell_creds = _GetDevshellCreds()

        creds = user_creds or service_account_creds or gce_creds or external_account_creds or devshell_creds

        # Use one of the above credential types to impersonate, if configured.
        if _HasImpersonateServiceAccount() and creds:
            failed_cred_type = CredTypes.IMPERSONATION
            return _GetImpersonationCredentials(creds, logger)
        else:
            return creds

    except Exception as e:
        # If we didn't actually try to authenticate because there were multiple
        # types of configured credentials, don't emit this warning.
        if failed_cred_type:
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug(traceback.format_exc())
            # If impersonation fails, show the user the actual error, since we handle
            # errors in iamcredentials_api.
            if failed_cred_type == CredTypes.IMPERSONATION:
                raise e
            elif system_util.InvokedViaCloudSdk():
                logger.warn(
                    'Your "%s" credentials are invalid. Please run\n'
                    '  $ gcloud auth login', failed_cred_type)
            else:
                logger.warn(
                    'Your "%s" credentials are invalid. For more help, see '
                    '"gsutil help creds", or re-run the gsutil config command (see '
                    '"gsutil help config").', failed_cred_type)

        # If there's any set of configured credentials, we'll fail if they're
        # invalid, rather than silently falling back to anonymous config (as
        # boto does). That approach leads to much confusion if users don't
        # realize their credentials are invalid.
        raise