Example #1
0
def _GetServiceAccountCreds(args):
    """Gets service account credentials from given file path or default if any.

  Args:
    args: Command arguments.

  Returns:
    str, service account credentials.
  """
    if args.json_key:
        file_content = _LoadJsonFile(args.json_key)
        return base64.b64encode(file_content).decode("utf-8")

    account = properties.VALUES.core.account.Get()
    if not account:
        raise store.NoActiveAccountException()
    cred = store.Load(account, prevent_refresh=True)
    if not cred:
        raise store.NoCredentialsForAccountException(account)

    account_type = creds.CredentialType.FromCredentials(cred)
    if account_type == creds.CredentialType.SERVICE_ACCOUNT:
        paths = config.Paths()
        json_content = files.ReadFileContents(
            paths.LegacyCredentialsAdcPath(account))
        return base64.b64encode(json_content.encode("utf-8")).decode("utf-8")
    return ""
Example #2
0
def main():
  """Launches bq."""
  version = bootstrapping.ReadFileContents('platform/bq', 'VERSION')
  bootstrapping.CommandStart('bq', version=version)
  blocked_commands = {
      'init': 'To authenticate, run gcloud auth.',
  }
  argv = bootstrapping.GetDecodedArgv()
  bootstrapping.WarnAndExitOnBlockedCommand(argv, blocked_commands)

  cmd_args = [arg for arg in argv[1:] if not arg.startswith('-')]
  args = []
  if cmd_args and cmd_args[0] not in ('version', 'help'):
    # Check for credentials only if they are needed.
    store.Load()  # Checks if there are active credentials

    project, account = bootstrapping.GetActiveProjectAndAccount()
    adc_path = config.Paths().LegacyCredentialsAdcPath(account)
    single_store_path = config.Paths().LegacyCredentialsBqPath(account)

    gce_metadata = gce.Metadata()
    if gce_metadata and account in gce_metadata.Accounts():
      args = ['--use_gce_service_account']
    elif os.path.isfile(adc_path):
      args = ['--application_default_credential_file', adc_path,
              '--credential_file', single_store_path]
    else:
      p12_key_path = config.Paths().LegacyCredentialsP12KeyPath(account)
      if os.path.isfile(p12_key_path):
        args = ['--service_account', account,
                '--service_account_credential_file', single_store_path,
                '--service_account_private_key_file', p12_key_path]
      else:
        # Don't have any credentials we can pass.
        raise store.NoCredentialsForAccountException(account)

    use_client_cert = (
        os.getenv('GOOGLE_API_USE_CLIENT_CERTIFICATE',
                  'false').upper() == 'TRUE')
    if use_client_cert:
      args.append('--mtls')

    _MaybeAddOption(args, 'project_id', project)

  bootstrapping.CheckUpdates('bq')

  proxy_params = properties.VALUES.proxy
  _MaybeAddOption(args, 'proxy_address', proxy_params.address.Get())
  _MaybeAddOption(args, 'proxy_port', proxy_params.port.Get())
  _MaybeAddOption(args, 'proxy_username', proxy_params.username.Get())
  _MaybeAddOption(args, 'proxy_password', proxy_params.password.Get())
  _MaybeAddOption(args, 'disable_ssl_validation',
                  properties.VALUES.auth.disable_ssl_validation.GetBool())
  _MaybeAddOption(args, 'ca_certificates_file',
                  properties.VALUES.core.custom_ca_certs_file .Get())

  bootstrapping.ExecutePythonTool(
      'platform/bq', 'bq.py', *args)
Example #3
0
def main():
    """Launches bq."""
    version = bootstrapping.GetFileContents('platform/bq', 'VERSION')
    bootstrapping.CommandStart('bq', version=version)
    blacklist = {
        'init': 'To authenticate, run gcloud auth.',
    }
    bootstrapping.CheckForBlacklistedCommand(sys.argv,
                                             blacklist,
                                             warn=True,
                                             die=True)
    cmd_args = [arg for arg in sys.argv[1:] if not arg.startswith('-')]
    args = []
    if cmd_args and cmd_args[0] not in ('version', 'help'):
        # Check for credentials only if they are needed.
        store.Load()  # Checks if there are active credentials

        project, account = bootstrapping.GetActiveProjectAndAccount()
        adc_path = config.Paths().LegacyCredentialsAdcPath(account)
        single_store_path = config.Paths().LegacyCredentialsBqPath(account)

        gce_metadata = gce.Metadata()
        if gce_metadata and account in gce_metadata.Accounts():
            args = ['--use_gce_service_account']
        elif os.path.isfile(adc_path):
            args = [
                '--application_default_credential_file', adc_path,
                '--credential_file', single_store_path
            ]
        else:
            p12_key_path = config.Paths().LegacyCredentialsP12KeyPath(account)
            if os.path.isfile(p12_key_path):
                args = [
                    '--service_account', account,
                    '--service_account_credential_file', single_store_path,
                    '--service_account_private_key_file', p12_key_path
                ]
            else:
                # Don't have any credentials we can pass.
                raise store.NoCredentialsForAccountException(account)

        _MaybeAddOption(args, 'project', project)

    bootstrapping.CheckUpdates('bq')

    proxy_params = properties.VALUES.proxy
    _MaybeAddOption(args, 'proxy_address', proxy_params.address.Get())
    _MaybeAddOption(args, 'proxy_port', proxy_params.port.Get())
    _MaybeAddOption(args, 'proxy_username', proxy_params.username.Get())
    _MaybeAddOption(args, 'proxy_password', proxy_params.password.Get())
    _MaybeAddOption(args, 'disable_ssl_validation',
                    properties.VALUES.auth.disable_ssl_validation.GetBool())
    _MaybeAddOption(args, 'ca_certificates_file',
                    properties.VALUES.core.custom_ca_certs_file.Get())

    bootstrapping.ExecutePythonTool('platform/bq', 'bq.py', *args)
Example #4
0
  def FakeAuthSetCredentialsPresent(self, present):
    """Set whether there should be active credentials.

    Args:
      present: bool, True to have credentials present, False for no credentials.
    """
    if present:
      # pylint:disable=unused-argument
      # This function must match the signature of store.Load.
      def _FakeLoad(account=None,
                    scopes=None,
                    prevent_refresh=False,
                    allow_account_impersonation=True,
                    use_google_auth=False):
        return self._FakeAuthCredential(use_google_auth)

      # pylint:enable=unused-argument

      self._load_mock.side_effect = _FakeLoad
    else:
      self._load_mock.side_effect = c_store.NoCredentialsForAccountException(
          self.FakeAuthAccount())