Exemple #1
0
 def _GetToken(self):
     try:
         cred = store.LoadFreshCredential(
             self._account,
             allow_account_impersonation=self._use_account_impersonation)
         return cred.access_token
     except Exception as e:  # pylint: disable=broad-except
         raise client_base.ClientException(
             'Error Configuring KCC Client: [{}]'.format(e))
Exemple #2
0
def GetAuthToken(account=None):
    """Generate a JSON object containing the current gcloud auth token."""
    try:
        cred = c_store.LoadFreshCredential(account)
        output = {
            'AuthToken': cred.access_token,
        }
    except Exception as e:  # pylint: disable=broad-except
        raise KubeRunAuthException(
            'Error retrieving auth credentials for {account}: {error}. '.
            format(account=account, error=e))
    return json.dumps(output, sort_keys=True)
Exemple #3
0
def GetAuthToken(account, operation, impersonated=False):
  """Generate a JSON object containing the current gcloud auth token."""
  try:
    cred = c_store.LoadFreshCredential(account,
                                       allow_account_impersonation=impersonated)
    output = {
        'auth_token': cred.access_token,
    }
  except Exception as e:  # pylint: disable=broad-except
    raise AnthosAuthException(
        'Error retrieving auth credentials for {operation}: {error}. '.format(
            operation=operation, error=e))
  return json.dumps(output, sort_keys=True)
  def __init__(self, server=None, ignore_bad_certs=False):
    self.server = server or 'appengine.google.com'
    self.project = properties.VALUES.core.project.Get(required=True)
    self.ignore_bad_certs = ignore_bad_certs
    # Auth related options
    self.oauth2_access_token = None
    self.oauth2_refresh_token = None
    self.oauth_scopes = APPCFG_SCOPES
    self.authenticate_service_account = False
    self.client_id = None
    self.client_secret = None

    credentials = c_store.LoadFreshCredential(use_google_auth=True)
    if credentials:
      self._InitCredentials(credentials)
    def __init__(self, server=None, ignore_bad_certs=False):
        self.server = server or 'appengine.google.com'
        self.project = properties.VALUES.core.project.Get(required=True)
        self.ignore_bad_certs = ignore_bad_certs
        # Auth related options
        self.oauth2_access_token = None
        self.oauth2_refresh_token = None
        self.oauth_scopes = APPCFG_SCOPES
        self.authenticate_service_account = False
        self.client_id = None
        self.client_secret = None

        credentials = c_store.LoadFreshCredential()
        if credentials:
            if isinstance(credentials,
                          service_account.ServiceAccountCredentials):
                self.oauth2_access_token = credentials.access_token
                self.client_id = credentials.client_id
                self.client_secret = credentials.client_secret
            elif isinstance(credentials, c_devshell.DevshellCredentials):
                # TODO(b/36057357): This passes the access token to use for API calls to
                # appcfg which means that commands that are longer than the lifetime
                # of the access token may fail - e.g. some long deployments.  The proper
                # solution is to integrate appcfg closer with the Cloud SDK libraries,
                # this code will go away then and the standard credentials flow will be
                # used.
                self.oauth2_access_token = credentials.access_token
                self.client_id = None
                self.client_secret = None
            elif isinstance(credentials,
                            oauth2client_gce.AppAssertionCredentials):
                # If we are on GCE, use the service account
                self.authenticate_service_account = True
                self.client_id = None
                self.client_secret = None
            else:
                # Otherwise use a stored refresh token
                self.oauth2_refresh_token = credentials.refresh_token
                self.client_id = credentials.client_id
                self.client_secret = credentials.client_secret
Exemple #6
0
def MakeRequest(url, command_path):
    """Gets the request object for the given URL using the requests library.

  If the URL is for cloud storage and we get a 403, this will try to load the
  active credentials and use them to authenticate the download.

  Args:
    url: str, the URL to download.
    command_path: str, the command path to include in the User-Agent header if
      the URL is HTTP.

  Raises:
    AuthenticationError: If this download requires authentication and there
      are no credentials or the credentials do not have access.

  Returns:
    requests.Response object
  """
    if url.startswith(ComponentInstaller.GCS_BROWSER_DL_URL):
        url = url.replace(ComponentInstaller.GCS_BROWSER_DL_URL,
                          ComponentInstaller.GCS_API_DL_URL, 1)
    headers = {
        b'Cache-Control':
        b'no-cache',
        b'User-Agent':
        http_encoding.Encode(transport.MakeUserAgentString(command_path))
    }
    timeout = TIMEOUT_IN_SEC
    if command_path == UPDATE_MANAGER_COMMAND_PATH:
        timeout = UPDATE_MANAGER_TIMEOUT_IN_SEC

    try:
        return _RawRequest(url, headers=headers, timeout=timeout)
    except requests.exceptions.HTTPError as e:
        if e.response.status_code != 403 or not e.response.url.startswith(
                ComponentInstaller.GCS_API_DL_URL):
            raise e
        try:
            creds = store.LoadFreshCredential(use_google_auth=True)
            creds.apply(headers)
        except creds_exceptions.Error as e:
            # If we fail here, it is because there are no active credentials or the
            # credentials are bad.
            raise AuthenticationError(
                'This component requires valid credentials to install.', e)
        try:
            # Retry the download using the credentials.
            return _RawRequest(url, headers=headers, timeout=timeout)
        except requests.exceptions.HTTPError as e:
            if e.response.status_code != 403:
                raise e
            # If we fail again with a 403, that means we used the credentials, but
            # they didn't have access to the resource.
            raise AuthenticationError(
                """\
Account [{account}] does not have permission to install this component.  Please
ensure that this account should have access or run:

$ gcloud config set account `ACCOUNT`

to choose another account.""".format(
                    account=properties.VALUES.core.account.Get()), e)
def _GetFreshIdToken():
    cred = store.LoadFreshCredential()
    credential = config_helper.Credential(cred)
    return credential.id_token