diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing/__init__.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing/__init__.py index a3bdbca55a1e..75f635a85f29 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing/__init__.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing/__init__.py @@ -25,29 +25,39 @@ ConfidentialComputingClient, ) from google.cloud.confidentialcomputing_v1.types.service import ( + AwsPrincipalTagsOptions, Challenge, ConfidentialSpaceInfo, ContainerImageSignature, CreateChallengeRequest, + GceShieldedIdentity, GcpCredentials, SevSnpAttestation, + SignatureType, SignedEntity, SigningAlgorithm, TdxCcelAttestation, TokenOptions, + TokenProfile, TokenType, TpmAttestation, VerifyAttestationRequest, VerifyAttestationResponse, + VerifyConfidentialGkeRequest, + VerifyConfidentialGkeResponse, + VerifyConfidentialSpaceRequest, + VerifyConfidentialSpaceResponse, ) __all__ = ( "ConfidentialComputingClient", "ConfidentialComputingAsyncClient", + "AwsPrincipalTagsOptions", "Challenge", "ConfidentialSpaceInfo", "ContainerImageSignature", "CreateChallengeRequest", + "GceShieldedIdentity", "GcpCredentials", "SevSnpAttestation", "SignedEntity", @@ -56,6 +66,12 @@ "TpmAttestation", "VerifyAttestationRequest", "VerifyAttestationResponse", + "VerifyConfidentialGkeRequest", + "VerifyConfidentialGkeResponse", + "VerifyConfidentialSpaceRequest", + "VerifyConfidentialSpaceResponse", + "SignatureType", "SigningAlgorithm", + "TokenProfile", "TokenType", ) diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/__init__.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/__init__.py index 5dfeeeefd0c4..e2de97741c72 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/__init__.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/__init__.py @@ -23,37 +23,53 @@ ConfidentialComputingClient, ) from .types.service import ( + AwsPrincipalTagsOptions, Challenge, ConfidentialSpaceInfo, ContainerImageSignature, CreateChallengeRequest, + GceShieldedIdentity, GcpCredentials, SevSnpAttestation, + SignatureType, SignedEntity, SigningAlgorithm, TdxCcelAttestation, TokenOptions, + TokenProfile, TokenType, TpmAttestation, VerifyAttestationRequest, VerifyAttestationResponse, + VerifyConfidentialGkeRequest, + VerifyConfidentialGkeResponse, + VerifyConfidentialSpaceRequest, + VerifyConfidentialSpaceResponse, ) __all__ = ( "ConfidentialComputingAsyncClient", + "AwsPrincipalTagsOptions", "Challenge", "ConfidentialComputingClient", "ConfidentialSpaceInfo", "ContainerImageSignature", "CreateChallengeRequest", + "GceShieldedIdentity", "GcpCredentials", "SevSnpAttestation", + "SignatureType", "SignedEntity", "SigningAlgorithm", "TdxCcelAttestation", "TokenOptions", + "TokenProfile", "TokenType", "TpmAttestation", "VerifyAttestationRequest", "VerifyAttestationResponse", + "VerifyConfidentialGkeRequest", + "VerifyConfidentialGkeResponse", + "VerifyConfidentialSpaceRequest", + "VerifyConfidentialSpaceResponse", ) diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/gapic_metadata.json b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/gapic_metadata.json index 1f03d82e18a7..5227e556513e 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/gapic_metadata.json +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/gapic_metadata.json @@ -19,6 +19,16 @@ "methods": [ "verify_attestation" ] + }, + "VerifyConfidentialGke": { + "methods": [ + "verify_confidential_gke" + ] + }, + "VerifyConfidentialSpace": { + "methods": [ + "verify_confidential_space" + ] } } }, @@ -34,6 +44,16 @@ "methods": [ "verify_attestation" ] + }, + "VerifyConfidentialGke": { + "methods": [ + "verify_confidential_gke" + ] + }, + "VerifyConfidentialSpace": { + "methods": [ + "verify_confidential_space" + ] } } }, @@ -49,6 +69,16 @@ "methods": [ "verify_attestation" ] + }, + "VerifyConfidentialGke": { + "methods": [ + "verify_confidential_gke" + ] + }, + "VerifyConfidentialSpace": { + "methods": [ + "verify_confidential_space" + ] } } } diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/async_client.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/async_client.py index 35c979469389..8e048194152f 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/async_client.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/async_client.py @@ -431,7 +431,7 @@ async def verify_attestation( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service.VerifyAttestationResponse: r"""Verifies the provided attestation info, returning a - signed OIDC token. + signed attestation token. .. code-block:: python @@ -461,7 +461,7 @@ async def sample_verify_attestation(): Args: request (Optional[Union[google.cloud.confidentialcomputing_v1.types.VerifyAttestationRequest, dict]]): - The request object. A request for an OIDC token, + The request object. A request for an attestation token, providing all the necessary information needed for this service to verify the platform state of the requestor. @@ -477,7 +477,7 @@ async def sample_verify_attestation(): google.cloud.confidentialcomputing_v1.types.VerifyAttestationResponse: A response once an attestation has been successfully verified, containing a - signed OIDC token. + signed attestation token. """ # Create or coerce a protobuf request object. @@ -514,6 +514,194 @@ async def sample_verify_attestation(): # Done; return the response. return response + async def verify_confidential_space( + self, + request: Optional[Union[service.VerifyConfidentialSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.VerifyConfidentialSpaceResponse: + r"""Verifies whether the provided attestation info is + valid, returning a signed attestation token if so. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import confidentialcomputing_v1 + + async def sample_verify_confidential_space(): + # Create a client + client = confidentialcomputing_v1.ConfidentialComputingAsyncClient() + + # Initialize request argument(s) + request = confidentialcomputing_v1.VerifyConfidentialSpaceRequest( + challenge="challenge_value", + ) + + # Make the request + response = await client.verify_confidential_space(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceRequest, dict]]): + The request object. A request for an attestation token, + providing all the necessary information + needed for this service to verify the + platform state of the requestor. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceResponse: + VerifyConfidentialSpaceResponse is + returned once a Confidential Space + attestation has been successfully + verified, containing a signed token. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.VerifyConfidentialSpaceRequest): + request = service.VerifyConfidentialSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.verify_confidential_space + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("challenge", request.challenge),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def verify_confidential_gke( + self, + request: Optional[Union[service.VerifyConfidentialGkeRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.VerifyConfidentialGkeResponse: + r"""Verifies the provided Confidential GKE attestation + info, returning a signed OIDC token. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import confidentialcomputing_v1 + + async def sample_verify_confidential_gke(): + # Create a client + client = confidentialcomputing_v1.ConfidentialComputingAsyncClient() + + # Initialize request argument(s) + request = confidentialcomputing_v1.VerifyConfidentialGkeRequest( + challenge="challenge_value", + ) + + # Make the request + response = await client.verify_confidential_gke(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.confidentialcomputing_v1.types.VerifyConfidentialGkeRequest, dict]]): + The request object. A request for an attestation token, + providing all the necessary information + needed for this service to verify + Confidential GKE platform state of the + requestor. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.confidentialcomputing_v1.types.VerifyConfidentialGkeResponse: + VerifyConfidentialGkeResponse + response is returened once a + Confidential GKE attestation has been + successfully verified, containing a + signed OIDC token. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.VerifyConfidentialGkeRequest): + request = service.VerifyConfidentialGkeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.verify_confidential_gke + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("challenge", request.challenge),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_location( self, request: Optional[locations_pb2.GetLocationRequest] = None, diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/client.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/client.py index 69e3c75a8edf..9a38a0016d49 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/client.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/client.py @@ -850,7 +850,7 @@ def verify_attestation( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service.VerifyAttestationResponse: r"""Verifies the provided attestation info, returning a - signed OIDC token. + signed attestation token. .. code-block:: python @@ -880,7 +880,7 @@ def sample_verify_attestation(): Args: request (Union[google.cloud.confidentialcomputing_v1.types.VerifyAttestationRequest, dict]): - The request object. A request for an OIDC token, + The request object. A request for an attestation token, providing all the necessary information needed for this service to verify the platform state of the requestor. @@ -896,7 +896,7 @@ def sample_verify_attestation(): google.cloud.confidentialcomputing_v1.types.VerifyAttestationResponse: A response once an attestation has been successfully verified, containing a - signed OIDC token. + signed attestation token. """ # Create or coerce a protobuf request object. @@ -931,6 +931,192 @@ def sample_verify_attestation(): # Done; return the response. return response + def verify_confidential_space( + self, + request: Optional[Union[service.VerifyConfidentialSpaceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.VerifyConfidentialSpaceResponse: + r"""Verifies whether the provided attestation info is + valid, returning a signed attestation token if so. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import confidentialcomputing_v1 + + def sample_verify_confidential_space(): + # Create a client + client = confidentialcomputing_v1.ConfidentialComputingClient() + + # Initialize request argument(s) + request = confidentialcomputing_v1.VerifyConfidentialSpaceRequest( + challenge="challenge_value", + ) + + # Make the request + response = client.verify_confidential_space(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceRequest, dict]): + The request object. A request for an attestation token, + providing all the necessary information + needed for this service to verify the + platform state of the requestor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceResponse: + VerifyConfidentialSpaceResponse is + returned once a Confidential Space + attestation has been successfully + verified, containing a signed token. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.VerifyConfidentialSpaceRequest): + request = service.VerifyConfidentialSpaceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.verify_confidential_space + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("challenge", request.challenge),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def verify_confidential_gke( + self, + request: Optional[Union[service.VerifyConfidentialGkeRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.VerifyConfidentialGkeResponse: + r"""Verifies the provided Confidential GKE attestation + info, returning a signed OIDC token. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import confidentialcomputing_v1 + + def sample_verify_confidential_gke(): + # Create a client + client = confidentialcomputing_v1.ConfidentialComputingClient() + + # Initialize request argument(s) + request = confidentialcomputing_v1.VerifyConfidentialGkeRequest( + challenge="challenge_value", + ) + + # Make the request + response = client.verify_confidential_gke(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.confidentialcomputing_v1.types.VerifyConfidentialGkeRequest, dict]): + The request object. A request for an attestation token, + providing all the necessary information + needed for this service to verify + Confidential GKE platform state of the + requestor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.confidentialcomputing_v1.types.VerifyConfidentialGkeResponse: + VerifyConfidentialGkeResponse + response is returened once a + Confidential GKE attestation has been + successfully verified, containing a + signed OIDC token. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.VerifyConfidentialGkeRequest): + request = service.VerifyConfidentialGkeRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.verify_confidential_gke] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("challenge", request.challenge),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "ConfidentialComputingClient": return self diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/base.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/base.py index 33e00a6a33c1..9e54ddafc32a 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/base.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/base.py @@ -161,6 +161,34 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.verify_confidential_space: gapic_v1.method.wrap_method( + self.verify_confidential_space, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.verify_confidential_gke: gapic_v1.method.wrap_method( + self.verify_confidential_gke, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -203,6 +231,30 @@ def verify_attestation( ]: raise NotImplementedError() + @property + def verify_confidential_space( + self, + ) -> Callable[ + [service.VerifyConfidentialSpaceRequest], + Union[ + service.VerifyConfidentialSpaceResponse, + Awaitable[service.VerifyConfidentialSpaceResponse], + ], + ]: + raise NotImplementedError() + + @property + def verify_confidential_gke( + self, + ) -> Callable[ + [service.VerifyConfidentialGkeRequest], + Union[ + service.VerifyConfidentialGkeResponse, + Awaitable[service.VerifyConfidentialGkeResponse], + ], + ]: + raise NotImplementedError() + @property def get_location( self, diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/grpc.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/grpc.py index 4753b77aa2d9..893159f6fca3 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/grpc.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/grpc.py @@ -356,7 +356,7 @@ def verify_attestation( r"""Return a callable for the verify attestation method over gRPC. Verifies the provided attestation info, returning a - signed OIDC token. + signed attestation token. Returns: Callable[[~.VerifyAttestationRequest], @@ -376,6 +376,65 @@ def verify_attestation( ) return self._stubs["verify_attestation"] + @property + def verify_confidential_space( + self, + ) -> Callable[ + [service.VerifyConfidentialSpaceRequest], + service.VerifyConfidentialSpaceResponse, + ]: + r"""Return a callable for the verify confidential space method over gRPC. + + Verifies whether the provided attestation info is + valid, returning a signed attestation token if so. + + Returns: + Callable[[~.VerifyConfidentialSpaceRequest], + ~.VerifyConfidentialSpaceResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "verify_confidential_space" not in self._stubs: + self._stubs["verify_confidential_space"] = self._logged_channel.unary_unary( + "/google.cloud.confidentialcomputing.v1.ConfidentialComputing/VerifyConfidentialSpace", + request_serializer=service.VerifyConfidentialSpaceRequest.serialize, + response_deserializer=service.VerifyConfidentialSpaceResponse.deserialize, + ) + return self._stubs["verify_confidential_space"] + + @property + def verify_confidential_gke( + self, + ) -> Callable[ + [service.VerifyConfidentialGkeRequest], service.VerifyConfidentialGkeResponse + ]: + r"""Return a callable for the verify confidential gke method over gRPC. + + Verifies the provided Confidential GKE attestation + info, returning a signed OIDC token. + + Returns: + Callable[[~.VerifyConfidentialGkeRequest], + ~.VerifyConfidentialGkeResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "verify_confidential_gke" not in self._stubs: + self._stubs["verify_confidential_gke"] = self._logged_channel.unary_unary( + "/google.cloud.confidentialcomputing.v1.ConfidentialComputing/VerifyConfidentialGke", + request_serializer=service.VerifyConfidentialGkeRequest.serialize, + response_deserializer=service.VerifyConfidentialGkeResponse.deserialize, + ) + return self._stubs["verify_confidential_gke"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/grpc_asyncio.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/grpc_asyncio.py index 848c4fc51d04..393da1d16924 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/grpc_asyncio.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/grpc_asyncio.py @@ -364,7 +364,7 @@ def verify_attestation( r"""Return a callable for the verify attestation method over gRPC. Verifies the provided attestation info, returning a - signed OIDC token. + signed attestation token. Returns: Callable[[~.VerifyAttestationRequest], @@ -384,6 +384,66 @@ def verify_attestation( ) return self._stubs["verify_attestation"] + @property + def verify_confidential_space( + self, + ) -> Callable[ + [service.VerifyConfidentialSpaceRequest], + Awaitable[service.VerifyConfidentialSpaceResponse], + ]: + r"""Return a callable for the verify confidential space method over gRPC. + + Verifies whether the provided attestation info is + valid, returning a signed attestation token if so. + + Returns: + Callable[[~.VerifyConfidentialSpaceRequest], + Awaitable[~.VerifyConfidentialSpaceResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "verify_confidential_space" not in self._stubs: + self._stubs["verify_confidential_space"] = self._logged_channel.unary_unary( + "/google.cloud.confidentialcomputing.v1.ConfidentialComputing/VerifyConfidentialSpace", + request_serializer=service.VerifyConfidentialSpaceRequest.serialize, + response_deserializer=service.VerifyConfidentialSpaceResponse.deserialize, + ) + return self._stubs["verify_confidential_space"] + + @property + def verify_confidential_gke( + self, + ) -> Callable[ + [service.VerifyConfidentialGkeRequest], + Awaitable[service.VerifyConfidentialGkeResponse], + ]: + r"""Return a callable for the verify confidential gke method over gRPC. + + Verifies the provided Confidential GKE attestation + info, returning a signed OIDC token. + + Returns: + Callable[[~.VerifyConfidentialGkeRequest], + Awaitable[~.VerifyConfidentialGkeResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "verify_confidential_gke" not in self._stubs: + self._stubs["verify_confidential_gke"] = self._logged_channel.unary_unary( + "/google.cloud.confidentialcomputing.v1.ConfidentialComputing/VerifyConfidentialGke", + request_serializer=service.VerifyConfidentialGkeRequest.serialize, + response_deserializer=service.VerifyConfidentialGkeResponse.deserialize, + ) + return self._stubs["verify_confidential_gke"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -415,6 +475,34 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.verify_confidential_space: self._wrap_method( + self.verify_confidential_space, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.verify_confidential_gke: self._wrap_method( + self.verify_confidential_gke, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/rest.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/rest.py index c580012d37d8..f4b10615fa46 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/rest.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/rest.py @@ -89,6 +89,22 @@ def post_verify_attestation(self, response): logging.log(f"Received response: {response}") return response + def pre_verify_confidential_gke(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_verify_confidential_gke(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_verify_confidential_space(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_verify_confidential_space(self, response): + logging.log(f"Received response: {response}") + return response + transport = ConfidentialComputingRestTransport(interceptor=MyCustomConfidentialComputingInterceptor()) client = ConfidentialComputingClient(transport=transport) @@ -189,6 +205,106 @@ def post_verify_attestation_with_metadata( """ return response, metadata + def pre_verify_confidential_gke( + self, + request: service.VerifyConfidentialGkeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.VerifyConfidentialGkeRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for verify_confidential_gke + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConfidentialComputing server. + """ + return request, metadata + + def post_verify_confidential_gke( + self, response: service.VerifyConfidentialGkeResponse + ) -> service.VerifyConfidentialGkeResponse: + """Post-rpc interceptor for verify_confidential_gke + + DEPRECATED. Please use the `post_verify_confidential_gke_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ConfidentialComputing server but before + it is returned to user code. This `post_verify_confidential_gke` interceptor runs + before the `post_verify_confidential_gke_with_metadata` interceptor. + """ + return response + + def post_verify_confidential_gke_with_metadata( + self, + response: service.VerifyConfidentialGkeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.VerifyConfidentialGkeResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for verify_confidential_gke + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ConfidentialComputing server but before it is returned to user code. + + We recommend only using this `post_verify_confidential_gke_with_metadata` + interceptor in new development instead of the `post_verify_confidential_gke` interceptor. + When both interceptors are used, this `post_verify_confidential_gke_with_metadata` interceptor runs after the + `post_verify_confidential_gke` interceptor. The (possibly modified) response returned by + `post_verify_confidential_gke` will be passed to + `post_verify_confidential_gke_with_metadata`. + """ + return response, metadata + + def pre_verify_confidential_space( + self, + request: service.VerifyConfidentialSpaceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.VerifyConfidentialSpaceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for verify_confidential_space + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConfidentialComputing server. + """ + return request, metadata + + def post_verify_confidential_space( + self, response: service.VerifyConfidentialSpaceResponse + ) -> service.VerifyConfidentialSpaceResponse: + """Post-rpc interceptor for verify_confidential_space + + DEPRECATED. Please use the `post_verify_confidential_space_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ConfidentialComputing server but before + it is returned to user code. This `post_verify_confidential_space` interceptor runs + before the `post_verify_confidential_space_with_metadata` interceptor. + """ + return response + + def post_verify_confidential_space_with_metadata( + self, + response: service.VerifyConfidentialSpaceResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.VerifyConfidentialSpaceResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for verify_confidential_space + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ConfidentialComputing server but before it is returned to user code. + + We recommend only using this `post_verify_confidential_space_with_metadata` + interceptor in new development instead of the `post_verify_confidential_space` interceptor. + When both interceptors are used, this `post_verify_confidential_space_with_metadata` interceptor runs after the + `post_verify_confidential_space` interceptor. The (possibly modified) response returned by + `post_verify_confidential_space` will be passed to + `post_verify_confidential_space_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -525,7 +641,7 @@ def __call__( Args: request (~.service.VerifyAttestationRequest): - The request object. A request for an OIDC token, + The request object. A request for an attestation token, providing all the necessary information needed for this service to verify the platform state of the requestor. @@ -541,7 +657,7 @@ def __call__( ~.service.VerifyAttestationResponse: A response once an attestation has been successfully verified, containing a - signed OIDC token. + signed attestation token. """ @@ -646,6 +762,334 @@ def __call__( ) return resp + class _VerifyConfidentialGke( + _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialGke, + ConfidentialComputingRestStub, + ): + def __hash__(self): + return hash("ConfidentialComputingRestTransport.VerifyConfidentialGke") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.VerifyConfidentialGkeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.VerifyConfidentialGkeResponse: + r"""Call the verify confidential gke method over HTTP. + + Args: + request (~.service.VerifyConfidentialGkeRequest): + The request object. A request for an attestation token, + providing all the necessary information + needed for this service to verify + Confidential GKE platform state of the + requestor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.VerifyConfidentialGkeResponse: + VerifyConfidentialGkeResponse + response is returened once a + Confidential GKE attestation has been + successfully verified, containing a + signed OIDC token. + + """ + + http_options = ( + _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialGke._get_http_options() + ) + + request, metadata = self._interceptor.pre_verify_confidential_gke( + request, metadata + ) + transcoded_request = _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialGke._get_transcoded_request( + http_options, request + ) + + body = _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialGke._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialGke._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.confidentialcomputing_v1.ConfidentialComputingClient.VerifyConfidentialGke", + extra={ + "serviceName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing", + "rpcName": "VerifyConfidentialGke", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + ConfidentialComputingRestTransport._VerifyConfidentialGke._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.VerifyConfidentialGkeResponse() + pb_resp = service.VerifyConfidentialGkeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_verify_confidential_gke(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_verify_confidential_gke_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.VerifyConfidentialGkeResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.confidentialcomputing_v1.ConfidentialComputingClient.verify_confidential_gke", + extra={ + "serviceName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing", + "rpcName": "VerifyConfidentialGke", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _VerifyConfidentialSpace( + _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialSpace, + ConfidentialComputingRestStub, + ): + def __hash__(self): + return hash("ConfidentialComputingRestTransport.VerifyConfidentialSpace") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.VerifyConfidentialSpaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.VerifyConfidentialSpaceResponse: + r"""Call the verify confidential space method over HTTP. + + Args: + request (~.service.VerifyConfidentialSpaceRequest): + The request object. A request for an attestation token, + providing all the necessary information + needed for this service to verify the + platform state of the requestor. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.VerifyConfidentialSpaceResponse: + VerifyConfidentialSpaceResponse is + returned once a Confidential Space + attestation has been successfully + verified, containing a signed token. + + """ + + http_options = ( + _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialSpace._get_http_options() + ) + + request, metadata = self._interceptor.pre_verify_confidential_space( + request, metadata + ) + transcoded_request = _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialSpace._get_transcoded_request( + http_options, request + ) + + body = _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialSpace._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialSpace._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.confidentialcomputing_v1.ConfidentialComputingClient.VerifyConfidentialSpace", + extra={ + "serviceName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing", + "rpcName": "VerifyConfidentialSpace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfidentialComputingRestTransport._VerifyConfidentialSpace._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.VerifyConfidentialSpaceResponse() + pb_resp = service.VerifyConfidentialSpaceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_verify_confidential_space(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_verify_confidential_space_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.VerifyConfidentialSpaceResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.confidentialcomputing_v1.ConfidentialComputingClient.verify_confidential_space", + extra={ + "serviceName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing", + "rpcName": "VerifyConfidentialSpace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def create_challenge( self, @@ -664,6 +1108,27 @@ def verify_attestation( # In C++ this would require a dynamic_cast return self._VerifyAttestation(self._session, self._host, self._interceptor) # type: ignore + @property + def verify_confidential_gke( + self, + ) -> Callable[ + [service.VerifyConfidentialGkeRequest], service.VerifyConfidentialGkeResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._VerifyConfidentialGke(self._session, self._host, self._interceptor) # type: ignore + + @property + def verify_confidential_space( + self, + ) -> Callable[ + [service.VerifyConfidentialSpaceRequest], + service.VerifyConfidentialSpaceResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._VerifyConfidentialSpace(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/rest_base.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/rest_base.py index 118c5c977bdc..7e04713b4c04 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/rest_base.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/services/confidential_computing/transports/rest_base.py @@ -202,6 +202,120 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseVerifyConfidentialGke: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{challenge=projects/*/locations/*/challenges/*}:verifyConfidentialGke", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.VerifyConfidentialGkeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialGke._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseVerifyConfidentialSpace: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{challenge=projects/*/locations/*/challenges/*}:verifyConfidentialSpace", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.VerifyConfidentialSpaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseConfidentialComputingRestTransport._BaseVerifyConfidentialSpace._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/types/__init__.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/types/__init__.py index fda613300f9f..32812c04e204 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/types/__init__.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/types/__init__.py @@ -14,27 +14,37 @@ # limitations under the License. # from .service import ( + AwsPrincipalTagsOptions, Challenge, ConfidentialSpaceInfo, ContainerImageSignature, CreateChallengeRequest, + GceShieldedIdentity, GcpCredentials, SevSnpAttestation, + SignatureType, SignedEntity, SigningAlgorithm, TdxCcelAttestation, TokenOptions, + TokenProfile, TokenType, TpmAttestation, VerifyAttestationRequest, VerifyAttestationResponse, + VerifyConfidentialGkeRequest, + VerifyConfidentialGkeResponse, + VerifyConfidentialSpaceRequest, + VerifyConfidentialSpaceResponse, ) __all__ = ( + "AwsPrincipalTagsOptions", "Challenge", "ConfidentialSpaceInfo", "ContainerImageSignature", "CreateChallengeRequest", + "GceShieldedIdentity", "GcpCredentials", "SevSnpAttestation", "SignedEntity", @@ -43,6 +53,12 @@ "TpmAttestation", "VerifyAttestationRequest", "VerifyAttestationResponse", + "VerifyConfidentialGkeRequest", + "VerifyConfidentialGkeResponse", + "VerifyConfidentialSpaceRequest", + "VerifyConfidentialSpaceResponse", + "SignatureType", "SigningAlgorithm", + "TokenProfile", "TokenType", ) diff --git a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/types/service.py b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/types/service.py index c23bded7fdf0..7193a179f4ec 100644 --- a/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/types/service.py +++ b/packages/google-cloud-confidentialcomputing/google/cloud/confidentialcomputing_v1/types/service.py @@ -26,6 +26,8 @@ manifest={ "SigningAlgorithm", "TokenType", + "SignatureType", + "TokenProfile", "Challenge", "CreateChallengeRequest", "VerifyAttestationRequest", @@ -34,10 +36,16 @@ "VerifyAttestationResponse", "GcpCredentials", "TokenOptions", + "AwsPrincipalTagsOptions", "TpmAttestation", "ConfidentialSpaceInfo", "SignedEntity", "ContainerImageSignature", + "VerifyConfidentialSpaceRequest", + "GceShieldedIdentity", + "VerifyConfidentialSpaceResponse", + "VerifyConfidentialGkeRequest", + "VerifyConfidentialGkeResponse", }, ) @@ -86,6 +94,39 @@ class TokenType(proto.Enum): TOKEN_TYPE_AWS_PRINCIPALTAGS = 4 +class SignatureType(proto.Enum): + r"""SignatureType enumerates supported signature types for + attestation tokens. + + Values: + SIGNATURE_TYPE_UNSPECIFIED (0): + Unspecified signature type. + SIGNATURE_TYPE_OIDC (1): + Google OIDC signature. + SIGNATURE_TYPE_PKI (2): + Public Key Infrastructure (PKI) signature. + """ + SIGNATURE_TYPE_UNSPECIFIED = 0 + SIGNATURE_TYPE_OIDC = 1 + SIGNATURE_TYPE_PKI = 2 + + +class TokenProfile(proto.Enum): + r"""TokenProfile enumerates the supported token claims profiles. + + Values: + TOKEN_PROFILE_UNSPECIFIED (0): + Unspecified token profile. + TOKEN_PROFILE_DEFAULT_EAT (1): + EAT claims. + TOKEN_PROFILE_AWS (2): + AWS Principal Tags claims. + """ + TOKEN_PROFILE_UNSPECIFIED = 0 + TOKEN_PROFILE_DEFAULT_EAT = 1 + TOKEN_PROFILE_AWS = 2 + + class Challenge(proto.Message): r"""A Challenge from the server used to guarantee freshness of attestations @@ -160,9 +201,9 @@ class CreateChallengeRequest(proto.Message): class VerifyAttestationRequest(proto.Message): - r"""A request for an OIDC token, providing all the necessary - information needed for this service to verify the platform state - of the requestor. + r"""A request for an attestation token, providing all the + necessary information needed for this service to verify the + platform state of the requestor. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -315,7 +356,7 @@ class SevSnpAttestation(proto.Message): class VerifyAttestationResponse(proto.Message): r"""A response once an attestation has been successfully - verified, containing a signed OIDC token. + verified, containing a signed attestation token. Attributes: oidc_claims_token (str): @@ -361,9 +402,8 @@ class TokenOptions(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - aws_principal_tags_options (google.cloud.confidentialcomputing_v1.types.TokenOptions.AwsPrincipalTagsOptions): - Optional. Options for the Limited AWS token - type. + aws_principal_tags_options (google.cloud.confidentialcomputing_v1.types.AwsPrincipalTagsOptions): + Optional. Options for AWS token type. This field is a member of `oneof`_ ``token_type_options``. audience (str): @@ -380,74 +420,75 @@ class TokenOptions(proto.Message): type of token to return. """ - class AwsPrincipalTagsOptions(proto.Message): - r"""Token options that only apply to the AWS Principal Tags token - type. + aws_principal_tags_options: "AwsPrincipalTagsOptions" = proto.Field( + proto.MESSAGE, + number=4, + oneof="token_type_options", + message="AwsPrincipalTagsOptions", + ) + audience: str = proto.Field( + proto.STRING, + number=1, + ) + nonce: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + token_type: "TokenType" = proto.Field( + proto.ENUM, + number=3, + enum="TokenType", + ) + + +class AwsPrincipalTagsOptions(proto.Message): + r"""Token options that only apply to the AWS Principal Tags token + type. + + Attributes: + allowed_principal_tags (google.cloud.confidentialcomputing_v1.types.AwsPrincipalTagsOptions.AllowedPrincipalTags): + Optional. Principal tags to allow in the + token. + """ + + class AllowedPrincipalTags(proto.Message): + r"""Allowed principal tags is used to define what principal tags + will be placed in the token. Attributes: - allowed_principal_tags (google.cloud.confidentialcomputing_v1.types.TokenOptions.AwsPrincipalTagsOptions.AllowedPrincipalTags): - Optional. Principal tags to allow in the - token. + container_image_signatures (google.cloud.confidentialcomputing_v1.types.AwsPrincipalTagsOptions.AllowedPrincipalTags.ContainerImageSignatures): + Optional. Container image signatures allowed + in the token. """ - class AllowedPrincipalTags(proto.Message): - r"""Allowed principal tags is used to define what principal tags - will be placed in the token. + class ContainerImageSignatures(proto.Message): + r"""Allowed Container Image Signatures. Key IDs are required to + allow this claim to fit within the narrow AWS IAM restrictions. Attributes: - container_image_signatures (google.cloud.confidentialcomputing_v1.types.TokenOptions.AwsPrincipalTagsOptions.AllowedPrincipalTags.ContainerImageSignatures): - Optional. Container image signatures allowed - in the token. + key_ids (MutableSequence[str]): + Optional. List of key ids to filter into the + Principal tags. Only keys that have been + validated and added to the token will be + filtered into principal tags. Unrecognized key + ids will be ignored. """ - class ContainerImageSignatures(proto.Message): - r"""Allowed Container Image Signatures. Key IDs are required to - allow this claim to fit within the narrow AWS IAM restrictions. - - Attributes: - key_ids (MutableSequence[str]): - Optional. List of key ids to filter into the - Principal tags. Only keys that have been - validated and added to the token will be - filtered into principal tags. Unrecognized key - ids will be ignored. - """ - - key_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - container_image_signatures: "TokenOptions.AwsPrincipalTagsOptions.AllowedPrincipalTags.ContainerImageSignatures" = proto.Field( - proto.MESSAGE, + key_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, number=1, - message="TokenOptions.AwsPrincipalTagsOptions.AllowedPrincipalTags.ContainerImageSignatures", ) - allowed_principal_tags: "TokenOptions.AwsPrincipalTagsOptions.AllowedPrincipalTags" = proto.Field( + container_image_signatures: "AwsPrincipalTagsOptions.AllowedPrincipalTags.ContainerImageSignatures" = proto.Field( proto.MESSAGE, number=1, - message="TokenOptions.AwsPrincipalTagsOptions.AllowedPrincipalTags", + message="AwsPrincipalTagsOptions.AllowedPrincipalTags.ContainerImageSignatures", ) - aws_principal_tags_options: AwsPrincipalTagsOptions = proto.Field( + allowed_principal_tags: AllowedPrincipalTags = proto.Field( proto.MESSAGE, - number=4, - oneof="token_type_options", - message=AwsPrincipalTagsOptions, - ) - audience: str = proto.Field( - proto.STRING, number=1, - ) - nonce: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - token_type: "TokenType" = proto.Field( - proto.ENUM, - number=3, - enum="TokenType", + message=AllowedPrincipalTags, ) @@ -620,4 +661,255 @@ class ContainerImageSignature(proto.Message): ) +class VerifyConfidentialSpaceRequest(proto.Message): + r"""A request for an attestation token, providing all the + necessary information needed for this service to verify the + platform state of the requestor. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + td_ccel (google.cloud.confidentialcomputing_v1.types.TdxCcelAttestation): + Input only. A TDX with CCEL and RTMR + Attestation Quote. + + This field is a member of `oneof`_ ``tee_attestation``. + tpm_attestation (google.cloud.confidentialcomputing_v1.types.TpmAttestation): + Input only. The TPM-specific data provided by + the attesting platform, used to populate any of + the claims regarding platform state. + + This field is a member of `oneof`_ ``tee_attestation``. + challenge (str): + Required. The name of the Challenge whose nonce was used to + generate the attestation, in the format + ``projects/*/locations/*/challenges/*``. The provided + Challenge will be consumed, and cannot be used again. + gcp_credentials (google.cloud.confidentialcomputing_v1.types.GcpCredentials): + Optional. Credentials used to populate the "emails" claim in + the claims_token. If not present, token will not contain the + "emails" claim. + signed_entities (MutableSequence[google.cloud.confidentialcomputing_v1.types.SignedEntity]): + Optional. A list of signed entities + containing container image signatures that can + be used for server-side signature verification. + gce_shielded_identity (google.cloud.confidentialcomputing_v1.types.GceShieldedIdentity): + Optional. Information about the associated Compute Engine + instance. Required for td_ccel requests only - + tpm_attestation requests will provide this information in + the attestation. + options (google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceRequest.ConfidentialSpaceOptions): + Optional. A collection of fields that modify + the token output. + """ + + class ConfidentialSpaceOptions(proto.Message): + r"""Token options for Confidential Space attestation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + aws_principal_tags_options (google.cloud.confidentialcomputing_v1.types.AwsPrincipalTagsOptions): + Optional. Options for the AWS token type. + + This field is a member of `oneof`_ ``token_profile_options``. + audience (str): + Optional. Optional string to issue the token + with a custom audience claim. Required if custom + nonces are specified. + token_profile (google.cloud.confidentialcomputing_v1.types.TokenProfile): + Optional. Optional specification for token + claims profile. + nonce (MutableSequence[str]): + Optional. Optional parameter to place one or more nonces in + the eat_nonce claim in the output token. The minimum size + for JSON-encoded EATs is 10 bytes and the maximum size is 74 + bytes. + signature_type (google.cloud.confidentialcomputing_v1.types.SignatureType): + Optional. Optional specification for how to sign the + attestation token. Defaults to SIGNATURE_TYPE_OIDC if + unspecified. + """ + + aws_principal_tags_options: "AwsPrincipalTagsOptions" = proto.Field( + proto.MESSAGE, + number=5, + oneof="token_profile_options", + message="AwsPrincipalTagsOptions", + ) + audience: str = proto.Field( + proto.STRING, + number=1, + ) + token_profile: "TokenProfile" = proto.Field( + proto.ENUM, + number=2, + enum="TokenProfile", + ) + nonce: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + signature_type: "SignatureType" = proto.Field( + proto.ENUM, + number=4, + enum="SignatureType", + ) + + td_ccel: "TdxCcelAttestation" = proto.Field( + proto.MESSAGE, + number=3, + oneof="tee_attestation", + message="TdxCcelAttestation", + ) + tpm_attestation: "TpmAttestation" = proto.Field( + proto.MESSAGE, + number=4, + oneof="tee_attestation", + message="TpmAttestation", + ) + challenge: str = proto.Field( + proto.STRING, + number=1, + ) + gcp_credentials: "GcpCredentials" = proto.Field( + proto.MESSAGE, + number=2, + message="GcpCredentials", + ) + signed_entities: MutableSequence["SignedEntity"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="SignedEntity", + ) + gce_shielded_identity: "GceShieldedIdentity" = proto.Field( + proto.MESSAGE, + number=6, + message="GceShieldedIdentity", + ) + options: ConfidentialSpaceOptions = proto.Field( + proto.MESSAGE, + number=7, + message=ConfidentialSpaceOptions, + ) + + +class GceShieldedIdentity(proto.Message): + r"""GceShieldedIdentity contains information about a Compute + Engine instance. + + Attributes: + ak_cert (bytes): + Optional. DER-encoded X.509 certificate of + the Attestation Key (otherwise known as an AK or + a TPM restricted signing key) used to generate + the quotes. + ak_cert_chain (MutableSequence[bytes]): + Optional. List of DER-encoded X.509 certificates which, + together with the ak_cert, chain back to a trusted Root + Certificate. + """ + + ak_cert: bytes = proto.Field( + proto.BYTES, + number=1, + ) + ak_cert_chain: MutableSequence[bytes] = proto.RepeatedField( + proto.BYTES, + number=2, + ) + + +class VerifyConfidentialSpaceResponse(proto.Message): + r"""VerifyConfidentialSpaceResponse is returned once a + Confidential Space attestation has been successfully verified, + containing a signed token. + + Attributes: + attestation_token (str): + Output only. The attestation token issued by + this service. It contains specific platform + claims based on the contents of the provided + attestation. + partial_errors (MutableSequence[google.rpc.status_pb2.Status]): + Output only. A list of messages that carry + the partial error details related to + VerifyConfidentialSpace. This field is populated + by errors during container image signature + verification, which may reflect problems in the + provided image signatures. This does not block + the issuing of an attestation token, but the + token will not contain claims for the failed + image signatures. + """ + + attestation_token: str = proto.Field( + proto.STRING, + number=1, + ) + partial_errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + +class VerifyConfidentialGkeRequest(proto.Message): + r"""A request for an attestation token, providing all the + necessary information needed for this service to verify + Confidential GKE platform state of the requestor. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tpm_attestation (google.cloud.confidentialcomputing_v1.types.TpmAttestation): + The TPM-specific data provided by the + attesting platform, used to populate any of the + claims regarding platform state. + + This field is a member of `oneof`_ ``tee_attestation``. + challenge (str): + Required. The name of the Challenge whose nonce was used to + generate the attestation, in the format + projects/*/locations/*/challenges/\*. The provided Challenge + will be consumed, and cannot be used again. + """ + + tpm_attestation: "TpmAttestation" = proto.Field( + proto.MESSAGE, + number=2, + oneof="tee_attestation", + message="TpmAttestation", + ) + challenge: str = proto.Field( + proto.STRING, + number=1, + ) + + +class VerifyConfidentialGkeResponse(proto.Message): + r"""VerifyConfidentialGkeResponse response is returened once a + Confidential GKE attestation has been successfully verified, + containing a signed OIDC token. + + Attributes: + attestation_token (str): + Output only. The attestation token issued by + this service for Confidential GKE. It contains + specific platform claims based on the contents + of the provided attestation. + """ + + attestation_token: str = proto.Field( + proto.STRING, + number=1, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-confidentialcomputing/noxfile.py b/packages/google-cloud-confidentialcomputing/noxfile.py index 7992e58a1ad0..357c2ed2ce63 100644 --- a/packages/google-cloud-confidentialcomputing/noxfile.py +++ b/packages/google-cloud-confidentialcomputing/noxfile.py @@ -365,9 +365,10 @@ def docs(session): "-T", # show full traceback on exception "-N", # no colors "-b", - "html", + "html", # builder "-d", - os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", "_build", "doctrees", ""), # cache directory + # paths to build: os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) diff --git a/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_async.py b/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_async.py new file mode 100644 index 000000000000..f31b51fb713f --- /dev/null +++ b/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for VerifyConfidentialGke +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-confidentialcomputing + + +# [START confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialGke_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import confidentialcomputing_v1 + + +async def sample_verify_confidential_gke(): + # Create a client + client = confidentialcomputing_v1.ConfidentialComputingAsyncClient() + + # Initialize request argument(s) + request = confidentialcomputing_v1.VerifyConfidentialGkeRequest( + challenge="challenge_value", + ) + + # Make the request + response = await client.verify_confidential_gke(request=request) + + # Handle the response + print(response) + +# [END confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialGke_async] diff --git a/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_sync.py b/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_sync.py new file mode 100644 index 000000000000..f48c41b7d257 --- /dev/null +++ b/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for VerifyConfidentialGke +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-confidentialcomputing + + +# [START confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialGke_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import confidentialcomputing_v1 + + +def sample_verify_confidential_gke(): + # Create a client + client = confidentialcomputing_v1.ConfidentialComputingClient() + + # Initialize request argument(s) + request = confidentialcomputing_v1.VerifyConfidentialGkeRequest( + challenge="challenge_value", + ) + + # Make the request + response = client.verify_confidential_gke(request=request) + + # Handle the response + print(response) + +# [END confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialGke_sync] diff --git a/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_async.py b/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_async.py new file mode 100644 index 000000000000..2a518ead0d28 --- /dev/null +++ b/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for VerifyConfidentialSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-confidentialcomputing + + +# [START confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialSpace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import confidentialcomputing_v1 + + +async def sample_verify_confidential_space(): + # Create a client + client = confidentialcomputing_v1.ConfidentialComputingAsyncClient() + + # Initialize request argument(s) + request = confidentialcomputing_v1.VerifyConfidentialSpaceRequest( + challenge="challenge_value", + ) + + # Make the request + response = await client.verify_confidential_space(request=request) + + # Handle the response + print(response) + +# [END confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialSpace_async] diff --git a/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_sync.py b/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_sync.py new file mode 100644 index 000000000000..c7a2756f49bc --- /dev/null +++ b/packages/google-cloud-confidentialcomputing/samples/generated_samples/confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for VerifyConfidentialSpace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-confidentialcomputing + + +# [START confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialSpace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import confidentialcomputing_v1 + + +def sample_verify_confidential_space(): + # Create a client + client = confidentialcomputing_v1.ConfidentialComputingClient() + + # Initialize request argument(s) + request = confidentialcomputing_v1.VerifyConfidentialSpaceRequest( + challenge="challenge_value", + ) + + # Make the request + response = client.verify_confidential_space(request=request) + + # Handle the response + print(response) + +# [END confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialSpace_sync] diff --git a/packages/google-cloud-confidentialcomputing/samples/generated_samples/snippet_metadata_google.cloud.confidentialcomputing.v1.json b/packages/google-cloud-confidentialcomputing/samples/generated_samples/snippet_metadata_google.cloud.confidentialcomputing.v1.json index 09c4ea010a47..1994174817f3 100644 --- a/packages/google-cloud-confidentialcomputing/samples/generated_samples/snippet_metadata_google.cloud.confidentialcomputing.v1.json +++ b/packages/google-cloud-confidentialcomputing/samples/generated_samples/snippet_metadata_google.cloud.confidentialcomputing.v1.json @@ -332,6 +332,312 @@ } ], "title": "confidentialcomputing_v1_generated_confidential_computing_verify_attestation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.confidentialcomputing_v1.ConfidentialComputingAsyncClient", + "shortName": "ConfidentialComputingAsyncClient" + }, + "fullName": "google.cloud.confidentialcomputing_v1.ConfidentialComputingAsyncClient.verify_confidential_gke", + "method": { + "fullName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing.VerifyConfidentialGke", + "service": { + "fullName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing", + "shortName": "ConfidentialComputing" + }, + "shortName": "VerifyConfidentialGke" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.confidentialcomputing_v1.types.VerifyConfidentialGkeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.confidentialcomputing_v1.types.VerifyConfidentialGkeResponse", + "shortName": "verify_confidential_gke" + }, + "description": "Sample for VerifyConfidentialGke", + "file": "confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialGke_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.confidentialcomputing_v1.ConfidentialComputingClient", + "shortName": "ConfidentialComputingClient" + }, + "fullName": "google.cloud.confidentialcomputing_v1.ConfidentialComputingClient.verify_confidential_gke", + "method": { + "fullName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing.VerifyConfidentialGke", + "service": { + "fullName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing", + "shortName": "ConfidentialComputing" + }, + "shortName": "VerifyConfidentialGke" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.confidentialcomputing_v1.types.VerifyConfidentialGkeRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.confidentialcomputing_v1.types.VerifyConfidentialGkeResponse", + "shortName": "verify_confidential_gke" + }, + "description": "Sample for VerifyConfidentialGke", + "file": "confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialGke_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "confidentialcomputing_v1_generated_confidential_computing_verify_confidential_gke_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.confidentialcomputing_v1.ConfidentialComputingAsyncClient", + "shortName": "ConfidentialComputingAsyncClient" + }, + "fullName": "google.cloud.confidentialcomputing_v1.ConfidentialComputingAsyncClient.verify_confidential_space", + "method": { + "fullName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing.VerifyConfidentialSpace", + "service": { + "fullName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing", + "shortName": "ConfidentialComputing" + }, + "shortName": "VerifyConfidentialSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceResponse", + "shortName": "verify_confidential_space" + }, + "description": "Sample for VerifyConfidentialSpace", + "file": "confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialSpace_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.confidentialcomputing_v1.ConfidentialComputingClient", + "shortName": "ConfidentialComputingClient" + }, + "fullName": "google.cloud.confidentialcomputing_v1.ConfidentialComputingClient.verify_confidential_space", + "method": { + "fullName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing.VerifyConfidentialSpace", + "service": { + "fullName": "google.cloud.confidentialcomputing.v1.ConfidentialComputing", + "shortName": "ConfidentialComputing" + }, + "shortName": "VerifyConfidentialSpace" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.confidentialcomputing_v1.types.VerifyConfidentialSpaceResponse", + "shortName": "verify_confidential_space" + }, + "description": "Sample for VerifyConfidentialSpace", + "file": "confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "confidentialcomputing_v1_generated_ConfidentialComputing_VerifyConfidentialSpace_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "confidentialcomputing_v1_generated_confidential_computing_verify_confidential_space_sync.py" } ] } diff --git a/packages/google-cloud-confidentialcomputing/scripts/fixup_confidentialcomputing_v1_keywords.py b/packages/google-cloud-confidentialcomputing/scripts/fixup_confidentialcomputing_v1_keywords.py index 344a4f1c8a8b..6a8e4fb95705 100644 --- a/packages/google-cloud-confidentialcomputing/scripts/fixup_confidentialcomputing_v1_keywords.py +++ b/packages/google-cloud-confidentialcomputing/scripts/fixup_confidentialcomputing_v1_keywords.py @@ -41,6 +41,8 @@ class confidentialcomputingCallTransformer(cst.CSTTransformer): METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'create_challenge': ('parent', 'challenge', ), 'verify_attestation': ('challenge', 'tpm_attestation', 'td_ccel', 'sev_snp_attestation', 'gcp_credentials', 'confidential_space_info', 'token_options', 'attester', ), + 'verify_confidential_gke': ('challenge', 'tpm_attestation', ), + 'verify_confidential_space': ('challenge', 'td_ccel', 'tpm_attestation', 'gcp_credentials', 'signed_entities', 'gce_shielded_identity', 'options', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/packages/google-cloud-confidentialcomputing/tests/unit/gapic/confidentialcomputing_v1/test_confidential_computing.py b/packages/google-cloud-confidentialcomputing/tests/unit/gapic/confidentialcomputing_v1/test_confidential_computing.py index 930cdc8c9a09..18bdd65dd627 100644 --- a/packages/google-cloud-confidentialcomputing/tests/unit/gapic/confidentialcomputing_v1/test_confidential_computing.py +++ b/packages/google-cloud-confidentialcomputing/tests/unit/gapic/confidentialcomputing_v1/test_confidential_computing.py @@ -1770,13 +1770,81 @@ async def test_verify_attestation_field_headers_async(): ) in kw["metadata"] -def test_create_challenge_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + service.VerifyConfidentialSpaceRequest, + dict, + ], +) +def test_verify_confidential_space(request_type, transport: str = "grpc"): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_space), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.VerifyConfidentialSpaceResponse( + attestation_token="attestation_token_value", + ) + response = client.verify_confidential_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.VerifyConfidentialSpaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.VerifyConfidentialSpaceResponse) + assert response.attestation_token == "attestation_token_value" + + +def test_verify_confidential_space_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.VerifyConfidentialSpaceRequest( + challenge="challenge_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_space), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.verify_confidential_space(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.VerifyConfidentialSpaceRequest( + challenge="challenge_value", + ) + + +def test_verify_confidential_space_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -1784,7 +1852,10 @@ def test_create_challenge_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_challenge in client._transport._wrapped_methods + assert ( + client._transport.verify_confidential_space + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -1792,181 +1863,244 @@ def test_create_challenge_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_challenge + client._transport.verify_confidential_space ] = mock_rpc - request = {} - client.create_challenge(request) + client.verify_confidential_space(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_challenge(request) + client.verify_confidential_space(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_challenge_rest_required_fields( - request_type=service.CreateChallengeRequest, +@pytest.mark.asyncio +async def test_verify_confidential_space_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.ConfidentialComputingRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_challenge._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify required fields with default values are now present + # Ensure method has been cached + assert ( + client._client._transport.verify_confidential_space + in client._client._transport._wrapped_methods + ) - jsonified_request["parent"] = "parent_value" + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.verify_confidential_space + ] = mock_rpc - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_challenge._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + request = {} + await client.verify_confidential_space(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - client = ConfidentialComputingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.verify_confidential_space(request) - # Designate an appropriate value for the returned response. - return_value = service.Challenge() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.Challenge.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_verify_confidential_space_async( + transport: str = "grpc_asyncio", request_type=service.VerifyConfidentialSpaceRequest +): + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.create_challenge(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_space), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.VerifyConfidentialSpaceResponse( + attestation_token="attestation_token_value", + ) + ) + response = await client.verify_confidential_space(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.VerifyConfidentialSpaceRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, service.VerifyConfidentialSpaceResponse) + assert response.attestation_token == "attestation_token_value" -def test_create_challenge_rest_unset_required_fields(): - transport = transports.ConfidentialComputingRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.create_challenge._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "challenge", - ) - ) - ) +@pytest.mark.asyncio +async def test_verify_confidential_space_async_from_dict(): + await test_verify_confidential_space_async(request_type=dict) -def test_create_challenge_rest_flattened(): +def test_verify_confidential_space_field_headers(): client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.Challenge() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.VerifyConfidentialSpaceRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - challenge=service.Challenge(name="name_value"), - ) - mock_args.update(sample_request) + request.challenge = "challenge_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.Challenge.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_space), "__call__" + ) as call: + call.return_value = service.VerifyConfidentialSpaceResponse() + client.verify_confidential_space(request) - client.create_challenge(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/challenges" % client.transport._host, - args[1], - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "challenge=challenge_value", + ) in kw["metadata"] -def test_create_challenge_rest_flattened_error(transport: str = "rest"): - client = ConfidentialComputingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_verify_confidential_space_field_headers_async(): + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_challenge( - service.CreateChallengeRequest(), - parent="parent_value", - challenge=service.Challenge(name="name_value"), - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.VerifyConfidentialSpaceRequest() + request.challenge = "challenge_value" -def test_verify_attestation_rest_use_cached_wrapped_rpc(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_space), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.VerifyConfidentialSpaceResponse() + ) + await client.verify_confidential_space(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "challenge=challenge_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + service.VerifyConfidentialGkeRequest, + dict, + ], +) +def test_verify_confidential_gke(request_type, transport: str = "grpc"): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_gke), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.VerifyConfidentialGkeResponse( + attestation_token="attestation_token_value", + ) + response = client.verify_confidential_gke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.VerifyConfidentialGkeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.VerifyConfidentialGkeResponse) + assert response.attestation_token == "attestation_token_value" + + +def test_verify_confidential_gke_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.VerifyConfidentialGkeRequest( + challenge="challenge_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_gke), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.verify_confidential_gke(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.VerifyConfidentialGkeRequest( + challenge="challenge_value", + ) + + +def test_verify_confidential_gke_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -1975,7 +2109,8 @@ def test_verify_attestation_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.verify_attestation in client._transport._wrapped_methods + client._transport.verify_confidential_gke + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -1984,29 +2119,214 @@ def test_verify_attestation_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.verify_attestation + client._transport.verify_confidential_gke + ] = mock_rpc + request = {} + client.verify_confidential_gke(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.verify_confidential_gke(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_verify_confidential_gke_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.verify_confidential_gke + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.verify_confidential_gke ] = mock_rpc request = {} - client.verify_attestation(request) + await client.verify_confidential_gke(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.verify_attestation(request) + await client.verify_confidential_gke(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_verify_attestation_rest_required_fields( - request_type=service.VerifyAttestationRequest, +@pytest.mark.asyncio +async def test_verify_confidential_gke_async( + transport: str = "grpc_asyncio", request_type=service.VerifyConfidentialGkeRequest +): + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_gke), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.VerifyConfidentialGkeResponse( + attestation_token="attestation_token_value", + ) + ) + response = await client.verify_confidential_gke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.VerifyConfidentialGkeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.VerifyConfidentialGkeResponse) + assert response.attestation_token == "attestation_token_value" + + +@pytest.mark.asyncio +async def test_verify_confidential_gke_async_from_dict(): + await test_verify_confidential_gke_async(request_type=dict) + + +def test_verify_confidential_gke_field_headers(): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.VerifyConfidentialGkeRequest() + + request.challenge = "challenge_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_gke), "__call__" + ) as call: + call.return_value = service.VerifyConfidentialGkeResponse() + client.verify_confidential_gke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "challenge=challenge_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_verify_confidential_gke_field_headers_async(): + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.VerifyConfidentialGkeRequest() + + request.challenge = "challenge_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_gke), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.VerifyConfidentialGkeResponse() + ) + await client.verify_confidential_gke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "challenge=challenge_value", + ) in kw["metadata"] + + +def test_create_challenge_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_challenge in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_challenge + ] = mock_rpc + + request = {} + client.create_challenge(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_challenge(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_challenge_rest_required_fields( + request_type=service.CreateChallengeRequest, ): transport_class = transports.ConfidentialComputingRestTransport request_init = {} - request_init["challenge"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -2017,21 +2337,21 @@ def test_verify_attestation_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).verify_attestation._get_unset_required_fields(jsonified_request) + ).create_challenge._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["challenge"] = "challenge_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).verify_attestation._get_unset_required_fields(jsonified_request) + ).create_challenge._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "challenge" in jsonified_request - assert jsonified_request["challenge"] == "challenge_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2040,7 +2360,7 @@ def test_verify_attestation_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.VerifyAttestationResponse() + return_value = service.Challenge() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -2062,272 +2382,1160 @@ def test_verify_attestation_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.VerifyAttestationResponse.pb(return_value) + return_value = service.Challenge.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.verify_attestation(request) + response = client.create_challenge(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_verify_attestation_rest_unset_required_fields(): +def test_create_challenge_rest_unset_required_fields(): transport = transports.ConfidentialComputingRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.verify_attestation._get_unset_required_fields({}) + unset_fields = transport.create_challenge._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set( ( + "parent", "challenge", - "tpmAttestation", ) ) ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConfidentialComputingGrpcTransport( +def test_create_challenge_rest_flattened(): + client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ConfidentialComputingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.Challenge() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + challenge=service.Challenge(name="name_value"), ) + mock_args.update(sample_request) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConfidentialComputingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConfidentialComputingClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.Challenge.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_challenge(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/challenges" % client.transport._host, + args[1], ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ConfidentialComputingGrpcTransport( + +def test_create_challenge_rest_flattened_error(transport: str = "rest"): + client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConfidentialComputingClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): - client = ConfidentialComputingClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client.create_challenge( + service.CreateChallengeRequest(), + parent="parent_value", + challenge=service.Challenge(name="name_value"), ) - # It is an error to provide scopes and a transport instance. - transport = transports.ConfidentialComputingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): + +def test_verify_attestation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = ConfidentialComputingClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConfidentialComputingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConfidentialComputingClient(transport=transport) - assert client.transport is transport - + # Ensure method has been cached + assert ( + client._transport.verify_attestation in client._transport._wrapped_methods + ) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConfidentialComputingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.verify_attestation + ] = mock_rpc - transport = transports.ConfidentialComputingGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + request = {} + client.verify_attestation(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -@pytest.mark.parametrize( - "transport_class", - [ - transports.ConfidentialComputingGrpcTransport, - transports.ConfidentialComputingGrpcAsyncIOTransport, - transports.ConfidentialComputingRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + client.verify_attestation(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -def test_transport_kind_grpc(): - transport = ConfidentialComputingClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" +def test_verify_attestation_rest_required_fields( + request_type=service.VerifyAttestationRequest, +): + transport_class = transports.ConfidentialComputingRestTransport -def test_initialize_client_w_grpc(): - client = ConfidentialComputingClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + request_init = {} + request_init["challenge"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) - assert client is not None + # verify fields with default values are dropped -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_challenge_empty_call_grpc(): - client = ConfidentialComputingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).verify_attestation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_challenge), "__call__") as call: - call.return_value = service.Challenge() - client.create_challenge(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateChallengeRequest() + jsonified_request["challenge"] = "challenge_value" - assert args[0] == request_msg + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).verify_attestation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with non-default values are left alone + assert "challenge" in jsonified_request + assert jsonified_request["challenge"] == "challenge_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_verify_attestation_empty_call_grpc(): client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.verify_attestation), "__call__" - ) as call: - call.return_value = service.VerifyAttestationResponse() - client.verify_attestation(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.VerifyAttestationRequest() + # Designate an appropriate value for the returned response. + return_value = service.VerifyAttestationResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.VerifyAttestationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) -def test_transport_kind_grpc_asyncio(): - transport = ConfidentialComputingAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.verify_attestation(request) -def test_initialize_client_w_grpc_asyncio(): + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_verify_attestation_rest_unset_required_fields(): + transport = transports.ConfidentialComputingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.verify_attestation._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "challenge", + "tpmAttestation", + ) + ) + ) + + +def test_verify_confidential_space_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.verify_confidential_space + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.verify_confidential_space + ] = mock_rpc + + request = {} + client.verify_confidential_space(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.verify_confidential_space(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_verify_confidential_space_rest_required_fields( + request_type=service.VerifyConfidentialSpaceRequest, +): + transport_class = transports.ConfidentialComputingRestTransport + + request_init = {} + request_init["challenge"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).verify_confidential_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["challenge"] = "challenge_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).verify_confidential_space._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "challenge" in jsonified_request + assert jsonified_request["challenge"] == "challenge_value" + + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.VerifyConfidentialSpaceResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.VerifyConfidentialSpaceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.verify_confidential_space(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_verify_confidential_space_rest_unset_required_fields(): + transport = transports.ConfidentialComputingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.verify_confidential_space._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("challenge",))) + + +def test_verify_confidential_gke_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.verify_confidential_gke + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.verify_confidential_gke + ] = mock_rpc + + request = {} + client.verify_confidential_gke(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.verify_confidential_gke(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_verify_confidential_gke_rest_required_fields( + request_type=service.VerifyConfidentialGkeRequest, +): + transport_class = transports.ConfidentialComputingRestTransport + + request_init = {} + request_init["challenge"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).verify_confidential_gke._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["challenge"] = "challenge_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).verify_confidential_gke._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "challenge" in jsonified_request + assert jsonified_request["challenge"] == "challenge_value" + + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.VerifyConfidentialGkeResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.VerifyConfidentialGkeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.verify_confidential_gke(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_verify_confidential_gke_rest_unset_required_fields(): + transport = transports.ConfidentialComputingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.verify_confidential_gke._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("challenge",))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ConfidentialComputingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConfidentialComputingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfidentialComputingClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ConfidentialComputingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConfidentialComputingClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConfidentialComputingClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConfidentialComputingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfidentialComputingClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConfidentialComputingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConfidentialComputingClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConfidentialComputingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConfidentialComputingGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConfidentialComputingGrpcTransport, + transports.ConfidentialComputingGrpcAsyncIOTransport, + transports.ConfidentialComputingRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = ConfidentialComputingClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_challenge_empty_call_grpc(): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_challenge), "__call__") as call: + call.return_value = service.Challenge() + client.create_challenge(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateChallengeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_verify_attestation_empty_call_grpc(): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_attestation), "__call__" + ) as call: + call.return_value = service.VerifyAttestationResponse() + client.verify_attestation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.VerifyAttestationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_verify_confidential_space_empty_call_grpc(): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_space), "__call__" + ) as call: + call.return_value = service.VerifyConfidentialSpaceResponse() + client.verify_confidential_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.VerifyConfidentialSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_verify_confidential_gke_empty_call_grpc(): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_gke), "__call__" + ) as call: + call.return_value = service.VerifyConfidentialGkeResponse() + client.verify_confidential_gke(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.VerifyConfidentialGkeRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ConfidentialComputingAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): client = ConfidentialComputingAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - assert client is not None + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_challenge_empty_call_grpc_asyncio(): + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_challenge), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.Challenge( + name="name_value", + used=True, + tpm_nonce="tpm_nonce_value", + ) + ) + await client.create_challenge(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateChallengeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_verify_attestation_empty_call_grpc_asyncio(): + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_attestation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.VerifyAttestationResponse( + oidc_claims_token="oidc_claims_token_value", + ) + ) + await client.verify_attestation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.VerifyAttestationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_verify_confidential_space_empty_call_grpc_asyncio(): + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_space), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.VerifyConfidentialSpaceResponse( + attestation_token="attestation_token_value", + ) + ) + await client.verify_confidential_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.VerifyConfidentialSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_verify_confidential_gke_empty_call_grpc_asyncio(): + client = ConfidentialComputingAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_gke), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.VerifyConfidentialGkeResponse( + attestation_token="attestation_token_value", + ) + ) + await client.verify_confidential_gke(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.VerifyConfidentialGkeRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ConfidentialComputingClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_challenge_rest_bad_request(request_type=service.CreateChallengeRequest): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_challenge(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateChallengeRequest, + dict, + ], +) +def test_create_challenge_rest_call_success(request_type): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["challenge"] = { + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "expire_time": {}, + "used": True, + "tpm_nonce": "tpm_nonce_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateChallengeRequest.meta.fields["challenge"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_challenge_empty_call_grpc_asyncio(): - client = ConfidentialComputingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["challenge"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["challenge"][field])): + del request_init["challenge"][field][i][subfield] + else: + del request_init["challenge"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.Challenge( + name="name_value", + used=True, + tpm_nonce="tpm_nonce_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.Challenge.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_challenge(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Challenge) + assert response.name == "name_value" + assert response.used is True + assert response.tpm_nonce == "tpm_nonce_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_challenge_rest_interceptors(null_interceptor): + transport = transports.ConfidentialComputingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ConfidentialComputingRestInterceptor(), ) + client = ConfidentialComputingClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_challenge), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.Challenge( - name="name_value", - used=True, - tpm_nonce="tpm_nonce_value", - ) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ConfidentialComputingRestInterceptor, "post_create_challenge" + ) as post, mock.patch.object( + transports.ConfidentialComputingRestInterceptor, + "post_create_challenge_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.ConfidentialComputingRestInterceptor, "pre_create_challenge" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateChallengeRequest.pb(service.CreateChallengeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.Challenge.to_json(service.Challenge()) + req.return_value.content = return_value + + request = service.CreateChallengeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.Challenge() + post_with_metadata.return_value = service.Challenge(), metadata + + client.create_challenge( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - await client.create_challenge(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateChallengeRequest() + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_verify_attestation_rest_bad_request( + request_type=service.VerifyAttestationRequest, +): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "challenge": "projects/sample1/locations/sample2/challenges/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.verify_attestation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.VerifyAttestationRequest, + dict, + ], +) +def test_verify_attestation_rest_call_success(request_type): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "challenge": "projects/sample1/locations/sample2/challenges/sample3" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.VerifyAttestationResponse( + oidc_claims_token="oidc_claims_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.VerifyAttestationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.verify_attestation(request) - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, service.VerifyAttestationResponse) + assert response.oidc_claims_token == "oidc_claims_token_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_verify_attestation_empty_call_grpc_asyncio(): - client = ConfidentialComputingAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_verify_attestation_rest_interceptors(null_interceptor): + transport = transports.ConfidentialComputingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ConfidentialComputingRestInterceptor(), ) + client = ConfidentialComputingClient(transport=transport) - # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.verify_attestation), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.VerifyAttestationResponse( - oidc_claims_token="oidc_claims_token_value", - ) + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ConfidentialComputingRestInterceptor, "post_verify_attestation" + ) as post, mock.patch.object( + transports.ConfidentialComputingRestInterceptor, + "post_verify_attestation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.ConfidentialComputingRestInterceptor, "pre_verify_attestation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.VerifyAttestationRequest.pb( + service.VerifyAttestationRequest() ) - await client.verify_attestation(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.VerifyAttestationRequest() + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.VerifyAttestationResponse.to_json( + service.VerifyAttestationResponse() + ) + req.return_value.content = return_value - assert args[0] == request_msg + request = service.VerifyAttestationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.VerifyAttestationResponse() + post_with_metadata.return_value = service.VerifyAttestationResponse(), metadata + client.verify_attestation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = ConfidentialComputingClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_create_challenge_rest_bad_request(request_type=service.CreateChallengeRequest): +def test_verify_confidential_space_rest_bad_request( + request_type=service.VerifyConfidentialSpaceRequest, +): client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "challenge": "projects/sample1/locations/sample2/challenges/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -2342,106 +3550,32 @@ def test_create_challenge_rest_bad_request(request_type=service.CreateChallengeR response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_challenge(request) + client.verify_confidential_space(request) @pytest.mark.parametrize( "request_type", [ - service.CreateChallengeRequest, + service.VerifyConfidentialSpaceRequest, dict, ], ) -def test_create_challenge_rest_call_success(request_type): +def test_verify_confidential_space_rest_call_success(request_type): client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["challenge"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "expire_time": {}, - "used": True, - "tpm_nonce": "tpm_nonce_value", + request_init = { + "challenge": "projects/sample1/locations/sample2/challenges/sample3" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateChallengeRequest.meta.fields["challenge"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["challenge"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["challenge"][field])): - del request_init["challenge"][field][i][subfield] - else: - del request_init["challenge"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.Challenge( - name="name_value", - used=True, - tpm_nonce="tpm_nonce_value", + return_value = service.VerifyConfidentialSpaceResponse( + attestation_token="attestation_token_value", ) # Wrap the value into a proper Response obj @@ -2449,22 +3583,20 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.Challenge.pb(return_value) + return_value = service.VerifyConfidentialSpaceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_challenge(request) + response = client.verify_confidential_space(request) # Establish that the response is the type that we expect. - assert isinstance(response, service.Challenge) - assert response.name == "name_value" - assert response.used is True - assert response.tpm_nonce == "tpm_nonce_value" + assert isinstance(response, service.VerifyConfidentialSpaceResponse) + assert response.attestation_token == "attestation_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_challenge_rest_interceptors(null_interceptor): +def test_verify_confidential_space_rest_interceptors(null_interceptor): transport = transports.ConfidentialComputingRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2478,17 +3610,20 @@ def test_create_challenge_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfidentialComputingRestInterceptor, "post_create_challenge" + transports.ConfidentialComputingRestInterceptor, + "post_verify_confidential_space", ) as post, mock.patch.object( transports.ConfidentialComputingRestInterceptor, - "post_create_challenge_with_metadata", + "post_verify_confidential_space_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConfidentialComputingRestInterceptor, "pre_create_challenge" + transports.ConfidentialComputingRestInterceptor, "pre_verify_confidential_space" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.CreateChallengeRequest.pb(service.CreateChallengeRequest()) + pb_message = service.VerifyConfidentialSpaceRequest.pb( + service.VerifyConfidentialSpaceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2499,19 +3634,24 @@ def test_create_challenge_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.Challenge.to_json(service.Challenge()) + return_value = service.VerifyConfidentialSpaceResponse.to_json( + service.VerifyConfidentialSpaceResponse() + ) req.return_value.content = return_value - request = service.CreateChallengeRequest() + request = service.VerifyConfidentialSpaceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.Challenge() - post_with_metadata.return_value = service.Challenge(), metadata + post.return_value = service.VerifyConfidentialSpaceResponse() + post_with_metadata.return_value = ( + service.VerifyConfidentialSpaceResponse(), + metadata, + ) - client.create_challenge( + client.verify_confidential_space( request, metadata=[ ("key", "val"), @@ -2524,8 +3664,8 @@ def test_create_challenge_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_verify_attestation_rest_bad_request( - request_type=service.VerifyAttestationRequest, +def test_verify_confidential_gke_rest_bad_request( + request_type=service.VerifyConfidentialGkeRequest, ): client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2548,17 +3688,17 @@ def test_verify_attestation_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.verify_attestation(request) + client.verify_confidential_gke(request) @pytest.mark.parametrize( "request_type", [ - service.VerifyAttestationRequest, + service.VerifyConfidentialGkeRequest, dict, ], ) -def test_verify_attestation_rest_call_success(request_type): +def test_verify_confidential_gke_rest_call_success(request_type): client = ConfidentialComputingClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2572,8 +3712,8 @@ def test_verify_attestation_rest_call_success(request_type): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.VerifyAttestationResponse( - oidc_claims_token="oidc_claims_token_value", + return_value = service.VerifyConfidentialGkeResponse( + attestation_token="attestation_token_value", ) # Wrap the value into a proper Response obj @@ -2581,20 +3721,20 @@ def test_verify_attestation_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.VerifyAttestationResponse.pb(return_value) + return_value = service.VerifyConfidentialGkeResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.verify_attestation(request) + response = client.verify_confidential_gke(request) # Establish that the response is the type that we expect. - assert isinstance(response, service.VerifyAttestationResponse) - assert response.oidc_claims_token == "oidc_claims_token_value" + assert isinstance(response, service.VerifyConfidentialGkeResponse) + assert response.attestation_token == "attestation_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_verify_attestation_rest_interceptors(null_interceptor): +def test_verify_confidential_gke_rest_interceptors(null_interceptor): transport = transports.ConfidentialComputingRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2608,18 +3748,18 @@ def test_verify_attestation_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfidentialComputingRestInterceptor, "post_verify_attestation" + transports.ConfidentialComputingRestInterceptor, "post_verify_confidential_gke" ) as post, mock.patch.object( transports.ConfidentialComputingRestInterceptor, - "post_verify_attestation_with_metadata", + "post_verify_confidential_gke_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.ConfidentialComputingRestInterceptor, "pre_verify_attestation" + transports.ConfidentialComputingRestInterceptor, "pre_verify_confidential_gke" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.VerifyAttestationRequest.pb( - service.VerifyAttestationRequest() + pb_message = service.VerifyConfidentialGkeRequest.pb( + service.VerifyConfidentialGkeRequest() ) transcode.return_value = { "method": "post", @@ -2631,21 +3771,24 @@ def test_verify_attestation_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.VerifyAttestationResponse.to_json( - service.VerifyAttestationResponse() + return_value = service.VerifyConfidentialGkeResponse.to_json( + service.VerifyConfidentialGkeResponse() ) req.return_value.content = return_value - request = service.VerifyAttestationRequest() + request = service.VerifyConfidentialGkeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.VerifyAttestationResponse() - post_with_metadata.return_value = service.VerifyAttestationResponse(), metadata + post.return_value = service.VerifyConfidentialGkeResponse() + post_with_metadata.return_value = ( + service.VerifyConfidentialGkeResponse(), + metadata, + ) - client.verify_attestation( + client.verify_confidential_gke( request, metadata=[ ("key", "val"), @@ -2827,6 +3970,50 @@ def test_verify_attestation_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_verify_confidential_space_empty_call_rest(): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_space), "__call__" + ) as call: + client.verify_confidential_space(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.VerifyConfidentialSpaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_verify_confidential_gke_empty_call_rest(): + client = ConfidentialComputingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_confidential_gke), "__call__" + ) as call: + client.verify_confidential_gke(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.VerifyConfidentialGkeRequest() + + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = ConfidentialComputingClient( @@ -2862,6 +4049,8 @@ def test_confidential_computing_base_transport(): methods = ( "create_challenge", "verify_attestation", + "verify_confidential_space", + "verify_confidential_gke", "get_location", "list_locations", ) @@ -3130,6 +4319,12 @@ def test_confidential_computing_client_transport_session_collision(transport_nam session1 = client1.transport.verify_attestation._session session2 = client2.transport.verify_attestation._session assert session1 != session2 + session1 = client1.transport.verify_confidential_space._session + session2 = client2.transport.verify_confidential_space._session + assert session1 != session2 + session1 = client1.transport.verify_confidential_gke._session + session2 = client2.transport.verify_confidential_gke._session + assert session1 != session2 def test_confidential_computing_grpc_transport_channel():