diff --git a/.coveragerc b/.coveragerc index c4d733d..82179d1 100644 --- a/.coveragerc +++ b/.coveragerc @@ -5,6 +5,7 @@ branch = True show_missing = True omit = google/cloud/binaryauthorization/__init__.py + google/cloud/binaryauthorization/gapic_version.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 889f77d..5fc5daa 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320 + digest: sha256:8555f0e37e6261408f792bfd6635102d2da5ad73f8f09bcb24f25e6afb5fac97 diff --git a/.kokoro/requirements.in b/.kokoro/requirements.in index cbd7e77..882178c 100644 --- a/.kokoro/requirements.in +++ b/.kokoro/requirements.in @@ -1,5 +1,5 @@ gcp-docuploader -gcp-releasetool +gcp-releasetool>=1.10.5 # required for compatibility with cryptography>=39.x importlib-metadata typing-extensions twine diff --git a/.kokoro/requirements.txt b/.kokoro/requirements.txt index 05dc467..fa99c12 100644 --- a/.kokoro/requirements.txt +++ b/.kokoro/requirements.txt @@ -113,33 +113,28 @@ commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via rich -cryptography==38.0.3 \ - --hash=sha256:068147f32fa662c81aebab95c74679b401b12b57494872886eb5c1139250ec5d \ - --hash=sha256:06fc3cc7b6f6cca87bd56ec80a580c88f1da5306f505876a71c8cfa7050257dd \ - --hash=sha256:25c1d1f19729fb09d42e06b4bf9895212292cb27bb50229f5aa64d039ab29146 \ - --hash=sha256:402852a0aea73833d982cabb6d0c3bb582c15483d29fb7085ef2c42bfa7e38d7 \ - --hash=sha256:4e269dcd9b102c5a3d72be3c45d8ce20377b8076a43cbed6f660a1afe365e436 \ - --hash=sha256:5419a127426084933076132d317911e3c6eb77568a1ce23c3ac1e12d111e61e0 \ - --hash=sha256:554bec92ee7d1e9d10ded2f7e92a5d70c1f74ba9524947c0ba0c850c7b011828 \ - --hash=sha256:5e89468fbd2fcd733b5899333bc54d0d06c80e04cd23d8c6f3e0542358c6060b \ - --hash=sha256:65535bc550b70bd6271984d9863a37741352b4aad6fb1b3344a54e6950249b55 \ - --hash=sha256:6ab9516b85bebe7aa83f309bacc5f44a61eeb90d0b4ec125d2d003ce41932d36 \ - --hash=sha256:6addc3b6d593cd980989261dc1cce38263c76954d758c3c94de51f1e010c9a50 \ - --hash=sha256:728f2694fa743a996d7784a6194da430f197d5c58e2f4e278612b359f455e4a2 \ - --hash=sha256:785e4056b5a8b28f05a533fab69febf5004458e20dad7e2e13a3120d8ecec75a \ - --hash=sha256:78cf5eefac2b52c10398a42765bfa981ce2372cbc0457e6bf9658f41ec3c41d8 \ - --hash=sha256:7f836217000342d448e1c9a342e9163149e45d5b5eca76a30e84503a5a96cab0 \ - --hash=sha256:8d41a46251bf0634e21fac50ffd643216ccecfaf3701a063257fe0b2be1b6548 \ - --hash=sha256:984fe150f350a3c91e84de405fe49e688aa6092b3525f407a18b9646f6612320 \ - --hash=sha256:9b24bcff7853ed18a63cfb0c2b008936a9554af24af2fb146e16d8e1aed75748 \ - --hash=sha256:b1b35d9d3a65542ed2e9d90115dfd16bbc027b3f07ee3304fc83580f26e43249 \ - --hash=sha256:b1b52c9e5f8aa2b802d48bd693190341fae201ea51c7a167d69fc48b60e8a959 \ - --hash=sha256:bbf203f1a814007ce24bd4d51362991d5cb90ba0c177a9c08825f2cc304d871f \ - --hash=sha256:be243c7e2bfcf6cc4cb350c0d5cdf15ca6383bbcb2a8ef51d3c9411a9d4386f0 \ - --hash=sha256:bfbe6ee19615b07a98b1d2287d6a6073f734735b49ee45b11324d85efc4d5cbd \ - --hash=sha256:c46837ea467ed1efea562bbeb543994c2d1f6e800785bd5a2c98bc096f5cb220 \ - --hash=sha256:dfb4f4dd568de1b6af9f4cda334adf7d72cf5bc052516e1b2608b683375dd95c \ - --hash=sha256:ed7b00096790213e09eb11c97cc6e2b757f15f3d2f85833cd2d3ec3fe37c1722 +cryptography==39.0.1 \ + --hash=sha256:0f8da300b5c8af9f98111ffd512910bc792b4c77392a9523624680f7956a99d4 \ + --hash=sha256:35f7c7d015d474f4011e859e93e789c87d21f6f4880ebdc29896a60403328f1f \ + --hash=sha256:5aa67414fcdfa22cf052e640cb5ddc461924a045cacf325cd164e65312d99502 \ + --hash=sha256:5d2d8b87a490bfcd407ed9d49093793d0f75198a35e6eb1a923ce1ee86c62b41 \ + --hash=sha256:6687ef6d0a6497e2b58e7c5b852b53f62142cfa7cd1555795758934da363a965 \ + --hash=sha256:6f8ba7f0328b79f08bdacc3e4e66fb4d7aab0c3584e0bd41328dce5262e26b2e \ + --hash=sha256:706843b48f9a3f9b9911979761c91541e3d90db1ca905fd63fee540a217698bc \ + --hash=sha256:807ce09d4434881ca3a7594733669bd834f5b2c6d5c7e36f8c00f691887042ad \ + --hash=sha256:83e17b26de248c33f3acffb922748151d71827d6021d98c70e6c1a25ddd78505 \ + --hash=sha256:96f1157a7c08b5b189b16b47bc9db2332269d6680a196341bf30046330d15388 \ + --hash=sha256:aec5a6c9864be7df2240c382740fcf3b96928c46604eaa7f3091f58b878c0bb6 \ + --hash=sha256:b0afd054cd42f3d213bf82c629efb1ee5f22eba35bf0eec88ea9ea7304f511a2 \ + --hash=sha256:ced4e447ae29ca194449a3f1ce132ded8fcab06971ef5f618605aacaa612beac \ + --hash=sha256:d1f6198ee6d9148405e49887803907fe8962a23e6c6f83ea7d98f1c0de375695 \ + --hash=sha256:e124352fd3db36a9d4a21c1aa27fd5d051e621845cb87fb851c08f4f75ce8be6 \ + --hash=sha256:e422abdec8b5fa8462aa016786680720d78bdce7a30c652b7fadf83a4ba35336 \ + --hash=sha256:ef8b72fa70b348724ff1218267e7f7375b8de4e8194d1636ee60510aae104cd0 \ + --hash=sha256:f0c64d1bd842ca2633e74a1a28033d139368ad959872533b1bab8c80e8240a0c \ + --hash=sha256:f24077a3b5298a5a06a8e0536e3ea9ec60e4c7ac486755e5fb6e6ea9b3500106 \ + --hash=sha256:fdd188c8a6ef8769f148f88f859884507b954cc64db6b52f66ef199bb9ad660a \ + --hash=sha256:fe913f20024eb2cb2f323e42a64bdf2911bb9738a15dba7d3cce48151034e3a8 # via # gcp-releasetool # secretstorage @@ -159,9 +154,9 @@ gcp-docuploader==0.6.4 \ --hash=sha256:01486419e24633af78fd0167db74a2763974765ee8078ca6eb6964d0ebd388af \ --hash=sha256:70861190c123d907b3b067da896265ead2eeb9263969d6955c9e0bb091b5ccbf # via -r requirements.in -gcp-releasetool==1.10.0 \ - --hash=sha256:72a38ca91b59c24f7e699e9227c90cbe4dd71b789383cb0164b088abae294c83 \ - --hash=sha256:8c7c99320208383d4bb2b808c6880eb7a81424afe7cdba3c8d84b25f4f0e097d +gcp-releasetool==1.10.5 \ + --hash=sha256:174b7b102d704b254f2a26a3eda2c684fd3543320ec239baf771542a2e58e109 \ + --hash=sha256:e29d29927fe2ca493105a82958c6873bb2b90d503acac56be2c229e74de0eec9 # via -r requirements.in google-api-core==2.10.2 \ --hash=sha256:10c06f7739fe57781f87523375e8e1a3a4674bf6392cd6131a3222182b971320 \ diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e20d7e8..0d1bebe 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.5.1" + ".": "1.6.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c074d9..69c01d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [1.6.0](https://github.com/googleapis/python-binary-authorization/compare/v1.5.1...v1.6.0) (2023-02-27) + + +### Features + +* Enable "rest" transport in Python for services supporting numeric enums ([#204](https://github.com/googleapis/python-binary-authorization/issues/204)) ([3ef88ce](https://github.com/googleapis/python-binary-authorization/commit/3ef88cecf3af6a7945a4fe6a30dfd6c47e56c725)) + ## [1.5.1](https://github.com/googleapis/python-binary-authorization/compare/v1.5.0...v1.5.1) (2023-01-20) diff --git a/google/cloud/binaryauthorization/gapic_version.py b/google/cloud/binaryauthorization/gapic_version.py index 69ff013..a016bdf 100644 --- a/google/cloud/binaryauthorization/gapic_version.py +++ b/google/cloud/binaryauthorization/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.5.1" # {x-release-please-version} +__version__ = "1.6.0" # {x-release-please-version} diff --git a/google/cloud/binaryauthorization_v1/__init__.py b/google/cloud/binaryauthorization_v1/__init__.py index a4b47c1..f454660 100644 --- a/google/cloud/binaryauthorization_v1/__init__.py +++ b/google/cloud/binaryauthorization_v1/__init__.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.binaryauthorization import gapic_version as package_version +from google.cloud.binaryauthorization_v1 import gapic_version as package_version __version__ = package_version.__version__ diff --git a/google/cloud/binaryauthorization_v1/gapic_metadata.json b/google/cloud/binaryauthorization_v1/gapic_metadata.json index 1d349e7..d201846 100644 --- a/google/cloud/binaryauthorization_v1/gapic_metadata.json +++ b/google/cloud/binaryauthorization_v1/gapic_metadata.json @@ -86,6 +86,46 @@ ] } } + }, + "rest": { + "libraryClient": "BinauthzManagementServiceV1Client", + "rpcs": { + "CreateAttestor": { + "methods": [ + "create_attestor" + ] + }, + "DeleteAttestor": { + "methods": [ + "delete_attestor" + ] + }, + "GetAttestor": { + "methods": [ + "get_attestor" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListAttestors": { + "methods": [ + "list_attestors" + ] + }, + "UpdateAttestor": { + "methods": [ + "update_attestor" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } } } }, @@ -110,6 +150,16 @@ ] } } + }, + "rest": { + "libraryClient": "SystemPolicyV1Client", + "rpcs": { + "GetSystemPolicy": { + "methods": [ + "get_system_policy" + ] + } + } } } }, @@ -134,6 +184,16 @@ ] } } + }, + "rest": { + "libraryClient": "ValidationHelperV1Client", + "rpcs": { + "ValidateAttestationOccurrence": { + "methods": [ + "validate_attestation_occurrence" + ] + } + } } } } diff --git a/google/cloud/binaryauthorization_v1/gapic_version.py b/google/cloud/binaryauthorization_v1/gapic_version.py index 69ff013..a016bdf 100644 --- a/google/cloud/binaryauthorization_v1/gapic_version.py +++ b/google/cloud/binaryauthorization_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.5.1" # {x-release-please-version} +__version__ = "1.6.0" # {x-release-please-version} diff --git a/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py b/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py index 11195b2..79a725b 100644 --- a/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py +++ b/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py @@ -56,6 +56,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, BinauthzManagementServiceV1Transport from .transports.grpc import BinauthzManagementServiceV1GrpcTransport from .transports.grpc_asyncio import BinauthzManagementServiceV1GrpcAsyncIOTransport +from .transports.rest import BinauthzManagementServiceV1RestTransport class BinauthzManagementServiceV1ClientMeta(type): @@ -73,6 +74,7 @@ class BinauthzManagementServiceV1ClientMeta(type): _transport_registry[ "grpc_asyncio" ] = BinauthzManagementServiceV1GrpcAsyncIOTransport + _transport_registry["rest"] = BinauthzManagementServiceV1RestTransport def get_transport_class( cls, diff --git a/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/__init__.py b/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/__init__.py index 4f62838..c806f94 100644 --- a/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/__init__.py +++ b/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/__init__.py @@ -19,6 +19,10 @@ from .base import BinauthzManagementServiceV1Transport from .grpc import BinauthzManagementServiceV1GrpcTransport from .grpc_asyncio import BinauthzManagementServiceV1GrpcAsyncIOTransport +from .rest import ( + BinauthzManagementServiceV1RestInterceptor, + BinauthzManagementServiceV1RestTransport, +) # Compile a registry of transports. _transport_registry = ( @@ -26,9 +30,12 @@ ) # type: Dict[str, Type[BinauthzManagementServiceV1Transport]] _transport_registry["grpc"] = BinauthzManagementServiceV1GrpcTransport _transport_registry["grpc_asyncio"] = BinauthzManagementServiceV1GrpcAsyncIOTransport +_transport_registry["rest"] = BinauthzManagementServiceV1RestTransport __all__ = ( "BinauthzManagementServiceV1Transport", "BinauthzManagementServiceV1GrpcTransport", "BinauthzManagementServiceV1GrpcAsyncIOTransport", + "BinauthzManagementServiceV1RestTransport", + "BinauthzManagementServiceV1RestInterceptor", ) diff --git a/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py b/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py new file mode 100644 index 0000000..8b2451e --- /dev/null +++ b/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py @@ -0,0 +1,1074 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.binaryauthorization_v1.types import resources, service + +from .base import BinauthzManagementServiceV1Transport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class BinauthzManagementServiceV1RestInterceptor: + """Interceptor for BinauthzManagementServiceV1. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the BinauthzManagementServiceV1RestTransport. + + .. code-block:: python + class MyCustomBinauthzManagementServiceV1Interceptor(BinauthzManagementServiceV1RestInterceptor): + def pre_create_attestor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_attestor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_attestor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_attestor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_attestor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_attestors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_attestors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_attestor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_attestor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BinauthzManagementServiceV1RestTransport(interceptor=MyCustomBinauthzManagementServiceV1Interceptor()) + client = BinauthzManagementServiceV1Client(transport=transport) + + + """ + + def pre_create_attestor( + self, + request: service.CreateAttestorRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateAttestorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_attestor + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 server. + """ + return request, metadata + + def post_create_attestor(self, response: resources.Attestor) -> resources.Attestor: + """Post-rpc interceptor for create_attestor + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1 server but before + it is returned to user code. + """ + return response + + def pre_delete_attestor( + self, + request: service.DeleteAttestorRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.DeleteAttestorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_attestor + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 server. + """ + return request, metadata + + def pre_get_attestor( + self, request: service.GetAttestorRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetAttestorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_attestor + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 server. + """ + return request, metadata + + def post_get_attestor(self, response: resources.Attestor) -> resources.Attestor: + """Post-rpc interceptor for get_attestor + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1 server but before + it is returned to user code. + """ + return response + + def pre_get_policy( + self, request: service.GetPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 server. + """ + return request, metadata + + def post_get_policy(self, response: resources.Policy) -> resources.Policy: + """Post-rpc interceptor for get_policy + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1 server but before + it is returned to user code. + """ + return response + + def pre_list_attestors( + self, request: service.ListAttestorsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListAttestorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_attestors + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 server. + """ + return request, metadata + + def post_list_attestors( + self, response: service.ListAttestorsResponse + ) -> service.ListAttestorsResponse: + """Post-rpc interceptor for list_attestors + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1 server but before + it is returned to user code. + """ + return response + + def pre_update_attestor( + self, + request: service.UpdateAttestorRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateAttestorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_attestor + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 server. + """ + return request, metadata + + def post_update_attestor(self, response: resources.Attestor) -> resources.Attestor: + """Post-rpc interceptor for update_attestor + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1 server but before + it is returned to user code. + """ + return response + + def pre_update_policy( + self, request: service.UpdatePolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.UpdatePolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 server. + """ + return request, metadata + + def post_update_policy(self, response: resources.Policy) -> resources.Policy: + """Post-rpc interceptor for update_policy + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1 server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BinauthzManagementServiceV1RestStub: + _session: AuthorizedSession + _host: str + _interceptor: BinauthzManagementServiceV1RestInterceptor + + +class BinauthzManagementServiceV1RestTransport(BinauthzManagementServiceV1Transport): + """REST backend transport for BinauthzManagementServiceV1. + + Google Cloud Management Service for Binary Authorization admission + policies and attestation authorities. + + This API implements a REST model with the following objects: + + - [Policy][google.cloud.binaryauthorization.v1.Policy] + - [Attestor][google.cloud.binaryauthorization.v1.Attestor] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "binaryauthorization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[BinauthzManagementServiceV1RestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or BinauthzManagementServiceV1RestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateAttestor(BinauthzManagementServiceV1RestStub): + def __hash__(self): + return hash("CreateAttestor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "attestorId": "", + } + + @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 + } + + def __call__( + self, + request: service.CreateAttestorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Attestor: + r"""Call the create attestor method over HTTP. + + Args: + request (~.service.CreateAttestorRequest): + The request object. Request message for + [BinauthzManagementService.CreateAttestor][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Attestor: + An + [attestor][google.cloud.binaryauthorization.v1.Attestor] + that attests to container image artifacts. An existing + attestor cannot be modified except where indicated. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/attestors", + "body": "attestor", + }, + ] + request, metadata = self._interceptor.pre_create_attestor(request, metadata) + pb_request = service.CreateAttestorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resources.Attestor() + pb_resp = resources.Attestor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_attestor(resp) + return resp + + class _DeleteAttestor(BinauthzManagementServiceV1RestStub): + def __hash__(self): + return hash("DeleteAttestor") + + __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 + } + + def __call__( + self, + request: service.DeleteAttestorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete attestor method over HTTP. + + Args: + request (~.service.DeleteAttestorRequest): + The request object. Request message for + [BinauthzManagementService.DeleteAttestor][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/attestors/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_attestor(request, metadata) + pb_request = service.DeleteAttestorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetAttestor(BinauthzManagementServiceV1RestStub): + def __hash__(self): + return hash("GetAttestor") + + __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 + } + + def __call__( + self, + request: service.GetAttestorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Attestor: + r"""Call the get attestor method over HTTP. + + Args: + request (~.service.GetAttestorRequest): + The request object. Request message for + [BinauthzManagementService.GetAttestor][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Attestor: + An + [attestor][google.cloud.binaryauthorization.v1.Attestor] + that attests to container image artifacts. An existing + attestor cannot be modified except where indicated. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/attestors/*}", + }, + ] + request, metadata = self._interceptor.pre_get_attestor(request, metadata) + pb_request = service.GetAttestorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resources.Attestor() + pb_resp = resources.Attestor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_attestor(resp) + return resp + + class _GetPolicy(BinauthzManagementServiceV1RestStub): + def __hash__(self): + return hash("GetPolicy") + + __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 + } + + def __call__( + self, + request: service.GetPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Policy: + r"""Call the get policy method over HTTP. + + Args: + request (~.service.GetPolicyRequest): + The request object. Request message for + [BinauthzManagementService.GetPolicy][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Policy: + A [policy][google.cloud.binaryauthorization.v1.Policy] + for container image binary authorization. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/policy}", + }, + ] + request, metadata = self._interceptor.pre_get_policy(request, metadata) + pb_request = service.GetPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resources.Policy() + pb_resp = resources.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_policy(resp) + return resp + + class _ListAttestors(BinauthzManagementServiceV1RestStub): + def __hash__(self): + return hash("ListAttestors") + + __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 + } + + def __call__( + self, + request: service.ListAttestorsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListAttestorsResponse: + r"""Call the list attestors method over HTTP. + + Args: + request (~.service.ListAttestorsRequest): + The request object. Request message for + [BinauthzManagementService.ListAttestors][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListAttestorsResponse: + Response message for + [BinauthzManagementService.ListAttestors][]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*}/attestors", + }, + ] + request, metadata = self._interceptor.pre_list_attestors(request, metadata) + pb_request = service.ListAttestorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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.ListAttestorsResponse() + pb_resp = service.ListAttestorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_attestors(resp) + return resp + + class _UpdateAttestor(BinauthzManagementServiceV1RestStub): + def __hash__(self): + return hash("UpdateAttestor") + + __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 + } + + def __call__( + self, + request: service.UpdateAttestorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Attestor: + r"""Call the update attestor method over HTTP. + + Args: + request (~.service.UpdateAttestorRequest): + The request object. Request message for + [BinauthzManagementService.UpdateAttestor][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Attestor: + An + [attestor][google.cloud.binaryauthorization.v1.Attestor] + that attests to container image artifacts. An existing + attestor cannot be modified except where indicated. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1/{attestor.name=projects/*/attestors/*}", + "body": "attestor", + }, + ] + request, metadata = self._interceptor.pre_update_attestor(request, metadata) + pb_request = service.UpdateAttestorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resources.Attestor() + pb_resp = resources.Attestor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_attestor(resp) + return resp + + class _UpdatePolicy(BinauthzManagementServiceV1RestStub): + def __hash__(self): + return hash("UpdatePolicy") + + __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 + } + + def __call__( + self, + request: service.UpdatePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Policy: + r"""Call the update policy method over HTTP. + + Args: + request (~.service.UpdatePolicyRequest): + The request object. Request message for + [BinauthzManagementService.UpdatePolicy][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Policy: + A [policy][google.cloud.binaryauthorization.v1.Policy] + for container image binary authorization. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1/{policy.name=projects/*/policy}", + "body": "policy", + }, + ] + request, metadata = self._interceptor.pre_update_policy(request, metadata) + pb_request = service.UpdatePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resources.Policy() + pb_resp = resources.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_policy(resp) + return resp + + @property + def create_attestor( + self, + ) -> Callable[[service.CreateAttestorRequest], resources.Attestor]: + # 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._CreateAttestor(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_attestor( + self, + ) -> Callable[[service.DeleteAttestorRequest], empty_pb2.Empty]: + # 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._DeleteAttestor(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_attestor( + self, + ) -> Callable[[service.GetAttestorRequest], resources.Attestor]: + # 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._GetAttestor(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_policy(self) -> Callable[[service.GetPolicyRequest], resources.Policy]: + # 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._GetPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_attestors( + self, + ) -> Callable[[service.ListAttestorsRequest], service.ListAttestorsResponse]: + # 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._ListAttestors(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_attestor( + self, + ) -> Callable[[service.UpdateAttestorRequest], resources.Attestor]: + # 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._UpdateAttestor(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_policy( + self, + ) -> Callable[[service.UpdatePolicyRequest], resources.Policy]: + # 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._UpdatePolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("BinauthzManagementServiceV1RestTransport",) diff --git a/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py b/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py index e60306a..a5eb3fc 100644 --- a/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py +++ b/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py @@ -53,6 +53,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, SystemPolicyV1Transport from .transports.grpc import SystemPolicyV1GrpcTransport from .transports.grpc_asyncio import SystemPolicyV1GrpcAsyncIOTransport +from .transports.rest import SystemPolicyV1RestTransport class SystemPolicyV1ClientMeta(type): @@ -68,6 +69,7 @@ class SystemPolicyV1ClientMeta(type): ) # type: Dict[str, Type[SystemPolicyV1Transport]] _transport_registry["grpc"] = SystemPolicyV1GrpcTransport _transport_registry["grpc_asyncio"] = SystemPolicyV1GrpcAsyncIOTransport + _transport_registry["rest"] = SystemPolicyV1RestTransport def get_transport_class( cls, diff --git a/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/__init__.py b/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/__init__.py index d136089..75269b3 100644 --- a/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/__init__.py +++ b/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/__init__.py @@ -19,14 +19,18 @@ from .base import SystemPolicyV1Transport from .grpc import SystemPolicyV1GrpcTransport from .grpc_asyncio import SystemPolicyV1GrpcAsyncIOTransport +from .rest import SystemPolicyV1RestInterceptor, SystemPolicyV1RestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[SystemPolicyV1Transport]] _transport_registry["grpc"] = SystemPolicyV1GrpcTransport _transport_registry["grpc_asyncio"] = SystemPolicyV1GrpcAsyncIOTransport +_transport_registry["rest"] = SystemPolicyV1RestTransport __all__ = ( "SystemPolicyV1Transport", "SystemPolicyV1GrpcTransport", "SystemPolicyV1GrpcAsyncIOTransport", + "SystemPolicyV1RestTransport", + "SystemPolicyV1RestInterceptor", ) diff --git a/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py b/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py new file mode 100644 index 0000000..3e2e10d --- /dev/null +++ b/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py @@ -0,0 +1,306 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.binaryauthorization_v1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import SystemPolicyV1Transport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SystemPolicyV1RestInterceptor: + """Interceptor for SystemPolicyV1. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SystemPolicyV1RestTransport. + + .. code-block:: python + class MyCustomSystemPolicyV1Interceptor(SystemPolicyV1RestInterceptor): + def pre_get_system_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_system_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SystemPolicyV1RestTransport(interceptor=MyCustomSystemPolicyV1Interceptor()) + client = SystemPolicyV1Client(transport=transport) + + + """ + + def pre_get_system_policy( + self, + request: service.GetSystemPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetSystemPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_system_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SystemPolicyV1 server. + """ + return request, metadata + + def post_get_system_policy(self, response: resources.Policy) -> resources.Policy: + """Post-rpc interceptor for get_system_policy + + Override in a subclass to manipulate the response + after it is returned by the SystemPolicyV1 server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SystemPolicyV1RestStub: + _session: AuthorizedSession + _host: str + _interceptor: SystemPolicyV1RestInterceptor + + +class SystemPolicyV1RestTransport(SystemPolicyV1Transport): + """REST backend transport for SystemPolicyV1. + + API for working with the system policy. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "binaryauthorization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SystemPolicyV1RestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SystemPolicyV1RestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetSystemPolicy(SystemPolicyV1RestStub): + def __hash__(self): + return hash("GetSystemPolicy") + + __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 + } + + def __call__( + self, + request: service.GetSystemPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Policy: + r"""Call the get system policy method over HTTP. + + Args: + request (~.service.GetSystemPolicyRequest): + The request object. Request to read the current system + policy. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Policy: + A [policy][google.cloud.binaryauthorization.v1.Policy] + for container image binary authorization. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=locations/*/policy}", + }, + ] + request, metadata = self._interceptor.pre_get_system_policy( + request, metadata + ) + pb_request = service.GetSystemPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resources.Policy() + pb_resp = resources.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_system_policy(resp) + return resp + + @property + def get_system_policy( + self, + ) -> Callable[[service.GetSystemPolicyRequest], resources.Policy]: + # 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._GetSystemPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SystemPolicyV1RestTransport",) diff --git a/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py b/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py index 3b16181..c062bf5 100644 --- a/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py +++ b/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py @@ -51,6 +51,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, ValidationHelperV1Transport from .transports.grpc import ValidationHelperV1GrpcTransport from .transports.grpc_asyncio import ValidationHelperV1GrpcAsyncIOTransport +from .transports.rest import ValidationHelperV1RestTransport class ValidationHelperV1ClientMeta(type): @@ -66,6 +67,7 @@ class ValidationHelperV1ClientMeta(type): ) # type: Dict[str, Type[ValidationHelperV1Transport]] _transport_registry["grpc"] = ValidationHelperV1GrpcTransport _transport_registry["grpc_asyncio"] = ValidationHelperV1GrpcAsyncIOTransport + _transport_registry["rest"] = ValidationHelperV1RestTransport def get_transport_class( cls, diff --git a/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/__init__.py b/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/__init__.py index f7b1990..231ec3e 100644 --- a/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/__init__.py +++ b/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/__init__.py @@ -19,6 +19,7 @@ from .base import ValidationHelperV1Transport from .grpc import ValidationHelperV1GrpcTransport from .grpc_asyncio import ValidationHelperV1GrpcAsyncIOTransport +from .rest import ValidationHelperV1RestInterceptor, ValidationHelperV1RestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[ValidationHelperV1Transport]] _transport_registry["grpc"] = ValidationHelperV1GrpcTransport _transport_registry["grpc_asyncio"] = ValidationHelperV1GrpcAsyncIOTransport +_transport_registry["rest"] = ValidationHelperV1RestTransport __all__ = ( "ValidationHelperV1Transport", "ValidationHelperV1GrpcTransport", "ValidationHelperV1GrpcAsyncIOTransport", + "ValidationHelperV1RestTransport", + "ValidationHelperV1RestInterceptor", ) diff --git a/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py b/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py new file mode 100644 index 0000000..fb96efb --- /dev/null +++ b/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py @@ -0,0 +1,321 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.binaryauthorization_v1.types import service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import ValidationHelperV1Transport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ValidationHelperV1RestInterceptor: + """Interceptor for ValidationHelperV1. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ValidationHelperV1RestTransport. + + .. code-block:: python + class MyCustomValidationHelperV1Interceptor(ValidationHelperV1RestInterceptor): + def pre_validate_attestation_occurrence(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_validate_attestation_occurrence(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ValidationHelperV1RestTransport(interceptor=MyCustomValidationHelperV1Interceptor()) + client = ValidationHelperV1Client(transport=transport) + + + """ + + def pre_validate_attestation_occurrence( + self, + request: service.ValidateAttestationOccurrenceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.ValidateAttestationOccurrenceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for validate_attestation_occurrence + + Override in a subclass to manipulate the request or metadata + before they are sent to the ValidationHelperV1 server. + """ + return request, metadata + + def post_validate_attestation_occurrence( + self, response: service.ValidateAttestationOccurrenceResponse + ) -> service.ValidateAttestationOccurrenceResponse: + """Post-rpc interceptor for validate_attestation_occurrence + + Override in a subclass to manipulate the response + after it is returned by the ValidationHelperV1 server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ValidationHelperV1RestStub: + _session: AuthorizedSession + _host: str + _interceptor: ValidationHelperV1RestInterceptor + + +class ValidationHelperV1RestTransport(ValidationHelperV1Transport): + """REST backend transport for ValidationHelperV1. + + BinAuthz Attestor verification + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "binaryauthorization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[ValidationHelperV1RestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ValidationHelperV1RestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ValidateAttestationOccurrence(ValidationHelperV1RestStub): + def __hash__(self): + return hash("ValidateAttestationOccurrence") + + __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 + } + + def __call__( + self, + request: service.ValidateAttestationOccurrenceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ValidateAttestationOccurrenceResponse: + r"""Call the validate attestation + occurrence method over HTTP. + + Args: + request (~.service.ValidateAttestationOccurrenceRequest): + The request object. Request message for + [ValidationHelperV1.ValidateAttestationOccurrence][google.cloud.binaryauthorization.v1.ValidationHelperV1.ValidateAttestationOccurrence]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ValidateAttestationOccurrenceResponse: + Response message for + [ValidationHelperV1.ValidateAttestationOccurrence][google.cloud.binaryauthorization.v1.ValidationHelperV1.ValidateAttestationOccurrence]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{attestor=projects/*/attestors/*}:validateAttestationOccurrence", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_validate_attestation_occurrence( + request, metadata + ) + pb_request = service.ValidateAttestationOccurrenceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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.ValidateAttestationOccurrenceResponse() + pb_resp = service.ValidateAttestationOccurrenceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_validate_attestation_occurrence(resp) + return resp + + @property + def validate_attestation_occurrence( + self, + ) -> Callable[ + [service.ValidateAttestationOccurrenceRequest], + service.ValidateAttestationOccurrenceResponse, + ]: + # 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._ValidateAttestationOccurrence(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ValidationHelperV1RestTransport",) diff --git a/google/cloud/binaryauthorization_v1/types/resources.py b/google/cloud/binaryauthorization_v1/types/resources.py index 546571e..918e997 100644 --- a/google/cloud/binaryauthorization_v1/types/resources.py +++ b/google/cloud/binaryauthorization_v1/types/resources.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import timestamp_pb2 # type: ignore diff --git a/google/cloud/binaryauthorization_v1/types/service.py b/google/cloud/binaryauthorization_v1/types/service.py index 2ef1287..370103f 100644 --- a/google/cloud/binaryauthorization_v1/types/service.py +++ b/google/cloud/binaryauthorization_v1/types/service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import grafeas.grafeas_v1.types # type: ignore diff --git a/google/cloud/binaryauthorization_v1beta1/__init__.py b/google/cloud/binaryauthorization_v1beta1/__init__.py index bf3e972..0a6fe24 100644 --- a/google/cloud/binaryauthorization_v1beta1/__init__.py +++ b/google/cloud/binaryauthorization_v1beta1/__init__.py @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from google.cloud.binaryauthorization import gapic_version as package_version +from google.cloud.binaryauthorization_v1beta1 import gapic_version as package_version __version__ = package_version.__version__ diff --git a/google/cloud/binaryauthorization_v1beta1/gapic_metadata.json b/google/cloud/binaryauthorization_v1beta1/gapic_metadata.json index 65f5f50..bf2774f 100644 --- a/google/cloud/binaryauthorization_v1beta1/gapic_metadata.json +++ b/google/cloud/binaryauthorization_v1beta1/gapic_metadata.json @@ -86,6 +86,46 @@ ] } } + }, + "rest": { + "libraryClient": "BinauthzManagementServiceV1Beta1Client", + "rpcs": { + "CreateAttestor": { + "methods": [ + "create_attestor" + ] + }, + "DeleteAttestor": { + "methods": [ + "delete_attestor" + ] + }, + "GetAttestor": { + "methods": [ + "get_attestor" + ] + }, + "GetPolicy": { + "methods": [ + "get_policy" + ] + }, + "ListAttestors": { + "methods": [ + "list_attestors" + ] + }, + "UpdateAttestor": { + "methods": [ + "update_attestor" + ] + }, + "UpdatePolicy": { + "methods": [ + "update_policy" + ] + } + } } } }, @@ -110,6 +150,16 @@ ] } } + }, + "rest": { + "libraryClient": "SystemPolicyV1Beta1Client", + "rpcs": { + "GetSystemPolicy": { + "methods": [ + "get_system_policy" + ] + } + } } } } diff --git a/google/cloud/binaryauthorization_v1beta1/gapic_version.py b/google/cloud/binaryauthorization_v1beta1/gapic_version.py index 69ff013..a016bdf 100644 --- a/google/cloud/binaryauthorization_v1beta1/gapic_version.py +++ b/google/cloud/binaryauthorization_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.5.1" # {x-release-please-version} +__version__ = "1.6.0" # {x-release-please-version} diff --git a/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py b/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py index 41d437b..1558a9d 100644 --- a/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py +++ b/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/client.py @@ -61,6 +61,7 @@ from .transports.grpc_asyncio import ( BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport, ) +from .transports.rest import BinauthzManagementServiceV1Beta1RestTransport class BinauthzManagementServiceV1Beta1ClientMeta(type): @@ -78,6 +79,7 @@ class BinauthzManagementServiceV1Beta1ClientMeta(type): _transport_registry[ "grpc_asyncio" ] = BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport + _transport_registry["rest"] = BinauthzManagementServiceV1Beta1RestTransport def get_transport_class( cls, diff --git a/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/__init__.py b/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/__init__.py index 407a4a5..7774684 100644 --- a/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/__init__.py +++ b/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/__init__.py @@ -19,6 +19,10 @@ from .base import BinauthzManagementServiceV1Beta1Transport from .grpc import BinauthzManagementServiceV1Beta1GrpcTransport from .grpc_asyncio import BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport +from .rest import ( + BinauthzManagementServiceV1Beta1RestInterceptor, + BinauthzManagementServiceV1Beta1RestTransport, +) # Compile a registry of transports. _transport_registry = ( @@ -28,9 +32,12 @@ _transport_registry[ "grpc_asyncio" ] = BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport +_transport_registry["rest"] = BinauthzManagementServiceV1Beta1RestTransport __all__ = ( "BinauthzManagementServiceV1Beta1Transport", "BinauthzManagementServiceV1Beta1GrpcTransport", "BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport", + "BinauthzManagementServiceV1Beta1RestTransport", + "BinauthzManagementServiceV1Beta1RestInterceptor", ) diff --git a/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py b/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py new file mode 100644 index 0000000..a4956ba --- /dev/null +++ b/google/cloud/binaryauthorization_v1beta1/services/binauthz_management_service_v1_beta1/transports/rest.py @@ -0,0 +1,1080 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.binaryauthorization_v1beta1.types import resources, service + +from .base import BinauthzManagementServiceV1Beta1Transport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class BinauthzManagementServiceV1Beta1RestInterceptor: + """Interceptor for BinauthzManagementServiceV1Beta1. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the BinauthzManagementServiceV1Beta1RestTransport. + + .. code-block:: python + class MyCustomBinauthzManagementServiceV1Beta1Interceptor(BinauthzManagementServiceV1Beta1RestInterceptor): + def pre_create_attestor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_attestor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_attestor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_attestor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_attestor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_attestors(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_attestors(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_attestor(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_attestor(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BinauthzManagementServiceV1Beta1RestTransport(interceptor=MyCustomBinauthzManagementServiceV1Beta1Interceptor()) + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + + + """ + + def pre_create_attestor( + self, + request: service.CreateAttestorRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.CreateAttestorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_attestor + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_create_attestor(self, response: resources.Attestor) -> resources.Attestor: + """Post-rpc interceptor for create_attestor + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_delete_attestor( + self, + request: service.DeleteAttestorRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.DeleteAttestorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_attestor + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def pre_get_attestor( + self, request: service.GetAttestorRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetAttestorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_attestor + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_get_attestor(self, response: resources.Attestor) -> resources.Attestor: + """Post-rpc interceptor for get_attestor + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_get_policy( + self, request: service.GetPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.GetPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_get_policy(self, response: resources.Policy) -> resources.Policy: + """Post-rpc interceptor for get_policy + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_list_attestors( + self, request: service.ListAttestorsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListAttestorsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_attestors + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_list_attestors( + self, response: service.ListAttestorsResponse + ) -> service.ListAttestorsResponse: + """Post-rpc interceptor for list_attestors + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_update_attestor( + self, + request: service.UpdateAttestorRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.UpdateAttestorRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_attestor + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_update_attestor(self, response: resources.Attestor) -> resources.Attestor: + """Post-rpc interceptor for update_attestor + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + def pre_update_policy( + self, request: service.UpdatePolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.UpdatePolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1Beta1 server. + """ + return request, metadata + + def post_update_policy(self, response: resources.Policy) -> resources.Policy: + """Post-rpc interceptor for update_policy + + Override in a subclass to manipulate the response + after it is returned by the BinauthzManagementServiceV1Beta1 server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BinauthzManagementServiceV1Beta1RestStub: + _session: AuthorizedSession + _host: str + _interceptor: BinauthzManagementServiceV1Beta1RestInterceptor + + +class BinauthzManagementServiceV1Beta1RestTransport( + BinauthzManagementServiceV1Beta1Transport +): + """REST backend transport for BinauthzManagementServiceV1Beta1. + + Google Cloud Management Service for Binary Authorization admission + policies and attestation authorities. + + This API implements a REST model with the following objects: + + - [Policy][google.cloud.binaryauthorization.v1beta1.Policy] + - [Attestor][google.cloud.binaryauthorization.v1beta1.Attestor] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "binaryauthorization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[BinauthzManagementServiceV1Beta1RestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = ( + interceptor or BinauthzManagementServiceV1Beta1RestInterceptor() + ) + self._prep_wrapped_messages(client_info) + + class _CreateAttestor(BinauthzManagementServiceV1Beta1RestStub): + def __hash__(self): + return hash("CreateAttestor") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "attestorId": "", + } + + @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 + } + + def __call__( + self, + request: service.CreateAttestorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Attestor: + r"""Call the create attestor method over HTTP. + + Args: + request (~.service.CreateAttestorRequest): + The request object. Request message for + [BinauthzManagementService.CreateAttestor][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Attestor: + An + [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] + that attests to container image artifacts. An existing + attestor cannot be modified except where indicated. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*}/attestors", + "body": "attestor", + }, + ] + request, metadata = self._interceptor.pre_create_attestor(request, metadata) + pb_request = service.CreateAttestorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resources.Attestor() + pb_resp = resources.Attestor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_attestor(resp) + return resp + + class _DeleteAttestor(BinauthzManagementServiceV1Beta1RestStub): + def __hash__(self): + return hash("DeleteAttestor") + + __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 + } + + def __call__( + self, + request: service.DeleteAttestorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete attestor method over HTTP. + + Args: + request (~.service.DeleteAttestorRequest): + The request object. Request message for + [BinauthzManagementService.DeleteAttestor][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta1/{name=projects/*/attestors/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_attestor(request, metadata) + pb_request = service.DeleteAttestorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetAttestor(BinauthzManagementServiceV1Beta1RestStub): + def __hash__(self): + return hash("GetAttestor") + + __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 + } + + def __call__( + self, + request: service.GetAttestorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Attestor: + r"""Call the get attestor method over HTTP. + + Args: + request (~.service.GetAttestorRequest): + The request object. Request message for + [BinauthzManagementService.GetAttestor][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Attestor: + An + [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] + that attests to container image artifacts. An existing + attestor cannot be modified except where indicated. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/attestors/*}", + }, + ] + request, metadata = self._interceptor.pre_get_attestor(request, metadata) + pb_request = service.GetAttestorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resources.Attestor() + pb_resp = resources.Attestor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_attestor(resp) + return resp + + class _GetPolicy(BinauthzManagementServiceV1Beta1RestStub): + def __hash__(self): + return hash("GetPolicy") + + __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 + } + + def __call__( + self, + request: service.GetPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Policy: + r"""Call the get policy method over HTTP. + + Args: + request (~.service.GetPolicyRequest): + The request object. Request message for + [BinauthzManagementService.GetPolicy][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Policy: + A + [policy][google.cloud.binaryauthorization.v1beta1.Policy] + for Binary Authorization. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/policy}", + }, + ] + request, metadata = self._interceptor.pre_get_policy(request, metadata) + pb_request = service.GetPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resources.Policy() + pb_resp = resources.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_policy(resp) + return resp + + class _ListAttestors(BinauthzManagementServiceV1Beta1RestStub): + def __hash__(self): + return hash("ListAttestors") + + __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 + } + + def __call__( + self, + request: service.ListAttestorsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListAttestorsResponse: + r"""Call the list attestors method over HTTP. + + Args: + request (~.service.ListAttestorsRequest): + The request object. Request message for + [BinauthzManagementService.ListAttestors][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListAttestorsResponse: + Response message for + [BinauthzManagementService.ListAttestors][]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{parent=projects/*}/attestors", + }, + ] + request, metadata = self._interceptor.pre_list_attestors(request, metadata) + pb_request = service.ListAttestorsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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.ListAttestorsResponse() + pb_resp = service.ListAttestorsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_attestors(resp) + return resp + + class _UpdateAttestor(BinauthzManagementServiceV1Beta1RestStub): + def __hash__(self): + return hash("UpdateAttestor") + + __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 + } + + def __call__( + self, + request: service.UpdateAttestorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Attestor: + r"""Call the update attestor method over HTTP. + + Args: + request (~.service.UpdateAttestorRequest): + The request object. Request message for + [BinauthzManagementService.UpdateAttestor][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Attestor: + An + [attestor][google.cloud.binaryauthorization.v1beta1.Attestor] + that attests to container image artifacts. An existing + attestor cannot be modified except where indicated. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1beta1/{attestor.name=projects/*/attestors/*}", + "body": "attestor", + }, + ] + request, metadata = self._interceptor.pre_update_attestor(request, metadata) + pb_request = service.UpdateAttestorRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resources.Attestor() + pb_resp = resources.Attestor.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_attestor(resp) + return resp + + class _UpdatePolicy(BinauthzManagementServiceV1Beta1RestStub): + def __hash__(self): + return hash("UpdatePolicy") + + __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 + } + + def __call__( + self, + request: service.UpdatePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Policy: + r"""Call the update policy method over HTTP. + + Args: + request (~.service.UpdatePolicyRequest): + The request object. Request message for + [BinauthzManagementService.UpdatePolicy][]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Policy: + A + [policy][google.cloud.binaryauthorization.v1beta1.Policy] + for Binary Authorization. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1beta1/{policy.name=projects/*/policy}", + "body": "policy", + }, + ] + request, metadata = self._interceptor.pre_update_policy(request, metadata) + pb_request = service.UpdatePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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 = resources.Policy() + pb_resp = resources.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_policy(resp) + return resp + + @property + def create_attestor( + self, + ) -> Callable[[service.CreateAttestorRequest], resources.Attestor]: + # 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._CreateAttestor(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_attestor( + self, + ) -> Callable[[service.DeleteAttestorRequest], empty_pb2.Empty]: + # 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._DeleteAttestor(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_attestor( + self, + ) -> Callable[[service.GetAttestorRequest], resources.Attestor]: + # 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._GetAttestor(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_policy(self) -> Callable[[service.GetPolicyRequest], resources.Policy]: + # 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._GetPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_attestors( + self, + ) -> Callable[[service.ListAttestorsRequest], service.ListAttestorsResponse]: + # 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._ListAttestors(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_attestor( + self, + ) -> Callable[[service.UpdateAttestorRequest], resources.Attestor]: + # 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._UpdateAttestor(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_policy( + self, + ) -> Callable[[service.UpdatePolicyRequest], resources.Policy]: + # 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._UpdatePolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("BinauthzManagementServiceV1Beta1RestTransport",) diff --git a/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py b/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py index 33ef514..f6a4901 100644 --- a/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py +++ b/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/client.py @@ -53,6 +53,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, SystemPolicyV1Beta1Transport from .transports.grpc import SystemPolicyV1Beta1GrpcTransport from .transports.grpc_asyncio import SystemPolicyV1Beta1GrpcAsyncIOTransport +from .transports.rest import SystemPolicyV1Beta1RestTransport class SystemPolicyV1Beta1ClientMeta(type): @@ -68,6 +69,7 @@ class SystemPolicyV1Beta1ClientMeta(type): ) # type: Dict[str, Type[SystemPolicyV1Beta1Transport]] _transport_registry["grpc"] = SystemPolicyV1Beta1GrpcTransport _transport_registry["grpc_asyncio"] = SystemPolicyV1Beta1GrpcAsyncIOTransport + _transport_registry["rest"] = SystemPolicyV1Beta1RestTransport def get_transport_class( cls, diff --git a/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/__init__.py b/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/__init__.py index 31c6c6c..79dddc1 100644 --- a/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/__init__.py +++ b/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/__init__.py @@ -19,6 +19,7 @@ from .base import SystemPolicyV1Beta1Transport from .grpc import SystemPolicyV1Beta1GrpcTransport from .grpc_asyncio import SystemPolicyV1Beta1GrpcAsyncIOTransport +from .rest import SystemPolicyV1Beta1RestInterceptor, SystemPolicyV1Beta1RestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[SystemPolicyV1Beta1Transport]] _transport_registry["grpc"] = SystemPolicyV1Beta1GrpcTransport _transport_registry["grpc_asyncio"] = SystemPolicyV1Beta1GrpcAsyncIOTransport +_transport_registry["rest"] = SystemPolicyV1Beta1RestTransport __all__ = ( "SystemPolicyV1Beta1Transport", "SystemPolicyV1Beta1GrpcTransport", "SystemPolicyV1Beta1GrpcAsyncIOTransport", + "SystemPolicyV1Beta1RestTransport", + "SystemPolicyV1Beta1RestInterceptor", ) diff --git a/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py b/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py new file mode 100644 index 0000000..b6f33de --- /dev/null +++ b/google/cloud/binaryauthorization_v1beta1/services/system_policy_v1_beta1/transports/rest.py @@ -0,0 +1,307 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.binaryauthorization_v1beta1.types import resources, service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import SystemPolicyV1Beta1Transport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SystemPolicyV1Beta1RestInterceptor: + """Interceptor for SystemPolicyV1Beta1. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SystemPolicyV1Beta1RestTransport. + + .. code-block:: python + class MyCustomSystemPolicyV1Beta1Interceptor(SystemPolicyV1Beta1RestInterceptor): + def pre_get_system_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_system_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SystemPolicyV1Beta1RestTransport(interceptor=MyCustomSystemPolicyV1Beta1Interceptor()) + client = SystemPolicyV1Beta1Client(transport=transport) + + + """ + + def pre_get_system_policy( + self, + request: service.GetSystemPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetSystemPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_system_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SystemPolicyV1Beta1 server. + """ + return request, metadata + + def post_get_system_policy(self, response: resources.Policy) -> resources.Policy: + """Post-rpc interceptor for get_system_policy + + Override in a subclass to manipulate the response + after it is returned by the SystemPolicyV1Beta1 server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SystemPolicyV1Beta1RestStub: + _session: AuthorizedSession + _host: str + _interceptor: SystemPolicyV1Beta1RestInterceptor + + +class SystemPolicyV1Beta1RestTransport(SystemPolicyV1Beta1Transport): + """REST backend transport for SystemPolicyV1Beta1. + + API for working with the system policy. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "binaryauthorization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SystemPolicyV1Beta1RestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SystemPolicyV1Beta1RestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetSystemPolicy(SystemPolicyV1Beta1RestStub): + def __hash__(self): + return hash("GetSystemPolicy") + + __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 + } + + def __call__( + self, + request: service.GetSystemPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Policy: + r"""Call the get system policy method over HTTP. + + Args: + request (~.service.GetSystemPolicyRequest): + The request object. Request to read the current system + policy. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Policy: + A + [policy][google.cloud.binaryauthorization.v1beta1.Policy] + for Binary Authorization. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=locations/*/policy}", + }, + ] + request, metadata = self._interceptor.pre_get_system_policy( + request, metadata + ) + pb_request = service.GetSystemPolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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 = resources.Policy() + pb_resp = resources.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_system_policy(resp) + return resp + + @property + def get_system_policy( + self, + ) -> Callable[[service.GetSystemPolicyRequest], resources.Policy]: + # 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._GetSystemPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SystemPolicyV1Beta1RestTransport",) diff --git a/google/cloud/binaryauthorization_v1beta1/types/continuous_validation_logging.py b/google/cloud/binaryauthorization_v1beta1/types/continuous_validation_logging.py index 3d705d9..1d78587 100644 --- a/google/cloud/binaryauthorization_v1beta1/types/continuous_validation_logging.py +++ b/google/cloud/binaryauthorization_v1beta1/types/continuous_validation_logging.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import timestamp_pb2 # type: ignore diff --git a/google/cloud/binaryauthorization_v1beta1/types/resources.py b/google/cloud/binaryauthorization_v1beta1/types/resources.py index 90d1dd5..811bda7 100644 --- a/google/cloud/binaryauthorization_v1beta1/types/resources.py +++ b/google/cloud/binaryauthorization_v1beta1/types/resources.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import timestamp_pb2 # type: ignore diff --git a/google/cloud/binaryauthorization_v1beta1/types/service.py b/google/cloud/binaryauthorization_v1beta1/types/service.py index b20e6e1..a8ec8f5 100644 --- a/google/cloud/binaryauthorization_v1beta1/types/service.py +++ b/google/cloud/binaryauthorization_v1beta1/types/service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence import proto # type: ignore diff --git a/noxfile.py b/noxfile.py index e716318..95e58c5 100644 --- a/noxfile.py +++ b/noxfile.py @@ -189,9 +189,9 @@ def unit(session): def install_systemtest_dependencies(session, *constraints): # Use pre-release gRPC for system tests. - # Exclude version 1.49.0rc1 which has a known issue. - # See https://github.com/grpc/grpc/pull/30642 - session.install("--pre", "grpcio!=1.49.0rc1") + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) @@ -346,9 +346,7 @@ def prerelease_deps(session): unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES session.install(*unit_deps_all) system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS + SYSTEM_TEST_STANDARD_DEPENDENCIES + SYSTEM_TEST_EXTERNAL_DEPENDENCIES ) session.install(*system_deps_all) @@ -378,8 +376,8 @@ def prerelease_deps(session): # dependency of grpc "six", "googleapis-common-protos", - # Exclude version 1.49.0rc1 which has a known issue. See https://github.com/grpc/grpc/pull/30642 - "grpcio!=1.49.0rc1", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", "grpcio-status", "google-api-core", "proto-plus", diff --git a/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1.json index c2c231e..4cb9a28 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-binary-authorization", - "version": "1.5.1" + "version": "1.6.0" }, "snippets": [ { diff --git a/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1beta1.json b/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1beta1.json index 2f86034..af2e556 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1beta1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.binaryauthorization.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-binary-authorization", - "version": "1.5.1" + "version": "1.6.0" }, "snippets": [ { diff --git a/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py b/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py index 83b869e..38c11e4 100644 --- a/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py +++ b/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,12 +33,15 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1 import ( BinauthzManagementServiceV1AsyncClient, @@ -99,6 +104,7 @@ def test__get_default_mtls_endpoint(): [ (BinauthzManagementServiceV1Client, "grpc"), (BinauthzManagementServiceV1AsyncClient, "grpc_asyncio"), + (BinauthzManagementServiceV1Client, "rest"), ], ) def test_binauthz_management_service_v1_client_from_service_account_info( @@ -114,7 +120,11 @@ def test_binauthz_management_service_v1_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -122,6 +132,7 @@ def test_binauthz_management_service_v1_client_from_service_account_info( [ (transports.BinauthzManagementServiceV1GrpcTransport, "grpc"), (transports.BinauthzManagementServiceV1GrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BinauthzManagementServiceV1RestTransport, "rest"), ], ) def test_binauthz_management_service_v1_client_service_account_always_use_jwt( @@ -147,6 +158,7 @@ def test_binauthz_management_service_v1_client_service_account_always_use_jwt( [ (BinauthzManagementServiceV1Client, "grpc"), (BinauthzManagementServiceV1AsyncClient, "grpc_asyncio"), + (BinauthzManagementServiceV1Client, "rest"), ], ) def test_binauthz_management_service_v1_client_from_service_account_file( @@ -169,13 +181,18 @@ def test_binauthz_management_service_v1_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) def test_binauthz_management_service_v1_client_get_transport_class(): transport = BinauthzManagementServiceV1Client.get_transport_class() available_transports = [ transports.BinauthzManagementServiceV1GrpcTransport, + transports.BinauthzManagementServiceV1RestTransport, ] assert transport in available_transports @@ -196,6 +213,11 @@ def test_binauthz_management_service_v1_client_get_transport_class(): transports.BinauthzManagementServiceV1GrpcAsyncIOTransport, "grpc_asyncio", ), + ( + BinauthzManagementServiceV1Client, + transports.BinauthzManagementServiceV1RestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -355,6 +377,18 @@ def test_binauthz_management_service_v1_client_client_options( "grpc_asyncio", "false", ), + ( + BinauthzManagementServiceV1Client, + transports.BinauthzManagementServiceV1RestTransport, + "rest", + "true", + ), + ( + BinauthzManagementServiceV1Client, + transports.BinauthzManagementServiceV1RestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -561,6 +595,11 @@ def test_binauthz_management_service_v1_client_get_mtls_endpoint_and_cert_source transports.BinauthzManagementServiceV1GrpcAsyncIOTransport, "grpc_asyncio", ), + ( + BinauthzManagementServiceV1Client, + transports.BinauthzManagementServiceV1RestTransport, + "rest", + ), ], ) def test_binauthz_management_service_v1_client_client_options_scopes( @@ -601,6 +640,12 @@ def test_binauthz_management_service_v1_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + BinauthzManagementServiceV1Client, + transports.BinauthzManagementServiceV1RestTransport, + "rest", + None, + ), ], ) def test_binauthz_management_service_v1_client_client_options_credentials_file( @@ -2562,172 +2607,2228 @@ async def test_delete_attestor_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BinauthzManagementServiceV1GrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + service.GetPolicyRequest, + dict, + ], +) +def test_get_policy_rest(request_type): + client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Client( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/policy"} + 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 = resources.Policy( + name="name_value", + description="description_value", + global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.BinauthzManagementServiceV1GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Policy) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.global_policy_evaluation_mode + == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Client( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + +def test_get_policy_rest_required_fields(request_type=service.GetPolicyRequest): + transport_class = transports.BinauthzManagementServiceV1RestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.BinauthzManagementServiceV1GrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Policy() + # 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": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_policy_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Client( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Client( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + unset_fields = transport.get_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) - # It is an error to provide scopes and a transport instance. - transport = transports.BinauthzManagementServiceV1GrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_policy_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1RestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1RestInterceptor(), ) - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Client( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = BinauthzManagementServiceV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "post_get_policy" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "pre_get_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetPolicyRequest.pb(service.GetPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Policy.to_json(resources.Policy()) + + request = service.GetPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Policy() + + client.get_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BinauthzManagementServiceV1GrpcTransport( + +def test_get_policy_rest_bad_request( + transport: str = "rest", request_type=service.GetPolicyRequest +): + client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = BinauthzManagementServiceV1Client(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/policy"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BinauthzManagementServiceV1GrpcTransport( + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_policy(request) + + +def test_get_policy_rest_flattened(): + client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.BinauthzManagementServiceV1GrpcAsyncIOTransport( + # 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 = resources.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/policy"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_policy(**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/{name=projects/*/policy}" % client.transport._host, args[1] + ) + + +def test_get_policy_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_policy( + service.GetPolicyRequest(), + name="name_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.BinauthzManagementServiceV1GrpcTransport, - transports.BinauthzManagementServiceV1GrpcAsyncIOTransport, - ], -) -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_get_policy_rest_error(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + service.UpdatePolicyRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = BinauthzManagementServiceV1Client.get_transport_class(transport_name)( +def test_update_policy_rest(request_type): + client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"policy": {"name": "projects/sample1/policy"}} + request_init["policy"] = { + "name": "projects/sample1/policy", + "description": "description_value", + "global_policy_evaluation_mode": 1, + "admission_whitelist_patterns": [{"name_pattern": "name_pattern_value"}], + "cluster_admission_rules": {}, + "kubernetes_namespace_admission_rules": {}, + "kubernetes_service_account_admission_rules": {}, + "istio_service_identity_admission_rules": {}, + "default_admission_rule": { + "evaluation_mode": 1, + "require_attestations_by": [ + "require_attestations_by_value1", + "require_attestations_by_value2", + ], + "enforcement_mode": 1, + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = resources.Policy( + name="name_value", + description="description_value", + global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Policy) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.global_policy_evaluation_mode + == resources.Policy.GlobalPolicyEvaluationMode.ENABLE + ) + + +def test_update_policy_rest_required_fields(request_type=service.UpdatePolicyRequest): + transport_class = transports.BinauthzManagementServiceV1RestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.BinauthzManagementServiceV1GrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Policy() + # 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": "put", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_policy_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.update_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("policy",))) -def test_binauthz_management_service_v1_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BinauthzManagementServiceV1Transport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_policy_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "post_update_policy" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "pre_update_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdatePolicyRequest.pb(service.UpdatePolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Policy.to_json(resources.Policy()) + + request = service.UpdatePolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Policy() -def test_binauthz_management_service_v1_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1.transports.BinauthzManagementServiceV1Transport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.BinauthzManagementServiceV1Transport( - credentials=ga_credentials.AnonymousCredentials(), + client.update_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "get_policy", - "update_policy", - "create_attestor", - "get_attestor", - "update_attestor", - "list_attestors", - "delete_attestor", + pre.assert_called_once() + post.assert_called_once() + + +def test_update_policy_rest_bad_request( + transport: str = "rest", request_type=service.UpdatePolicyRequest +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # send a request that will satisfy transcoding + request_init = {"policy": {"name": "projects/sample1/policy"}} + request_init["policy"] = { + "name": "projects/sample1/policy", + "description": "description_value", + "global_policy_evaluation_mode": 1, + "admission_whitelist_patterns": [{"name_pattern": "name_pattern_value"}], + "cluster_admission_rules": {}, + "kubernetes_namespace_admission_rules": {}, + "kubernetes_service_account_admission_rules": {}, + "istio_service_identity_admission_rules": {}, + "default_admission_rule": { + "evaluation_mode": 1, + "require_attestations_by": [ + "require_attestations_by_value1", + "require_attestations_by_value2", + ], + "enforcement_mode": 1, + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + request = request_type(**request_init) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_policy(request) -def test_binauthz_management_service_v1_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( +def test_update_policy_rest_flattened(): + client = BinauthzManagementServiceV1Client( + 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 = resources.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"policy": {"name": "projects/sample1/policy"}} + + # get truthy value for each flattened field + mock_args = dict( + policy=resources.Policy(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_policy(**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/{policy.name=projects/*/policy}" % client.transport._host, args[1] + ) + + +def test_update_policy_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_policy( + service.UpdatePolicyRequest(), + policy=resources.Policy(name="name_value"), + ) + + +def test_update_policy_rest_error(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateAttestorRequest, + dict, + ], +) +def test_create_attestor_rest(request_type): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["attestor"] = { + "name": "name_value", + "description": "description_value", + "user_owned_grafeas_note": { + "note_reference": "note_reference_value", + "public_keys": [ + { + "comment": "comment_value", + "id": "id_value", + "ascii_armored_pgp_public_key": "ascii_armored_pgp_public_key_value", + "pkix_public_key": { + "public_key_pem": "public_key_pem_value", + "signature_algorithm": 1, + }, + } + ], + "delegation_service_account_email": "delegation_service_account_email_value", + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = resources.Attestor( + name="name_value", + description="description_value", + user_owned_grafeas_note=resources.UserOwnedGrafeasNote( + note_reference="note_reference_value" + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_attestor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Attestor) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_create_attestor_rest_required_fields( + request_type=service.CreateAttestorRequest, +): + transport_class = transports.BinauthzManagementServiceV1RestTransport + + request_init = {} + request_init["parent"] = "" + request_init["attestor_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "attestorId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "attestorId" in jsonified_request + assert jsonified_request["attestorId"] == request_init["attestor_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["attestorId"] = "attestor_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_attestor._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("attestor_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "attestorId" in jsonified_request + assert jsonified_request["attestorId"] == "attestor_id_value" + + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Attestor() + # 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 + + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_attestor(request) + + expected_params = [ + ( + "attestorId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_attestor_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_attestor._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("attestorId",)) + & set( + ( + "parent", + "attestorId", + "attestor", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_attestor_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "post_create_attestor" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "pre_create_attestor" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateAttestorRequest.pb(service.CreateAttestorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Attestor.to_json(resources.Attestor()) + + request = service.CreateAttestorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Attestor() + + client.create_attestor( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_attestor_rest_bad_request( + transport: str = "rest", request_type=service.CreateAttestorRequest +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["attestor"] = { + "name": "name_value", + "description": "description_value", + "user_owned_grafeas_note": { + "note_reference": "note_reference_value", + "public_keys": [ + { + "comment": "comment_value", + "id": "id_value", + "ascii_armored_pgp_public_key": "ascii_armored_pgp_public_key_value", + "pkix_public_key": { + "public_key_pem": "public_key_pem_value", + "signature_algorithm": 1, + }, + } + ], + "delegation_service_account_email": "delegation_service_account_email_value", + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_attestor(request) + + +def test_create_attestor_rest_flattened(): + client = BinauthzManagementServiceV1Client( + 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 = resources.Attestor() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + attestor_id="attestor_id_value", + attestor=resources.Attestor(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_attestor(**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/*}/attestors" % client.transport._host, args[1] + ) + + +def test_create_attestor_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_attestor( + service.CreateAttestorRequest(), + parent="parent_value", + attestor_id="attestor_id_value", + attestor=resources.Attestor(name="name_value"), + ) + + +def test_create_attestor_rest_error(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetAttestorRequest, + dict, + ], +) +def test_get_attestor_rest(request_type): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/attestors/sample2"} + 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 = resources.Attestor( + name="name_value", + description="description_value", + user_owned_grafeas_note=resources.UserOwnedGrafeasNote( + note_reference="note_reference_value" + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_attestor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Attestor) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_get_attestor_rest_required_fields(request_type=service.GetAttestorRequest): + transport_class = transports.BinauthzManagementServiceV1RestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Attestor() + # 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": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_attestor(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_attestor_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_attestor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attestor_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "post_get_attestor" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "pre_get_attestor" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetAttestorRequest.pb(service.GetAttestorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Attestor.to_json(resources.Attestor()) + + request = service.GetAttestorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Attestor() + + client.get_attestor( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attestor_rest_bad_request( + transport: str = "rest", request_type=service.GetAttestorRequest +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/attestors/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_attestor(request) + + +def test_get_attestor_rest_flattened(): + client = BinauthzManagementServiceV1Client( + 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 = resources.Attestor() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/attestors/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_attestor(**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/{name=projects/*/attestors/*}" % client.transport._host, args[1] + ) + + +def test_get_attestor_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_attestor( + service.GetAttestorRequest(), + name="name_value", + ) + + +def test_get_attestor_rest_error(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateAttestorRequest, + dict, + ], +) +def test_update_attestor_rest(request_type): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"attestor": {"name": "projects/sample1/attestors/sample2"}} + request_init["attestor"] = { + "name": "projects/sample1/attestors/sample2", + "description": "description_value", + "user_owned_grafeas_note": { + "note_reference": "note_reference_value", + "public_keys": [ + { + "comment": "comment_value", + "id": "id_value", + "ascii_armored_pgp_public_key": "ascii_armored_pgp_public_key_value", + "pkix_public_key": { + "public_key_pem": "public_key_pem_value", + "signature_algorithm": 1, + }, + } + ], + "delegation_service_account_email": "delegation_service_account_email_value", + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = resources.Attestor( + name="name_value", + description="description_value", + user_owned_grafeas_note=resources.UserOwnedGrafeasNote( + note_reference="note_reference_value" + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_attestor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Attestor) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_update_attestor_rest_required_fields( + request_type=service.UpdateAttestorRequest, +): + transport_class = transports.BinauthzManagementServiceV1RestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Attestor() + # 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": "put", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_attestor(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_attestor_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_attestor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("attestor",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_attestor_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "post_update_attestor" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "pre_update_attestor" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateAttestorRequest.pb(service.UpdateAttestorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Attestor.to_json(resources.Attestor()) + + request = service.UpdateAttestorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Attestor() + + client.update_attestor( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_attestor_rest_bad_request( + transport: str = "rest", request_type=service.UpdateAttestorRequest +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"attestor": {"name": "projects/sample1/attestors/sample2"}} + request_init["attestor"] = { + "name": "projects/sample1/attestors/sample2", + "description": "description_value", + "user_owned_grafeas_note": { + "note_reference": "note_reference_value", + "public_keys": [ + { + "comment": "comment_value", + "id": "id_value", + "ascii_armored_pgp_public_key": "ascii_armored_pgp_public_key_value", + "pkix_public_key": { + "public_key_pem": "public_key_pem_value", + "signature_algorithm": 1, + }, + } + ], + "delegation_service_account_email": "delegation_service_account_email_value", + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_attestor(request) + + +def test_update_attestor_rest_flattened(): + client = BinauthzManagementServiceV1Client( + 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 = resources.Attestor() + + # get arguments that satisfy an http rule for this method + sample_request = {"attestor": {"name": "projects/sample1/attestors/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + attestor=resources.Attestor(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_attestor(**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/{attestor.name=projects/*/attestors/*}" % client.transport._host, + args[1], + ) + + +def test_update_attestor_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_attestor( + service.UpdateAttestorRequest(), + attestor=resources.Attestor(name="name_value"), + ) + + +def test_update_attestor_rest_error(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListAttestorsRequest, + dict, + ], +) +def test_list_attestors_rest(request_type): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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.ListAttestorsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListAttestorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_attestors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttestorsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_attestors_rest_required_fields(request_type=service.ListAttestorsRequest): + transport_class = transports.BinauthzManagementServiceV1RestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_attestors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_attestors._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListAttestorsResponse() + # 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": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListAttestorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_attestors(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_attestors_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_attestors._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_attestors_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "post_list_attestors" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "pre_list_attestors" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListAttestorsRequest.pb(service.ListAttestorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListAttestorsResponse.to_json( + service.ListAttestorsResponse() + ) + + request = service.ListAttestorsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListAttestorsResponse() + + client.list_attestors( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_attestors_rest_bad_request( + transport: str = "rest", request_type=service.ListAttestorsRequest +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_attestors(request) + + +def test_list_attestors_rest_flattened(): + client = BinauthzManagementServiceV1Client( + 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.ListAttestorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListAttestorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_attestors(**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/*}/attestors" % client.transport._host, args[1] + ) + + +def test_list_attestors_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_attestors( + service.ListAttestorsRequest(), + parent="parent_value", + ) + + +def test_list_attestors_rest_pager(transport: str = "rest"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListAttestorsResponse( + attestors=[ + resources.Attestor(), + resources.Attestor(), + resources.Attestor(), + ], + next_page_token="abc", + ), + service.ListAttestorsResponse( + attestors=[], + next_page_token="def", + ), + service.ListAttestorsResponse( + attestors=[ + resources.Attestor(), + ], + next_page_token="ghi", + ), + service.ListAttestorsResponse( + attestors=[ + resources.Attestor(), + resources.Attestor(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListAttestorsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1"} + + pager = client.list_attestors(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Attestor) for i in results) + + pages = list(client.list_attestors(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteAttestorRequest, + dict, + ], +) +def test_delete_attestor_rest(request_type): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/attestors/sample2"} + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_attestor(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_attestor_rest_required_fields( + request_type=service.DeleteAttestorRequest, +): + transport_class = transports.BinauthzManagementServiceV1RestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_attestor(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_attestor_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_attestor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_attestor_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1RestInterceptor, "pre_delete_attestor" + ) as pre: + pre.assert_not_called() + pb_message = service.DeleteAttestorRequest.pb(service.DeleteAttestorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = service.DeleteAttestorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_attestor( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_attestor_rest_bad_request( + transport: str = "rest", request_type=service.DeleteAttestorRequest +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/attestors/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_attestor(request) + + +def test_delete_attestor_rest_flattened(): + client = BinauthzManagementServiceV1Client( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/attestors/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_attestor(**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/{name=projects/*/attestors/*}" % client.transport._host, args[1] + ) + + +def test_delete_attestor_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_attestor( + service.DeleteAttestorRequest(), + name="name_value", + ) + + +def test_delete_attestor_rest_error(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BinauthzManagementServiceV1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BinauthzManagementServiceV1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Client( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BinauthzManagementServiceV1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Client( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Client( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BinauthzManagementServiceV1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Client( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BinauthzManagementServiceV1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BinauthzManagementServiceV1Client(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BinauthzManagementServiceV1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BinauthzManagementServiceV1GrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BinauthzManagementServiceV1GrpcTransport, + transports.BinauthzManagementServiceV1GrpcAsyncIOTransport, + transports.BinauthzManagementServiceV1RestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = BinauthzManagementServiceV1Client.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BinauthzManagementServiceV1GrpcTransport, + ) + + +def test_binauthz_management_service_v1_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BinauthzManagementServiceV1Transport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_binauthz_management_service_v1_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1.transports.BinauthzManagementServiceV1Transport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.BinauthzManagementServiceV1Transport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_policy", + "update_policy", + "create_attestor", + "get_attestor", + "update_attestor", + "list_attestors", + "delete_attestor", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_binauthz_management_service_v1_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( "google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1.transports.BinauthzManagementServiceV1Transport._prep_wrapped_messages" ) as Transport: Transport.return_value = None @@ -2792,6 +4893,7 @@ def test_binauthz_management_service_v1_transport_auth_adc(transport_class): [ transports.BinauthzManagementServiceV1GrpcTransport, transports.BinauthzManagementServiceV1GrpcAsyncIOTransport, + transports.BinauthzManagementServiceV1RestTransport, ], ) def test_binauthz_management_service_v1_transport_auth_gdch_credentials( @@ -2898,11 +5000,23 @@ def test_binauthz_management_service_v1_grpc_transport_client_cert_source_for_mt ) +def test_binauthz_management_service_v1_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.BinauthzManagementServiceV1RestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_binauthz_management_service_v1_host_no_port(transport_name): @@ -2913,7 +5027,11 @@ def test_binauthz_management_service_v1_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -2921,6 +5039,7 @@ def test_binauthz_management_service_v1_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_binauthz_management_service_v1_host_with_port(transport_name): @@ -2931,7 +5050,53 @@ def test_binauthz_management_service_v1_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:8000") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_binauthz_management_service_v1_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BinauthzManagementServiceV1Client( + credentials=creds1, + transport=transport_name, + ) + client2 = BinauthzManagementServiceV1Client( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_policy._session + session2 = client2.transport.get_policy._session + assert session1 != session2 + session1 = client1.transport.update_policy._session + session2 = client2.transport.update_policy._session + assert session1 != session2 + session1 = client1.transport.create_attestor._session + session2 = client2.transport.create_attestor._session + assert session1 != session2 + session1 = client1.transport.get_attestor._session + session2 = client2.transport.get_attestor._session + assert session1 != session2 + session1 = client1.transport.update_attestor._session + session2 = client2.transport.update_attestor._session + assert session1 != session2 + session1 = client1.transport.list_attestors._session + session2 = client2.transport.list_attestors._session + assert session1 != session2 + session1 = client1.transport.delete_attestor._session + session2 = client2.transport.delete_attestor._session + assert session1 != session2 def test_binauthz_management_service_v1_grpc_transport_channel(): @@ -3249,6 +5414,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -3266,6 +5432,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py b/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py index 5bc9fe8..8f05c6b 100644 --- a/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py +++ b/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,12 +33,15 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.binaryauthorization_v1.services.system_policy_v1 import ( SystemPolicyV1AsyncClient, @@ -95,6 +100,7 @@ def test__get_default_mtls_endpoint(): [ (SystemPolicyV1Client, "grpc"), (SystemPolicyV1AsyncClient, "grpc_asyncio"), + (SystemPolicyV1Client, "rest"), ], ) def test_system_policy_v1_client_from_service_account_info( @@ -110,7 +116,11 @@ def test_system_policy_v1_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -118,6 +128,7 @@ def test_system_policy_v1_client_from_service_account_info( [ (transports.SystemPolicyV1GrpcTransport, "grpc"), (transports.SystemPolicyV1GrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SystemPolicyV1RestTransport, "rest"), ], ) def test_system_policy_v1_client_service_account_always_use_jwt( @@ -143,6 +154,7 @@ def test_system_policy_v1_client_service_account_always_use_jwt( [ (SystemPolicyV1Client, "grpc"), (SystemPolicyV1AsyncClient, "grpc_asyncio"), + (SystemPolicyV1Client, "rest"), ], ) def test_system_policy_v1_client_from_service_account_file( @@ -165,13 +177,18 @@ def test_system_policy_v1_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) def test_system_policy_v1_client_get_transport_class(): transport = SystemPolicyV1Client.get_transport_class() available_transports = [ transports.SystemPolicyV1GrpcTransport, + transports.SystemPolicyV1RestTransport, ] assert transport in available_transports @@ -188,6 +205,7 @@ def test_system_policy_v1_client_get_transport_class(): transports.SystemPolicyV1GrpcAsyncIOTransport, "grpc_asyncio", ), + (SystemPolicyV1Client, transports.SystemPolicyV1RestTransport, "rest"), ], ) @mock.patch.object( @@ -333,6 +351,8 @@ def test_system_policy_v1_client_client_options( "grpc_asyncio", "false", ), + (SystemPolicyV1Client, transports.SystemPolicyV1RestTransport, "rest", "true"), + (SystemPolicyV1Client, transports.SystemPolicyV1RestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -532,6 +552,7 @@ def test_system_policy_v1_client_get_mtls_endpoint_and_cert_source(client_class) transports.SystemPolicyV1GrpcAsyncIOTransport, "grpc_asyncio", ), + (SystemPolicyV1Client, transports.SystemPolicyV1RestTransport, "rest"), ], ) def test_system_policy_v1_client_client_options_scopes( @@ -572,6 +593,7 @@ def test_system_policy_v1_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (SystemPolicyV1Client, transports.SystemPolicyV1RestTransport, "rest", None), ], ) def test_system_policy_v1_client_client_options_credentials_file( @@ -940,6 +962,275 @@ async def test_get_system_policy_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + service.GetSystemPolicyRequest, + dict, + ], +) +def test_get_system_policy_rest(request_type): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "locations/sample1/policy"} + 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 = resources.Policy( + name="name_value", + description="description_value", + global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_system_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Policy) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.global_policy_evaluation_mode + == resources.Policy.GlobalPolicyEvaluationMode.ENABLE + ) + + +def test_get_system_policy_rest_required_fields( + request_type=service.GetSystemPolicyRequest, +): + transport_class = transports.SystemPolicyV1RestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_system_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_system_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Policy() + # 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": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_system_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_system_policy_rest_unset_required_fields(): + transport = transports.SystemPolicyV1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_system_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_system_policy_rest_interceptors(null_interceptor): + transport = transports.SystemPolicyV1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SystemPolicyV1RestInterceptor(), + ) + client = SystemPolicyV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SystemPolicyV1RestInterceptor, "post_get_system_policy" + ) as post, mock.patch.object( + transports.SystemPolicyV1RestInterceptor, "pre_get_system_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetSystemPolicyRequest.pb(service.GetSystemPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Policy.to_json(resources.Policy()) + + request = service.GetSystemPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Policy() + + client.get_system_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_system_policy_rest_bad_request( + transport: str = "rest", request_type=service.GetSystemPolicyRequest +): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "locations/sample1/policy"} + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_system_policy(request) + + +def test_get_system_policy_rest_flattened(): + client = SystemPolicyV1Client( + 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 = resources.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "locations/sample1/policy"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_system_policy(**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/{name=locations/*/policy}" % client.transport._host, args[1] + ) + + +def test_get_system_policy_rest_flattened_error(transport: str = "rest"): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_system_policy( + service.GetSystemPolicyRequest(), + name="name_value", + ) + + +def test_get_system_policy_rest_error(): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SystemPolicyV1GrpcTransport( @@ -1021,6 +1312,7 @@ def test_transport_get_channel(): [ transports.SystemPolicyV1GrpcTransport, transports.SystemPolicyV1GrpcAsyncIOTransport, + transports.SystemPolicyV1RestTransport, ], ) def test_transport_adc(transport_class): @@ -1035,6 +1327,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1162,6 +1455,7 @@ def test_system_policy_v1_transport_auth_adc(transport_class): [ transports.SystemPolicyV1GrpcTransport, transports.SystemPolicyV1GrpcAsyncIOTransport, + transports.SystemPolicyV1RestTransport, ], ) def test_system_policy_v1_transport_auth_gdch_credentials(transport_class): @@ -1259,11 +1553,23 @@ def test_system_policy_v1_grpc_transport_client_cert_source_for_mtls(transport_c ) +def test_system_policy_v1_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SystemPolicyV1RestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_system_policy_v1_host_no_port(transport_name): @@ -1274,7 +1580,11 @@ def test_system_policy_v1_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -1282,6 +1592,7 @@ def test_system_policy_v1_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_system_policy_v1_host_with_port(transport_name): @@ -1292,7 +1603,33 @@ def test_system_policy_v1_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:8000") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_system_policy_v1_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SystemPolicyV1Client( + credentials=creds1, + transport=transport_name, + ) + client2 = SystemPolicyV1Client( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_system_policy._session + session2 = client2.transport.get_system_policy._session + assert session1 != session2 def test_system_policy_v1_grpc_transport_channel(): @@ -1583,6 +1920,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1600,6 +1938,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py b/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py index 5d39eef..bc32cae 100644 --- a/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py +++ b/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,6 +33,7 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format import grafeas.grafeas_v1.types # type: ignore from grafeas.grafeas_v1.types import common # type: ignore import grpc @@ -38,6 +41,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.binaryauthorization_v1.services.validation_helper_v1 import ( ValidationHelperV1AsyncClient, @@ -97,6 +102,7 @@ def test__get_default_mtls_endpoint(): [ (ValidationHelperV1Client, "grpc"), (ValidationHelperV1AsyncClient, "grpc_asyncio"), + (ValidationHelperV1Client, "rest"), ], ) def test_validation_helper_v1_client_from_service_account_info( @@ -112,7 +118,11 @@ def test_validation_helper_v1_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -120,6 +130,7 @@ def test_validation_helper_v1_client_from_service_account_info( [ (transports.ValidationHelperV1GrpcTransport, "grpc"), (transports.ValidationHelperV1GrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ValidationHelperV1RestTransport, "rest"), ], ) def test_validation_helper_v1_client_service_account_always_use_jwt( @@ -145,6 +156,7 @@ def test_validation_helper_v1_client_service_account_always_use_jwt( [ (ValidationHelperV1Client, "grpc"), (ValidationHelperV1AsyncClient, "grpc_asyncio"), + (ValidationHelperV1Client, "rest"), ], ) def test_validation_helper_v1_client_from_service_account_file( @@ -167,13 +179,18 @@ def test_validation_helper_v1_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) def test_validation_helper_v1_client_get_transport_class(): transport = ValidationHelperV1Client.get_transport_class() available_transports = [ transports.ValidationHelperV1GrpcTransport, + transports.ValidationHelperV1RestTransport, ] assert transport in available_transports @@ -190,6 +207,7 @@ def test_validation_helper_v1_client_get_transport_class(): transports.ValidationHelperV1GrpcAsyncIOTransport, "grpc_asyncio", ), + (ValidationHelperV1Client, transports.ValidationHelperV1RestTransport, "rest"), ], ) @mock.patch.object( @@ -345,6 +363,18 @@ def test_validation_helper_v1_client_client_options( "grpc_asyncio", "false", ), + ( + ValidationHelperV1Client, + transports.ValidationHelperV1RestTransport, + "rest", + "true", + ), + ( + ValidationHelperV1Client, + transports.ValidationHelperV1RestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -544,6 +574,7 @@ def test_validation_helper_v1_client_get_mtls_endpoint_and_cert_source(client_cl transports.ValidationHelperV1GrpcAsyncIOTransport, "grpc_asyncio", ), + (ValidationHelperV1Client, transports.ValidationHelperV1RestTransport, "rest"), ], ) def test_validation_helper_v1_client_client_options_scopes( @@ -584,6 +615,12 @@ def test_validation_helper_v1_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + ValidationHelperV1Client, + transports.ValidationHelperV1RestTransport, + "rest", + None, + ), ], ) def test_validation_helper_v1_client_client_options_credentials_file( @@ -865,6 +902,249 @@ async def test_validate_attestation_occurrence_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + service.ValidateAttestationOccurrenceRequest, + dict, + ], +) +def test_validate_attestation_occurrence_rest(request_type): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"attestor": "projects/sample1/attestors/sample2"} + 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.ValidateAttestationOccurrenceResponse( + result=service.ValidateAttestationOccurrenceResponse.Result.VERIFIED, + denial_reason="denial_reason_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ValidateAttestationOccurrenceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.validate_attestation_occurrence(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.ValidateAttestationOccurrenceResponse) + assert ( + response.result == service.ValidateAttestationOccurrenceResponse.Result.VERIFIED + ) + assert response.denial_reason == "denial_reason_value" + + +def test_validate_attestation_occurrence_rest_required_fields( + request_type=service.ValidateAttestationOccurrenceRequest, +): + transport_class = transports.ValidationHelperV1RestTransport + + request_init = {} + request_init["attestor"] = "" + request_init["occurrence_note"] = "" + request_init["occurrence_resource_uri"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).validate_attestation_occurrence._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["attestor"] = "attestor_value" + jsonified_request["occurrenceNote"] = "occurrence_note_value" + jsonified_request["occurrenceResourceUri"] = "occurrence_resource_uri_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).validate_attestation_occurrence._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "attestor" in jsonified_request + assert jsonified_request["attestor"] == "attestor_value" + assert "occurrenceNote" in jsonified_request + assert jsonified_request["occurrenceNote"] == "occurrence_note_value" + assert "occurrenceResourceUri" in jsonified_request + assert jsonified_request["occurrenceResourceUri"] == "occurrence_resource_uri_value" + + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ValidateAttestationOccurrenceResponse() + # 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 + + pb_return_value = service.ValidateAttestationOccurrenceResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.validate_attestation_occurrence(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_validate_attestation_occurrence_rest_unset_required_fields(): + transport = transports.ValidationHelperV1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.validate_attestation_occurrence._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "attestor", + "attestation", + "occurrenceNote", + "occurrenceResourceUri", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_validate_attestation_occurrence_rest_interceptors(null_interceptor): + transport = transports.ValidationHelperV1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ValidationHelperV1RestInterceptor(), + ) + client = ValidationHelperV1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ValidationHelperV1RestInterceptor, + "post_validate_attestation_occurrence", + ) as post, mock.patch.object( + transports.ValidationHelperV1RestInterceptor, + "pre_validate_attestation_occurrence", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ValidateAttestationOccurrenceRequest.pb( + service.ValidateAttestationOccurrenceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + service.ValidateAttestationOccurrenceResponse.to_json( + service.ValidateAttestationOccurrenceResponse() + ) + ) + + request = service.ValidateAttestationOccurrenceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ValidateAttestationOccurrenceResponse() + + client.validate_attestation_occurrence( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_validate_attestation_occurrence_rest_bad_request( + transport: str = "rest", request_type=service.ValidateAttestationOccurrenceRequest +): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"attestor": "projects/sample1/attestors/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.validate_attestation_occurrence(request) + + +def test_validate_attestation_occurrence_rest_error(): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ValidationHelperV1GrpcTransport( @@ -946,6 +1226,7 @@ def test_transport_get_channel(): [ transports.ValidationHelperV1GrpcTransport, transports.ValidationHelperV1GrpcAsyncIOTransport, + transports.ValidationHelperV1RestTransport, ], ) def test_transport_adc(transport_class): @@ -960,6 +1241,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1087,6 +1369,7 @@ def test_validation_helper_v1_transport_auth_adc(transport_class): [ transports.ValidationHelperV1GrpcTransport, transports.ValidationHelperV1GrpcAsyncIOTransport, + transports.ValidationHelperV1RestTransport, ], ) def test_validation_helper_v1_transport_auth_gdch_credentials(transport_class): @@ -1186,11 +1469,23 @@ def test_validation_helper_v1_grpc_transport_client_cert_source_for_mtls( ) +def test_validation_helper_v1_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ValidationHelperV1RestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_validation_helper_v1_host_no_port(transport_name): @@ -1201,7 +1496,11 @@ def test_validation_helper_v1_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -1209,6 +1508,7 @@ def test_validation_helper_v1_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_validation_helper_v1_host_with_port(transport_name): @@ -1219,7 +1519,33 @@ def test_validation_helper_v1_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:8000") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_validation_helper_v1_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ValidationHelperV1Client( + credentials=creds1, + transport=transport_name, + ) + client2 = ValidationHelperV1Client( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.validate_attestation_occurrence._session + session2 = client2.transport.validate_attestation_occurrence._session + assert session1 != session2 def test_validation_helper_v1_grpc_transport_channel(): @@ -1490,6 +1816,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1507,6 +1834,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py b/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py index 4d9426e..a8398a5 100644 --- a/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py +++ b/tests/unit/gapic/binaryauthorization_v1beta1/test_binauthz_management_service_v1_beta1.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,12 +33,15 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.binaryauthorization_v1beta1.services.binauthz_management_service_v1_beta1 import ( BinauthzManagementServiceV1Beta1AsyncClient, @@ -105,6 +110,7 @@ def test__get_default_mtls_endpoint(): [ (BinauthzManagementServiceV1Beta1Client, "grpc"), (BinauthzManagementServiceV1Beta1AsyncClient, "grpc_asyncio"), + (BinauthzManagementServiceV1Beta1Client, "rest"), ], ) def test_binauthz_management_service_v1_beta1_client_from_service_account_info( @@ -120,7 +126,11 @@ def test_binauthz_management_service_v1_beta1_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -131,6 +141,7 @@ def test_binauthz_management_service_v1_beta1_client_from_service_account_info( transports.BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", ), + (transports.BinauthzManagementServiceV1Beta1RestTransport, "rest"), ], ) def test_binauthz_management_service_v1_beta1_client_service_account_always_use_jwt( @@ -156,6 +167,7 @@ def test_binauthz_management_service_v1_beta1_client_service_account_always_use_ [ (BinauthzManagementServiceV1Beta1Client, "grpc"), (BinauthzManagementServiceV1Beta1AsyncClient, "grpc_asyncio"), + (BinauthzManagementServiceV1Beta1Client, "rest"), ], ) def test_binauthz_management_service_v1_beta1_client_from_service_account_file( @@ -178,13 +190,18 @@ def test_binauthz_management_service_v1_beta1_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) def test_binauthz_management_service_v1_beta1_client_get_transport_class(): transport = BinauthzManagementServiceV1Beta1Client.get_transport_class() available_transports = [ transports.BinauthzManagementServiceV1Beta1GrpcTransport, + transports.BinauthzManagementServiceV1Beta1RestTransport, ] assert transport in available_transports @@ -205,6 +222,11 @@ def test_binauthz_management_service_v1_beta1_client_get_transport_class(): transports.BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", ), + ( + BinauthzManagementServiceV1Beta1Client, + transports.BinauthzManagementServiceV1Beta1RestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -364,6 +386,18 @@ def test_binauthz_management_service_v1_beta1_client_client_options( "grpc_asyncio", "false", ), + ( + BinauthzManagementServiceV1Beta1Client, + transports.BinauthzManagementServiceV1Beta1RestTransport, + "rest", + "true", + ), + ( + BinauthzManagementServiceV1Beta1Client, + transports.BinauthzManagementServiceV1Beta1RestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -573,6 +607,11 @@ def test_binauthz_management_service_v1_beta1_client_get_mtls_endpoint_and_cert_ transports.BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", ), + ( + BinauthzManagementServiceV1Beta1Client, + transports.BinauthzManagementServiceV1Beta1RestTransport, + "rest", + ), ], ) def test_binauthz_management_service_v1_beta1_client_client_options_scopes( @@ -613,6 +652,12 @@ def test_binauthz_management_service_v1_beta1_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + BinauthzManagementServiceV1Beta1Client, + transports.BinauthzManagementServiceV1Beta1RestTransport, + "rest", + None, + ), ], ) def test_binauthz_management_service_v1_beta1_client_client_options_credentials_file( @@ -2574,172 +2619,2236 @@ async def test_delete_attestor_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + service.GetPolicyRequest, + dict, + ], +) +def test_get_policy_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Beta1Client( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/policy"} + 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 = resources.Policy( + name="name_value", + description="description_value", + global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Policy) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.global_policy_evaluation_mode + == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Beta1Client( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + +def test_get_policy_rest_required_fields(request_type=service.GetPolicyRequest): + transport_class = transports.BinauthzManagementServiceV1Beta1RestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Policy() + # 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": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_policy_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Beta1Client( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Beta1Client( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + unset_fields = transport.get_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) - # It is an error to provide scopes and a transport instance. - transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_policy_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1Beta1RestInterceptor(), ) - with pytest.raises(ValueError): - client = BinauthzManagementServiceV1Beta1Client( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, "post_get_policy" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, "pre_get_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetPolicyRequest.pb(service.GetPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Policy.to_json(resources.Policy()) + + request = service.GetPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Policy() + + client.get_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + +def test_get_policy_rest_bad_request( + transport: str = "rest", request_type=service.GetPolicyRequest +): + client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = BinauthzManagementServiceV1Beta1Client(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/policy"} + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_policy(request) + + +def test_get_policy_rest_flattened(): + client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport( + # 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 = resources.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/policy"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_policy(**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/v1beta1/{name=projects/*/policy}" % client.transport._host, args[1] + ) + + +def test_get_policy_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_policy( + service.GetPolicyRequest(), + name="name_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.BinauthzManagementServiceV1Beta1GrpcTransport, - transports.BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport, - ], -) -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_get_policy_rest_error(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + service.UpdatePolicyRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = BinauthzManagementServiceV1Beta1Client.get_transport_class( - transport_name - )( +def test_update_policy_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"policy": {"name": "projects/sample1/policy"}} + request_init["policy"] = { + "name": "projects/sample1/policy", + "description": "description_value", + "global_policy_evaluation_mode": 1, + "admission_whitelist_patterns": [{"name_pattern": "name_pattern_value"}], + "cluster_admission_rules": {}, + "kubernetes_namespace_admission_rules": {}, + "kubernetes_service_account_admission_rules": {}, + "istio_service_identity_admission_rules": {}, + "default_admission_rule": { + "evaluation_mode": 1, + "require_attestations_by": [ + "require_attestations_by_value1", + "require_attestations_by_value2", + ], + "enforcement_mode": 1, + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = resources.Policy( + name="name_value", + description="description_value", + global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Policy) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.global_policy_evaluation_mode + == resources.Policy.GlobalPolicyEvaluationMode.ENABLE + ) + + +def test_update_policy_rest_required_fields(request_type=service.UpdatePolicyRequest): + transport_class = transports.BinauthzManagementServiceV1Beta1RestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = BinauthzManagementServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.BinauthzManagementServiceV1Beta1GrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Policy() + # 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": "put", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_policy_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.update_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("policy",))) -def test_binauthz_management_service_v1_beta1_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BinauthzManagementServiceV1Beta1Transport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_policy_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1Beta1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, "post_update_policy" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, "pre_update_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdatePolicyRequest.pb(service.UpdatePolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Policy.to_json(resources.Policy()) + + request = service.UpdatePolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Policy() -def test_binauthz_management_service_v1_beta1_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.binaryauthorization_v1beta1.services.binauthz_management_service_v1_beta1.transports.BinauthzManagementServiceV1Beta1Transport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.BinauthzManagementServiceV1Beta1Transport( - credentials=ga_credentials.AnonymousCredentials(), + client.update_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "get_policy", - "update_policy", - "create_attestor", - "get_attestor", - "update_attestor", - "list_attestors", - "delete_attestor", + pre.assert_called_once() + post.assert_called_once() + + +def test_update_policy_rest_bad_request( + transport: str = "rest", request_type=service.UpdatePolicyRequest +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() + # send a request that will satisfy transcoding + request_init = {"policy": {"name": "projects/sample1/policy"}} + request_init["policy"] = { + "name": "projects/sample1/policy", + "description": "description_value", + "global_policy_evaluation_mode": 1, + "admission_whitelist_patterns": [{"name_pattern": "name_pattern_value"}], + "cluster_admission_rules": {}, + "kubernetes_namespace_admission_rules": {}, + "kubernetes_service_account_admission_rules": {}, + "istio_service_identity_admission_rules": {}, + "default_admission_rule": { + "evaluation_mode": 1, + "require_attestations_by": [ + "require_attestations_by_value1", + "require_attestations_by_value2", + ], + "enforcement_mode": 1, + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + request = request_type(**request_init) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_policy(request) -def test_binauthz_management_service_v1_beta1_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( +def test_update_policy_rest_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + 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 = resources.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"policy": {"name": "projects/sample1/policy"}} + + # get truthy value for each flattened field + mock_args = dict( + policy=resources.Policy(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_policy(**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/v1beta1/{policy.name=projects/*/policy}" % client.transport._host, + args[1], + ) + + +def test_update_policy_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_policy( + service.UpdatePolicyRequest(), + policy=resources.Policy(name="name_value"), + ) + + +def test_update_policy_rest_error(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateAttestorRequest, + dict, + ], +) +def test_create_attestor_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["attestor"] = { + "name": "name_value", + "description": "description_value", + "user_owned_drydock_note": { + "note_reference": "note_reference_value", + "public_keys": [ + { + "comment": "comment_value", + "id": "id_value", + "ascii_armored_pgp_public_key": "ascii_armored_pgp_public_key_value", + "pkix_public_key": { + "public_key_pem": "public_key_pem_value", + "signature_algorithm": 1, + }, + } + ], + "delegation_service_account_email": "delegation_service_account_email_value", + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = resources.Attestor( + name="name_value", + description="description_value", + user_owned_drydock_note=resources.UserOwnedDrydockNote( + note_reference="note_reference_value" + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_attestor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Attestor) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_create_attestor_rest_required_fields( + request_type=service.CreateAttestorRequest, +): + transport_class = transports.BinauthzManagementServiceV1Beta1RestTransport + + request_init = {} + request_init["parent"] = "" + request_init["attestor_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "attestorId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "attestorId" in jsonified_request + assert jsonified_request["attestorId"] == request_init["attestor_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["attestorId"] = "attestor_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_attestor._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("attestor_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "attestorId" in jsonified_request + assert jsonified_request["attestorId"] == "attestor_id_value" + + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Attestor() + # 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 + + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_attestor(request) + + expected_params = [ + ( + "attestorId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_attestor_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_attestor._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("attestorId",)) + & set( + ( + "parent", + "attestorId", + "attestor", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_attestor_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1Beta1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, + "post_create_attestor", + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, + "pre_create_attestor", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateAttestorRequest.pb(service.CreateAttestorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Attestor.to_json(resources.Attestor()) + + request = service.CreateAttestorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Attestor() + + client.create_attestor( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_attestor_rest_bad_request( + transport: str = "rest", request_type=service.CreateAttestorRequest +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["attestor"] = { + "name": "name_value", + "description": "description_value", + "user_owned_drydock_note": { + "note_reference": "note_reference_value", + "public_keys": [ + { + "comment": "comment_value", + "id": "id_value", + "ascii_armored_pgp_public_key": "ascii_armored_pgp_public_key_value", + "pkix_public_key": { + "public_key_pem": "public_key_pem_value", + "signature_algorithm": 1, + }, + } + ], + "delegation_service_account_email": "delegation_service_account_email_value", + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_attestor(request) + + +def test_create_attestor_rest_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + 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 = resources.Attestor() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + attestor_id="attestor_id_value", + attestor=resources.Attestor(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_attestor(**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/v1beta1/{parent=projects/*}/attestors" % client.transport._host, args[1] + ) + + +def test_create_attestor_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_attestor( + service.CreateAttestorRequest(), + parent="parent_value", + attestor_id="attestor_id_value", + attestor=resources.Attestor(name="name_value"), + ) + + +def test_create_attestor_rest_error(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetAttestorRequest, + dict, + ], +) +def test_get_attestor_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/attestors/sample2"} + 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 = resources.Attestor( + name="name_value", + description="description_value", + user_owned_drydock_note=resources.UserOwnedDrydockNote( + note_reference="note_reference_value" + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_attestor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Attestor) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_get_attestor_rest_required_fields(request_type=service.GetAttestorRequest): + transport_class = transports.BinauthzManagementServiceV1Beta1RestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Attestor() + # 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": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_attestor(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_attestor_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_attestor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attestor_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1Beta1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, "post_get_attestor" + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, "pre_get_attestor" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetAttestorRequest.pb(service.GetAttestorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Attestor.to_json(resources.Attestor()) + + request = service.GetAttestorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Attestor() + + client.get_attestor( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attestor_rest_bad_request( + transport: str = "rest", request_type=service.GetAttestorRequest +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/attestors/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_attestor(request) + + +def test_get_attestor_rest_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + 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 = resources.Attestor() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/attestors/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_attestor(**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/v1beta1/{name=projects/*/attestors/*}" % client.transport._host, args[1] + ) + + +def test_get_attestor_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_attestor( + service.GetAttestorRequest(), + name="name_value", + ) + + +def test_get_attestor_rest_error(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateAttestorRequest, + dict, + ], +) +def test_update_attestor_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"attestor": {"name": "projects/sample1/attestors/sample2"}} + request_init["attestor"] = { + "name": "projects/sample1/attestors/sample2", + "description": "description_value", + "user_owned_drydock_note": { + "note_reference": "note_reference_value", + "public_keys": [ + { + "comment": "comment_value", + "id": "id_value", + "ascii_armored_pgp_public_key": "ascii_armored_pgp_public_key_value", + "pkix_public_key": { + "public_key_pem": "public_key_pem_value", + "signature_algorithm": 1, + }, + } + ], + "delegation_service_account_email": "delegation_service_account_email_value", + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = resources.Attestor( + name="name_value", + description="description_value", + user_owned_drydock_note=resources.UserOwnedDrydockNote( + note_reference="note_reference_value" + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_attestor(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Attestor) + assert response.name == "name_value" + assert response.description == "description_value" + + +def test_update_attestor_rest_required_fields( + request_type=service.UpdateAttestorRequest, +): + transport_class = transports.BinauthzManagementServiceV1Beta1RestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Attestor() + # 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": "put", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_attestor(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_attestor_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_attestor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("attestor",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_attestor_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1Beta1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, + "post_update_attestor", + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, + "pre_update_attestor", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateAttestorRequest.pb(service.UpdateAttestorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Attestor.to_json(resources.Attestor()) + + request = service.UpdateAttestorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Attestor() + + client.update_attestor( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_attestor_rest_bad_request( + transport: str = "rest", request_type=service.UpdateAttestorRequest +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"attestor": {"name": "projects/sample1/attestors/sample2"}} + request_init["attestor"] = { + "name": "projects/sample1/attestors/sample2", + "description": "description_value", + "user_owned_drydock_note": { + "note_reference": "note_reference_value", + "public_keys": [ + { + "comment": "comment_value", + "id": "id_value", + "ascii_armored_pgp_public_key": "ascii_armored_pgp_public_key_value", + "pkix_public_key": { + "public_key_pem": "public_key_pem_value", + "signature_algorithm": 1, + }, + } + ], + "delegation_service_account_email": "delegation_service_account_email_value", + }, + "update_time": {"seconds": 751, "nanos": 543}, + } + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_attestor(request) + + +def test_update_attestor_rest_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + 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 = resources.Attestor() + + # get arguments that satisfy an http rule for this method + sample_request = {"attestor": {"name": "projects/sample1/attestors/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + attestor=resources.Attestor(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Attestor.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_attestor(**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/v1beta1/{attestor.name=projects/*/attestors/*}" + % client.transport._host, + args[1], + ) + + +def test_update_attestor_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_attestor( + service.UpdateAttestorRequest(), + attestor=resources.Attestor(name="name_value"), + ) + + +def test_update_attestor_rest_error(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListAttestorsRequest, + dict, + ], +) +def test_list_attestors_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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.ListAttestorsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListAttestorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_attestors(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAttestorsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_attestors_rest_required_fields(request_type=service.ListAttestorsRequest): + transport_class = transports.BinauthzManagementServiceV1Beta1RestTransport + + 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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_attestors._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_attestors._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListAttestorsResponse() + # 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": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListAttestorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_attestors(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_attestors_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_attestors._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_attestors_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1Beta1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, + "post_list_attestors", + ) as post, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, "pre_list_attestors" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListAttestorsRequest.pb(service.ListAttestorsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListAttestorsResponse.to_json( + service.ListAttestorsResponse() + ) + + request = service.ListAttestorsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListAttestorsResponse() + + client.list_attestors( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_attestors_rest_bad_request( + transport: str = "rest", request_type=service.ListAttestorsRequest +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_attestors(request) + + +def test_list_attestors_rest_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + 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.ListAttestorsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListAttestorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_attestors(**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/v1beta1/{parent=projects/*}/attestors" % client.transport._host, args[1] + ) + + +def test_list_attestors_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_attestors( + service.ListAttestorsRequest(), + parent="parent_value", + ) + + +def test_list_attestors_rest_pager(transport: str = "rest"): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListAttestorsResponse( + attestors=[ + resources.Attestor(), + resources.Attestor(), + resources.Attestor(), + ], + next_page_token="abc", + ), + service.ListAttestorsResponse( + attestors=[], + next_page_token="def", + ), + service.ListAttestorsResponse( + attestors=[ + resources.Attestor(), + ], + next_page_token="ghi", + ), + service.ListAttestorsResponse( + attestors=[ + resources.Attestor(), + resources.Attestor(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListAttestorsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1"} + + pager = client.list_attestors(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Attestor) for i in results) + + pages = list(client.list_attestors(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteAttestorRequest, + dict, + ], +) +def test_delete_attestor_rest(request_type): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/attestors/sample2"} + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_attestor(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_attestor_rest_required_fields( + request_type=service.DeleteAttestorRequest, +): + transport_class = transports.BinauthzManagementServiceV1Beta1RestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_attestor._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_attestor(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_attestor_rest_unset_required_fields(): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_attestor._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_attestor_rest_interceptors(null_interceptor): + transport = transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BinauthzManagementServiceV1Beta1RestInterceptor(), + ) + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.BinauthzManagementServiceV1Beta1RestInterceptor, + "pre_delete_attestor", + ) as pre: + pre.assert_not_called() + pb_message = service.DeleteAttestorRequest.pb(service.DeleteAttestorRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = service.DeleteAttestorRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_attestor( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_attestor_rest_bad_request( + transport: str = "rest", request_type=service.DeleteAttestorRequest +): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/attestors/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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_attestor(request) + + +def test_delete_attestor_rest_flattened(): + client = BinauthzManagementServiceV1Beta1Client( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/attestors/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_attestor(**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/v1beta1/{name=projects/*/attestors/*}" % client.transport._host, args[1] + ) + + +def test_delete_attestor_rest_flattened_error(transport: str = "rest"): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_attestor( + service.DeleteAttestorRequest(), + name="name_value", + ) + + +def test_delete_attestor_rest_error(): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Beta1Client( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Beta1Client( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Beta1Client( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BinauthzManagementServiceV1Beta1Client( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BinauthzManagementServiceV1Beta1Client(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BinauthzManagementServiceV1Beta1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BinauthzManagementServiceV1Beta1GrpcTransport, + transports.BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport, + transports.BinauthzManagementServiceV1Beta1RestTransport, + ], +) +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() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = BinauthzManagementServiceV1Beta1Client.get_transport_class( + transport_name + )( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BinauthzManagementServiceV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BinauthzManagementServiceV1Beta1GrpcTransport, + ) + + +def test_binauthz_management_service_v1_beta1_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BinauthzManagementServiceV1Beta1Transport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_binauthz_management_service_v1_beta1_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.binaryauthorization_v1beta1.services.binauthz_management_service_v1_beta1.transports.BinauthzManagementServiceV1Beta1Transport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.BinauthzManagementServiceV1Beta1Transport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_policy", + "update_policy", + "create_attestor", + "get_attestor", + "update_attestor", + "list_attestors", + "delete_attestor", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_binauthz_management_service_v1_beta1_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.binaryauthorization_v1beta1.services.binauthz_management_service_v1_beta1.transports.BinauthzManagementServiceV1Beta1Transport._prep_wrapped_messages" @@ -2806,6 +4915,7 @@ def test_binauthz_management_service_v1_beta1_transport_auth_adc(transport_class [ transports.BinauthzManagementServiceV1Beta1GrpcTransport, transports.BinauthzManagementServiceV1Beta1GrpcAsyncIOTransport, + transports.BinauthzManagementServiceV1Beta1RestTransport, ], ) def test_binauthz_management_service_v1_beta1_transport_auth_gdch_credentials( @@ -2912,11 +5022,23 @@ def test_binauthz_management_service_v1_beta1_grpc_transport_client_cert_source_ ) +def test_binauthz_management_service_v1_beta1_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.BinauthzManagementServiceV1Beta1RestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_binauthz_management_service_v1_beta1_host_no_port(transport_name): @@ -2927,7 +5049,11 @@ def test_binauthz_management_service_v1_beta1_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -2935,6 +5061,7 @@ def test_binauthz_management_service_v1_beta1_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_binauthz_management_service_v1_beta1_host_with_port(transport_name): @@ -2945,7 +5072,53 @@ def test_binauthz_management_service_v1_beta1_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:8000") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_binauthz_management_service_v1_beta1_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BinauthzManagementServiceV1Beta1Client( + credentials=creds1, + transport=transport_name, + ) + client2 = BinauthzManagementServiceV1Beta1Client( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_policy._session + session2 = client2.transport.get_policy._session + assert session1 != session2 + session1 = client1.transport.update_policy._session + session2 = client2.transport.update_policy._session + assert session1 != session2 + session1 = client1.transport.create_attestor._session + session2 = client2.transport.create_attestor._session + assert session1 != session2 + session1 = client1.transport.get_attestor._session + session2 = client2.transport.get_attestor._session + assert session1 != session2 + session1 = client1.transport.update_attestor._session + session2 = client2.transport.update_attestor._session + assert session1 != session2 + session1 = client1.transport.list_attestors._session + session2 = client2.transport.list_attestors._session + assert session1 != session2 + session1 = client1.transport.delete_attestor._session + session2 = client2.transport.delete_attestor._session + assert session1 != session2 def test_binauthz_management_service_v1_beta1_grpc_transport_channel(): @@ -3271,6 +5444,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -3288,6 +5462,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py b/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py index 17449a1..e7f4d0e 100644 --- a/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py +++ b/tests/unit/gapic/binaryauthorization_v1beta1/test_system_policy_v1_beta1.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,12 +33,15 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.binaryauthorization_v1beta1.services.system_policy_v1_beta1 import ( SystemPolicyV1Beta1AsyncClient, @@ -96,6 +101,7 @@ def test__get_default_mtls_endpoint(): [ (SystemPolicyV1Beta1Client, "grpc"), (SystemPolicyV1Beta1AsyncClient, "grpc_asyncio"), + (SystemPolicyV1Beta1Client, "rest"), ], ) def test_system_policy_v1_beta1_client_from_service_account_info( @@ -111,7 +117,11 @@ def test_system_policy_v1_beta1_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -119,6 +129,7 @@ def test_system_policy_v1_beta1_client_from_service_account_info( [ (transports.SystemPolicyV1Beta1GrpcTransport, "grpc"), (transports.SystemPolicyV1Beta1GrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SystemPolicyV1Beta1RestTransport, "rest"), ], ) def test_system_policy_v1_beta1_client_service_account_always_use_jwt( @@ -144,6 +155,7 @@ def test_system_policy_v1_beta1_client_service_account_always_use_jwt( [ (SystemPolicyV1Beta1Client, "grpc"), (SystemPolicyV1Beta1AsyncClient, "grpc_asyncio"), + (SystemPolicyV1Beta1Client, "rest"), ], ) def test_system_policy_v1_beta1_client_from_service_account_file( @@ -166,13 +178,18 @@ def test_system_policy_v1_beta1_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) def test_system_policy_v1_beta1_client_get_transport_class(): transport = SystemPolicyV1Beta1Client.get_transport_class() available_transports = [ transports.SystemPolicyV1Beta1GrpcTransport, + transports.SystemPolicyV1Beta1RestTransport, ] assert transport in available_transports @@ -193,6 +210,11 @@ def test_system_policy_v1_beta1_client_get_transport_class(): transports.SystemPolicyV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", ), + ( + SystemPolicyV1Beta1Client, + transports.SystemPolicyV1Beta1RestTransport, + "rest", + ), ], ) @mock.patch.object( @@ -348,6 +370,18 @@ def test_system_policy_v1_beta1_client_client_options( "grpc_asyncio", "false", ), + ( + SystemPolicyV1Beta1Client, + transports.SystemPolicyV1Beta1RestTransport, + "rest", + "true", + ), + ( + SystemPolicyV1Beta1Client, + transports.SystemPolicyV1Beta1RestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -551,6 +585,11 @@ def test_system_policy_v1_beta1_client_get_mtls_endpoint_and_cert_source(client_ transports.SystemPolicyV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", ), + ( + SystemPolicyV1Beta1Client, + transports.SystemPolicyV1Beta1RestTransport, + "rest", + ), ], ) def test_system_policy_v1_beta1_client_client_options_scopes( @@ -591,6 +630,12 @@ def test_system_policy_v1_beta1_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + SystemPolicyV1Beta1Client, + transports.SystemPolicyV1Beta1RestTransport, + "rest", + None, + ), ], ) def test_system_policy_v1_beta1_client_client_options_credentials_file( @@ -959,6 +1004,275 @@ async def test_get_system_policy_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + service.GetSystemPolicyRequest, + dict, + ], +) +def test_get_system_policy_rest(request_type): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "locations/sample1/policy"} + 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 = resources.Policy( + name="name_value", + description="description_value", + global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_system_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Policy) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.global_policy_evaluation_mode + == resources.Policy.GlobalPolicyEvaluationMode.ENABLE + ) + + +def test_get_system_policy_rest_required_fields( + request_type=service.GetSystemPolicyRequest, +): + transport_class = transports.SystemPolicyV1Beta1RestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_system_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_system_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Policy() + # 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": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_system_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_system_policy_rest_unset_required_fields(): + transport = transports.SystemPolicyV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_system_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_system_policy_rest_interceptors(null_interceptor): + transport = transports.SystemPolicyV1Beta1RestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SystemPolicyV1Beta1RestInterceptor(), + ) + client = SystemPolicyV1Beta1Client(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SystemPolicyV1Beta1RestInterceptor, "post_get_system_policy" + ) as post, mock.patch.object( + transports.SystemPolicyV1Beta1RestInterceptor, "pre_get_system_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetSystemPolicyRequest.pb(service.GetSystemPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Policy.to_json(resources.Policy()) + + request = service.GetSystemPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Policy() + + client.get_system_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_system_policy_rest_bad_request( + transport: str = "rest", request_type=service.GetSystemPolicyRequest +): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "locations/sample1/policy"} + 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_system_policy(request) + + +def test_get_system_policy_rest_flattened(): + client = SystemPolicyV1Beta1Client( + 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 = resources.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "locations/sample1/policy"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_system_policy(**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/v1beta1/{name=locations/*/policy}" % client.transport._host, args[1] + ) + + +def test_get_system_policy_rest_flattened_error(transport: str = "rest"): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_system_policy( + service.GetSystemPolicyRequest(), + name="name_value", + ) + + +def test_get_system_policy_rest_error(): + client = SystemPolicyV1Beta1Client( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SystemPolicyV1Beta1GrpcTransport( @@ -1040,6 +1354,7 @@ def test_transport_get_channel(): [ transports.SystemPolicyV1Beta1GrpcTransport, transports.SystemPolicyV1Beta1GrpcAsyncIOTransport, + transports.SystemPolicyV1Beta1RestTransport, ], ) def test_transport_adc(transport_class): @@ -1054,6 +1369,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1181,6 +1497,7 @@ def test_system_policy_v1_beta1_transport_auth_adc(transport_class): [ transports.SystemPolicyV1Beta1GrpcTransport, transports.SystemPolicyV1Beta1GrpcAsyncIOTransport, + transports.SystemPolicyV1Beta1RestTransport, ], ) def test_system_policy_v1_beta1_transport_auth_gdch_credentials(transport_class): @@ -1280,11 +1597,23 @@ def test_system_policy_v1_beta1_grpc_transport_client_cert_source_for_mtls( ) +def test_system_policy_v1_beta1_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SystemPolicyV1Beta1RestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_system_policy_v1_beta1_host_no_port(transport_name): @@ -1295,7 +1624,11 @@ def test_system_policy_v1_beta1_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:443") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com" + ) @pytest.mark.parametrize( @@ -1303,6 +1636,7 @@ def test_system_policy_v1_beta1_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_system_policy_v1_beta1_host_with_port(transport_name): @@ -1313,7 +1647,33 @@ def test_system_policy_v1_beta1_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("binaryauthorization.googleapis.com:8000") + assert client.transport._host == ( + "binaryauthorization.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://binaryauthorization.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_system_policy_v1_beta1_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SystemPolicyV1Beta1Client( + credentials=creds1, + transport=transport_name, + ) + client2 = SystemPolicyV1Beta1Client( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_system_policy._session + session2 = client2.transport.get_system_policy._session + assert session1 != session2 def test_system_policy_v1_beta1_grpc_transport_channel(): @@ -1604,6 +1964,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -1621,6 +1982,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: