Esempio n. 1
0
def _get_gce_credentials(
    target_audience: Optional[str],
    request: Optional[google.auth.transport.Request] = None
) -> Optional[google_auth_credentials.Credentials]:
    """Gets credentials and project ID from the GCE Metadata Service."""
    # Ping requires a transport, but we want application default credentials
    # to require no arguments. So, we'll use the _http_client transport which
    # uses http.client. This is only acceptable because the metadata server
    # doesn't do SSL and never requires proxies.

    # While this library is normally bundled with compute_engine, there are
    # some cases where it's not available, so we tolerate ImportError.
    try:
        from google.auth import compute_engine
        from google.auth.compute_engine import _metadata
    except ImportError:
        return None
    from google.auth.transport import _http_client

    if request is None:
        request = _http_client.Request()

    if _metadata.ping(request=request):
        return compute_engine.IDTokenCredentials(
            request, target_audience, use_metadata_identity_endpoint=True)

    return None
Esempio n. 2
0
    def _get_credentials_email(self) -> str:
        """
        Returns the email address associated with the currently logged in account

        If a service account is used, it returns the service account.
        If user authentication (e.g. gcloud auth) is used, it returns the e-mail account of that user.
        """
        credentials = self._get_credentials()

        if isinstance(credentials, compute_engine.Credentials):
            try:
                credentials.refresh(_http_client.Request())
            except RefreshError as msg:
                """
                If the Compute Engine metadata service can't be reached in this case the instance has not
                credentials.
                """
                self.log.debug(msg)

        service_account_email = getattr(credentials, 'service_account_email', None)
        if service_account_email:
            return service_account_email

        http_authorized = self._authorize()
        oauth2_client = discovery.build('oauth2', "v1", http=http_authorized, cache_discovery=False)
        return oauth2_client.tokeninfo().execute()['email']