def test_grpc_request_with_regular_credentials_and_self_signed_jwt(
        http_request):
    credentials, project_id = google.auth.default()

    # At the time this test is being written, there are no GAPIC libraries
    # that will trigger the self-signed JWT flow. Manually create the self-signed
    # jwt on the service account credential to check that the request
    # succeeds.
    credentials = credentials.with_scopes(
        scopes=[], default_scopes=["https://www.googleapis.com/auth/pubsub"])
    credentials._create_self_signed_jwt(
        audience="https://pubsub.googleapis.com/")

    # Create a pub/sub client.
    client = pubsub_v1.PublisherClient(credentials=credentials)

    # list the topics and drain the iterator to test that an authorized API
    # call works.
    list_topics_iter = client.list_topics(
        project="projects/{}".format(project_id))
    list(list_topics_iter)

    # Check that self-signed JWT was created and is being used
    assert credentials._jwt_credentials is not None
    assert credentials._jwt_credentials.token == credentials.token
Ejemplo n.º 2
0
 def spanner_api(self):
     """Helper for session-related API calls."""
     if self._spanner_api is None:
         credentials = self._instance._client.credentials
         if isinstance(credentials, google.auth.credentials.Scoped):
             credentials = credentials.with_scopes((SPANNER_DATA_SCOPE, ))
         self._spanner_api = SpannerClient(credentials=credentials,
                                           client_info=_CLIENT_INFO)
     return self._spanner_api
Ejemplo n.º 3
0
 def spanner_api(self):
     """Helper for session-related API calls."""
     if self._spanner_api is None:
         credentials = self._instance._client.credentials
         if isinstance(credentials, google.auth.credentials.Scoped):
             credentials = credentials.with_scopes((SPANNER_DATA_SCOPE,))
         self._spanner_api = SpannerClient(
             credentials=credentials, client_info=_CLIENT_INFO
         )
     return self._spanner_api
Ejemplo n.º 4
0
 def spanner_api(self):
     """Helper for session-related API calls."""
     if self._spanner_api is None:
         credentials = self._instance._client.credentials
         if isinstance(credentials, google.auth.credentials.Scoped):
             credentials = credentials.with_scopes((SPANNER_DATA_SCOPE, ))
         self._spanner_api = SpannerClient(
             lib_name='gccl',
             lib_version=__version__,
             credentials=credentials,
         )
     return self._spanner_api
Ejemplo n.º 5
0
 def spanner_api(self):
     """Helper for session-related API calls."""
     if self._spanner_api is None:
         client_info = self._instance._client._client_info
         client_options = self._instance._client._client_options
         if self._instance.emulator_host is not None:
             transport = spanner_grpc_transport.SpannerGrpcTransport(
                 channel=grpc.insecure_channel(
                     self._instance.emulator_host))
             self._spanner_api = SpannerClient(
                 client_info=client_info,
                 client_options=client_options,
                 transport=transport,
             )
             return self._spanner_api
         credentials = self._instance._client.credentials
         if isinstance(credentials, google.auth.credentials.Scoped):
             credentials = credentials.with_scopes((SPANNER_DATA_SCOPE, ))
         if (os.getenv("GOOGLE_CLOUD_SPANNER_ENABLE_RESOURCE_BASED_ROUTING")
                 == "true"):
             endpoint_cache = self._instance._client._endpoint_cache
             if self._instance.name in endpoint_cache:
                 client_options = ClientOptions(
                     api_endpoint=endpoint_cache[self._instance.name])
             else:
                 try:
                     api = self._instance._client.instance_admin_api
                     resp = api.get_instance(
                         self._instance.name,
                         field_mask={"paths": ["endpoint_uris"]},
                         metadata=_metadata_with_prefix(self.name),
                     )
                     endpoints = resp.endpoint_uris
                     if endpoints:
                         endpoint_cache[self._instance.name] = list(
                             endpoints)[0]
                         client_options = ClientOptions(
                             api_endpoint=endpoint_cache[
                                 self._instance.name])
                     # If there are no endpoints, use default endpoint.
                 except PermissionDenied:
                     warnings.warn(
                         _RESOURCE_ROUTING_PERMISSIONS_WARNING,
                         ResourceRoutingPermissionsWarning,
                         stacklevel=2,
                     )
         self._spanner_api = SpannerClient(
             credentials=credentials,
             client_info=client_info,
             client_options=client_options,
         )
     return self._spanner_api
Ejemplo n.º 6
0
 def spanner_api(self):
     """Helper for session-related API calls."""
     if self._spanner_api is None:
         client_info = self._instance._client._client_info
         client_options = self._instance._client._client_options
         if self._instance.emulator_host is not None:
             transport = SpannerGrpcTransport(channel=grpc.insecure_channel(
                 self._instance.emulator_host))
             self._spanner_api = SpannerClient(client_info=client_info,
                                               transport=transport)
             return self._spanner_api
         credentials = self._instance._client.credentials
         if isinstance(credentials, google.auth.credentials.Scoped):
             credentials = credentials.with_scopes((SPANNER_DATA_SCOPE, ))
         self._spanner_api = SpannerClient(
             credentials=credentials,
             client_info=client_info,
             client_options=client_options,
         )
     return self._spanner_api
def test_authorized_session_with_service_account_and_self_signed_jwt():
    credentials, project_id = google.auth.default()

    credentials = credentials.with_scopes(
        scopes=[],
        default_scopes=["https://www.googleapis.com/auth/pubsub"],
    )

    session = google.auth.transport.requests.AuthorizedSession(
        credentials=credentials, default_host="pubsub.googleapis.com")

    # List Pub/Sub Topics through the REST API
    # https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/list
    response = session.get(
        "https://pubsub.googleapis.com/v1/projects/{}/topics".format(
            project_id))
    response.raise_for_status()

    # Check that self-signed JWT was created and is being used
    assert credentials._jwt_credentials is not None
    assert credentials._jwt_credentials.token == credentials.token
Ejemplo n.º 8
0
def test_authorized_session_with_service_account_and_self_signed_jwt():
    credentials, project_id = google.auth.default()

    credentials = credentials.with_scopes(
        scopes=[],
        default_scopes=["https://www.googleapis.com/auth/pubsub"],
    )

    http = google.auth.transport.urllib3.AuthorizedHttp(
        credentials=credentials, default_host="pubsub.googleapis.com")

    # List Pub/Sub Topics through the REST API
    # https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics/list
    response = http.urlopen(
        method="GET",
        url="https://pubsub.googleapis.com/v1/projects/{}/topics".format(
            project_id))

    assert response.status == 200

    # Check that self-signed JWT was created and is being used
    assert credentials._jwt_credentials is not None
    assert credentials._jwt_credentials.token == credentials.token
Ejemplo n.º 9
0
def with_scopes_if_required(credentials, scopes):
    """Creates a copy of the credentials with scopes if scoping is required.

    This helper function is useful when you do not know (or care to know) the
    specific type of credentials you are using (such as when you use
    :func:`google.auth.default`). This function will call
    :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
    the credentials require scoping. Otherwise, it will return the credentials
    as-is.

    Args:
        credentials (google.auth.credentials.Credentials): The credentials to
            scope if necessary.
        scopes (Sequence[str]): The list of scopes to use.

    Returns:
        google.auth._credentials_async.Credentials: Either a new set of scoped
            credentials, or the passed in credentials instance if no scoping
            was required.
    """
    if isinstance(credentials, Scoped) and credentials.requires_scopes:
        return credentials.with_scopes(scopes)
    else:
        return credentials