Ejemplo n.º 1
0
def Load(account=None, scopes=None, prevent_refresh=False):
    """Get the credentials associated with the provided account.

  Args:
    account: str, The account address for the credentials being fetched. If
        None, the account stored in the core.account property is used.
    scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES
        are requested.
    prevent_refresh: bool, If True, do not refresh the access token even if it
        is out of date. (For use with operations that do not require a current
        access token, such as credential revocation.)

  Returns:
    oauth2client.client.Credentials, The specified credentials.

  Raises:
    NoActiveAccountException: If account is not provided and there is no
        active account.
    NoCredentialsForAccountException: If there are no valid credentials
        available for the provided or active account.
    c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
        be reached.
    TokenRefreshError: If the credentials fail to refresh.
    TokenRefreshReauthError: If the credentials fail to refresh due to reauth.
  """
    # If a credential file is set, just use that and ignore the active account
    # and whatever is in the credential store.
    cred_file_override = properties.VALUES.auth.credential_file_override.Get()
    if cred_file_override:
        log.info('Using alternate credentials from file: [%s]',
                 cred_file_override)
        try:
            cred = client.GoogleCredentials.from_stream(cred_file_override)
        except client.Error as e:
            raise InvalidCredentialFileException(cred_file_override, e)

        if cred.create_scoped_required():
            if scopes is None:
                scopes = config.CLOUDSDK_SCOPES
            cred = cred.create_scoped(scopes)

        # Set token_uri after scopes since token_uri needs to be explicitly
        # preserved when scopes are applied.
        token_uri_override = properties.VALUES.auth.token_host.Get()
        if token_uri_override:
            cred_type = creds.CredentialType.FromCredentials(cred)
            if cred_type in (creds.CredentialType.SERVICE_ACCOUNT,
                             creds.CredentialType.P12_SERVICE_ACCOUNT):
                cred.token_uri = token_uri_override
        return cred

    if not account:
        account = properties.VALUES.core.account.Get()

    if not account:
        raise NoActiveAccountException()

    devshell_creds = c_devshell.LoadDevshellCredentials()
    if devshell_creds and (devshell_creds.devshell_response.user_email
                           == account):
        return devshell_creds

    if account in c_gce.Metadata().Accounts():
        return AcquireFromGCE(account)

    store = creds.GetCredentialStore()
    cred = store.Load(account)
    if not cred:
        raise NoCredentialsForAccountException(account)

    # cred.token_expiry is in UTC time.
    if (not prevent_refresh
            and (not cred.token_expiry
                 or cred.token_expiry < cred.token_expiry.utcnow())):
        Refresh(cred)

    return cred
Ejemplo n.º 2
0
def _GetGCEZone():
    if properties.VALUES.core.check_gce_metadata.GetBool():
        return c_gce.Metadata().Zone()
    return None
Ejemplo n.º 3
0
    def Run(self, args):
        """Run the authentication command."""

        scopes = config.CLOUDSDK_SCOPES
        # Add REAUTH scope in case the user has 2fact activated.
        # This scope is only used here and when refreshing the access token.
        scopes += (config.REAUTH_SCOPE, )

        if args.enable_gdrive_access:
            scopes += (auth_util.GOOGLE_DRIVE_SCOPE, )

        if c_devshell.IsDevshellEnvironment():
            if c_devshell.HasDevshellAuth():
                message = textwrap.dedent("""
            You are already authenticated with gcloud when running
            inside the Cloud Shell and so do not need to run this
            command. Do you wish to proceed anyway?
            """)
                answer = console_io.PromptContinue(message=message)
                if not answer:
                    return None
        elif c_gce.Metadata().connected:
            message = textwrap.dedent("""
          You are running on a Google Compute Engine virtual machine.
          It is recommended that you use service accounts for authentication.

          You can run:

            $ gcloud config set account `ACCOUNT`

          to switch accounts if necessary.

          Your credentials may be visible to others with access to this
          virtual machine. Are you sure you want to authenticate with
          your personal account?
          """)
            answer = console_io.PromptContinue(message=message)
            if not answer:
                return None

        account = args.account

        if account and not args.force:
            try:
                creds = c_store.Load(account=account, scopes=scopes)
            except c_store.Error:
                creds = None
            if creds:
                # Account already has valid creds, just switch to it.
                return self.LoginAs(account, creds, args.project,
                                    args.activate, args.brief)

        # No valid creds, do the web flow.
        launch_browser = check_browser.ShouldLaunchBrowser(args.launch_browser)
        creds = auth_util.DoInstalledAppBrowserFlow(launch_browser, scopes)
        web_flow_account = creds.id_token['email']
        if account and account.lower() != web_flow_account.lower():
            raise auth_exceptions.WrongAccountError(
                'You attempted to log in as account [{account}] but the received '
                'credentials were for account [{web_flow_account}].\n\n'
                'Please check that your browser is logged in as account [{account}] '
                'and that you are using the correct browser profile.'.format(
                    account=account, web_flow_account=web_flow_account))

        account = web_flow_account
        # We got new creds, and they are for the correct user.
        c_store.Store(creds, account, scopes)
        return self.LoginAs(account, creds, args.project, args.activate,
                            args.brief)
Ejemplo n.º 4
0
def main():
  """Launches gsutil."""

  args = []

  project, account = bootstrapping.GetActiveProjectAndAccount()
  pass_credentials = (
      properties.VALUES.core.pass_credentials_to_gsutil.GetBool() and
      not properties.VALUES.auth.disable_credentials.GetBool())

  _MaybeAddBotoOption(args, 'GSUtil', 'default_project_id', project)

  if pass_credentials:
    # Allow gsutil to only check for the '1' string value, as is done
    # with regard to the 'CLOUDSDK_WRAPPER' environment variable.
    encoding.SetEncodedValue(
        os.environ, 'CLOUDSDK_CORE_PASS_CREDENTIALS_TO_GSUTIL', '1')

    if account in c_gce.Metadata().Accounts():
      # Tell gsutil that it should obtain credentials from the GCE metadata
      # server for the instance's configured service account.
      _MaybeAddBotoOption(args, 'GoogleCompute', 'service_account', 'default')
      # For auth'n debugging purposes, allow gsutil to reason about whether the
      # configured service account was set in a boto file or passed from here.
      encoding.SetEncodedValue(
          os.environ, 'CLOUDSDK_PASSED_GCE_SERVICE_ACCOUNT_TO_GSUTIL', '1')
    else:
      legacy_config_path = config.Paths().LegacyCredentialsGSUtilPath(account)
      # We construct a BOTO_PATH that tacks the config containing our
      # credentials options onto the end of the list of config paths. We ensure
      # the other credential options are loaded first so that ours will take
      # precedence and overwrite them.
      boto_config = encoding.GetEncodedValue(os.environ, 'BOTO_CONFIG', '')
      boto_path = encoding.GetEncodedValue(os.environ, 'BOTO_PATH', '')
      if boto_config:
        boto_path = os.pathsep.join([boto_config, legacy_config_path])
      elif boto_path:
        boto_path = os.pathsep.join([boto_path, legacy_config_path])
      else:
        path_parts = ['/etc/boto.cfg',
                      os.path.expanduser(os.path.join('~', '.boto')),
                      legacy_config_path]
        boto_path = os.pathsep.join(path_parts)

      encoding.SetEncodedValue(os.environ, 'BOTO_CONFIG', None)
      encoding.SetEncodedValue(os.environ, 'BOTO_PATH', boto_path)

  # Tell gsutil whether gcloud analytics collection is enabled.
  encoding.SetEncodedValue(
      os.environ, 'GA_CID', metrics.GetCIDIfMetricsEnabled())

  # Set proxy settings. Note that if these proxy settings are configured in a
  # boto config file, the options here will be loaded afterward, overriding
  # them.
  proxy_params = properties.VALUES.proxy
  proxy_address = proxy_params.address.Get()
  if proxy_address:
    _MaybeAddBotoOption(args, 'Boto', 'proxy', proxy_address)
    _MaybeAddBotoOption(args, 'Boto', 'proxy_port', proxy_params.port.Get())
    _MaybeAddBotoOption(args, 'Boto', 'proxy_rdns', proxy_params.rdns.GetBool())
    _MaybeAddBotoOption(args, 'Boto', 'proxy_user', proxy_params.username.Get())
    _MaybeAddBotoOption(args, 'Boto', 'proxy_pass', proxy_params.password.Get())

  # Set SSL-related settings.
  disable_ssl = properties.VALUES.auth.disable_ssl_validation.GetBool()
  _MaybeAddBotoOption(args, 'Boto', 'https_validate_certificates',
                      None if disable_ssl is None else not disable_ssl)
  _MaybeAddBotoOption(args, 'Boto', 'ca_certificates_file',
                      properties.VALUES.core.custom_ca_certs_file.Get())

  # Sync device certificate settings for mTLS.
  context_config = context_aware.Config()
  _MaybeAddBotoOption(args, 'Credentials', 'use_client_certificate',
                      context_config.use_client_certificate)
  if context_config.use_client_certificate:
    # Don't need to pass mTLS data if gsutil shouldn't be using it.
    _MaybeAddBotoOption(args, 'Credentials', 'cert_provider_command',
                        context_config.cert_provider_command)

  # Note that the original args to gsutil will be appended after the args we've
  # supplied here.
  bootstrapping.ExecutePythonTool('platform/gsutil', 'gsutil', *args)
 def GetAccounts(self):
     return set(c_gce.Metadata().Accounts())
 def GetProject(self):
     if properties.VALUES.core.check_gce_metadata.GetBool():
         return c_gce.Metadata().Project()
     return None
 def GetAccount(self):
     if properties.VALUES.core.check_gce_metadata.GetBool():
         return c_gce.Metadata().DefaultAccount()
     return None
 def GetCredentials(self, account):
     if account in c_gce.Metadata().Accounts():
         return AcquireFromGCE(account)
     return None
Ejemplo n.º 9
0
def Load(account=None, scopes=None):
    """Get the credentials associated with the provided account.

  Args:
    account: str, The account address for the credentials being fetched. If
        None, the account stored in the core.account property is used.
    scopes: tuple, Custom auth scopes to request. By default CLOUDSDK_SCOPES
        are requested.

  Returns:
    oauth2client.client.Credentials, The specified credentials.

  Raises:
    NoActiveAccountException: If account is not provided and there is no
        active account.
    NoCredentialsForAccountException: If there are no valid credentials
        available for the provided or active account.
    c_gce.CannotConnectToMetadataServerException: If the metadata server cannot
        be reached.
    TokenRefreshError: If the credentials fail to refresh.
  """
    # If a credential file is set, just use that and ignore the active account
    # and whatever is in the credential store.
    cred_file_override = properties.VALUES.auth.credential_file_override.Get()
    if cred_file_override:
        log.info('Using alternate credentials from file: [%s]',
                 cred_file_override)
        try:
            cred = client.GoogleCredentials.from_stream(cred_file_override)
            if cred.create_scoped_required():
                if scopes is None:
                    scopes = config.CLOUDSDK_SCOPES
                cred = cred.create_scoped(scopes)
            return cred
        except client.Error as e:
            raise InvalidCredentialFileException(cred_file_override, e)

    if not account:
        account = properties.VALUES.core.account.Get()

    if not account:
        raise NoActiveAccountException()

    devshell_creds = c_devshell.LoadDevshellCredentials()
    if devshell_creds and (devshell_creds.devshell_response.user_email
                           == account):
        return devshell_creds

    if account in c_gce.Metadata().Accounts():
        return AcquireFromGCE(account)

    store = _StorageForAccount(account)
    if not store:
        raise NoCredentialsForAccountException(account)
    cred = store.get()
    if not cred:
        raise NoCredentialsForAccountException(account)

    # cred.token_expiry is in UTC time.
    if not cred.token_expiry or cred.token_expiry < cred.token_expiry.utcnow():
        Refresh(cred)

    return cred
Ejemplo n.º 10
0
 def SetUp(self):
     self.metadata = gce.Metadata()
     self.metadata.connected = True
Ejemplo n.º 11
0
def main():
    """Launches gsutil."""

    project, account = bootstrapping.GetActiveProjectAndAccount()
    pass_credentials = (
        properties.VALUES.core.pass_credentials_to_gsutil.GetBool()
        and not properties.VALUES.auth.disable_credentials.GetBool())

    if pass_credentials and account not in c_gce.Metadata().Accounts():
        gsutil_path = config.Paths().LegacyCredentialsGSUtilPath(account)

        # Allow gsutil to only check for the '1' string value, as is done
        # with regard to the 'CLOUDSDK_WRAPPER' environment variable.
        os.environ['CLOUDSDK_CORE_PASS_CREDENTIALS_TO_GSUTIL'] = '1'

        boto_config = os.environ.get('BOTO_CONFIG', '')
        boto_path = os.environ.get('BOTO_PATH', '')

        # We construct a BOTO_PATH that tacks the refresh token config
        # on the end.
        if boto_config:
            boto_path = os.pathsep.join([boto_config, gsutil_path])
        elif boto_path:
            boto_path = os.pathsep.join([boto_path, gsutil_path])
        else:
            path_parts = [
                '/etc/boto.cfg',
                os.path.expanduser(os.path.join('~', '.boto')), gsutil_path
            ]
            boto_path = os.pathsep.join(path_parts)

        if 'BOTO_CONFIG' in os.environ:
            del os.environ['BOTO_CONFIG']
        os.environ['BOTO_PATH'] = boto_path

    # Tell gsutil whether gcloud analytics collection is enabled.
    os.environ['GA_CID'] = metrics.GetCIDIfMetricsEnabled()

    args = []

    _MaybeAddBotoOption(args, 'GSUtil', 'default_project_id', project)
    if pass_credentials and account in c_gce.Metadata().Accounts():
        # Tell gsutil to look for GCE service accounts.
        _MaybeAddBotoOption(args, 'GoogleCompute', 'service_account',
                            'default')

    proxy_params = properties.VALUES.proxy
    proxy_address = proxy_params.address.Get()
    if proxy_address:
        _MaybeAddBotoOption(args, 'Boto', 'proxy', proxy_address)
        _MaybeAddBotoOption(args, 'Boto', 'proxy_port',
                            proxy_params.port.Get())
        _MaybeAddBotoOption(args, 'Boto', 'proxy_rdns',
                            proxy_params.rdns.GetBool())
        _MaybeAddBotoOption(args, 'Boto', 'proxy_user',
                            proxy_params.username.Get())
        _MaybeAddBotoOption(args, 'Boto', 'proxy_pass',
                            proxy_params.password.Get())
    disable_ssl = properties.VALUES.auth.disable_ssl_validation.GetBool()
    _MaybeAddBotoOption(args, 'Boto', 'https_validate_certificates',
                        None if disable_ssl is None else not disable_ssl)
    _MaybeAddBotoOption(args, 'Boto', 'ca_certificates_file',
                        properties.VALUES.core.custom_ca_certs_file.Get())

    bootstrapping.ExecutePythonTool('platform/gsutil', 'gsutil', *args)