From e2c164e81fa55d5e2c593ef3487f0c67cc69df82 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 2 Nov 2021 18:37:43 +0100 Subject: [PATCH 01/24] chore(deps): update dependency google-cloud-kms to v2.10.1 (#202) --- samples/snippets/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index ae848175..25fbb41f 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,3 +1,3 @@ -google-cloud-kms==2.10.0 +google-cloud-kms==2.10.1 cryptography==35.0.0 crcmod==1.7 From c9823362dd3544f828410c1941314c8a2a41955c Mon Sep 17 00:00:00 2001 From: Benson Kuang <3453547+bkuang@users.noreply.github.com> Date: Wed, 3 Nov 2021 18:51:29 -0400 Subject: [PATCH 02/24] chore: update README and fix typos in attestation scripts (#203) Remove the README.rst.in until the README gen templates have been updated Co-authored-by: Benson Kuang --- samples/attestations/README.rst | 15 ++++++++------ samples/attestations/README.rst.in | 23 ---------------------- samples/attestations/verify_attestation.py | 2 +- 3 files changed, 10 insertions(+), 30 deletions(-) delete mode 100644 samples/attestations/README.rst.in diff --git a/samples/attestations/README.rst b/samples/attestations/README.rst index 4a9ff7f7..de84a153 100644 --- a/samples/attestations/README.rst +++ b/samples/attestations/README.rst @@ -1,5 +1,3 @@ -.. This file is automatically generated. Do not edit this file directly. - Google Cloud Key Management Service Python Samples =============================================================================== @@ -12,7 +10,7 @@ This directory contains samples for Google Cloud Key Management Service. The `Cl -.. _Google Cloud Key Management Service: https://cloud.google.com/kms/docs/ +.. _Cloud Key Management Service: https://cloud.google.com/kms/docs/ @@ -25,11 +23,11 @@ Setup Install Dependencies ++++++++++++++++++++ -#. Clone python-docs-samples and change directory to the sample directory you want to use. +#. Clone python-kms and change directory to the sample directory you want to use. .. code-block:: bash - $ git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git + $ git clone https://github.com/googleapis/python-kms.git #. Install `pip`_ and `virtualenv`_ if you do not already have them. You may want to refer to the `Python Development Environment Setup Guide`_ for Google Cloud Platform for instructions. @@ -43,6 +41,11 @@ Install Dependencies $ virtualenv env $ source env/bin/activate +#. Install the dependencies needed to run the samples. + + .. code-block:: bash + + $ pip install -r requirements.txt .. _pip: https://pip.pypa.io/ .. _virtualenv: https://virtualenv.pypa.io/ @@ -86,7 +89,7 @@ Verify attestations for keys generated by Cloud HSM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ .. image:: https://gstatic.com/cloudssh/images/open-btn.png - :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=samples/attestations/verify_attestation.py,samples/attestations/README.rst + :target: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/python-kms&page=editor&open_in_editor=samples/attestations/verify_attestation.py,samples/attestations/README.rst diff --git a/samples/attestations/README.rst.in b/samples/attestations/README.rst.in deleted file mode 100644 index 596ab5fe..00000000 --- a/samples/attestations/README.rst.in +++ /dev/null @@ -1,23 +0,0 @@ -# This file is used to generate README.rst - -product: - name: Google Cloud Key Management Service - short_name: Cloud Key Management Service - url: https://cloud.google.com/kms/docs/ - description: > - The `Cloud Key Management Service`_ allows you to create, import, and manage - cryptographic keys and perform cryptographic operations in a single centralized cloud service. - -setup: -- install_deps - -samples: -- name: Verify attestations and certificate chains for keys generated by Cloud HSM - file: verify_attestation_chains.py - show_help: True -- name: Verify attestations for keys generated by Cloud HSM - file: verify_attestation.py - show_help: True - -folder: samples/attestations - diff --git a/samples/attestations/verify_attestation.py b/samples/attestations/verify_attestation.py index e534ad9e..090f6b81 100644 --- a/samples/attestations/verify_attestation.py +++ b/samples/attestations/verify_attestation.py @@ -56,7 +56,7 @@ def verify(attestation_file, bundle_file): cert_obj = x509.load_pem_x509_certificate( str(cert).encode('utf-8'), backends.default_backend()) try: - # Check if the data was signed by the private key assosicated + # Check if the data was signed by the private key associated # with the public key in the certificate. The data should have # been signed with PKCS1v15 padding. cert_obj.public_key().verify( From f4747799bd6f0e2c0e2e8cf6cf86ee4df4568687 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 9 Nov 2021 19:02:44 -0500 Subject: [PATCH 03/24] chore: use gapic-generator-python 0.56.2 (#206) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: update Java and Python dependencies PiperOrigin-RevId: 408420890 Source-Link: https://github.com/googleapis/googleapis/commit/2921f9fb3bfbd16f6b2da0104373e2b47a80a65e Source-Link: https://github.com/googleapis/googleapis-gen/commit/6598ca8cbbf5226733a099c4506518a5af6ff74c Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNjU5OGNhOGNiYmY1MjI2NzMzYTA5OWM0NTA2NTE4YTVhZjZmZjc0YyJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- .../key_management_service/async_client.py | 13 +- .../services/key_management_service/client.py | 25 +- .../key_management_service/transports/base.py | 8 +- .../key_management_service/transports/grpc.py | 4 +- .../transports/grpc_asyncio.py | 4 +- google/cloud/kms_v1/types/resources.py | 1 + google/cloud/kms_v1/types/service.py | 4 + .../kms_v1/test_key_management_service.py | 360 +++++++++++++----- 8 files changed, 302 insertions(+), 117 deletions(-) diff --git a/google/cloud/kms_v1/services/key_management_service/async_client.py b/google/cloud/kms_v1/services/key_management_service/async_client.py index ab33fbb7..e549e6ef 100644 --- a/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -19,14 +19,17 @@ from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.kms_v1.services.key_management_service import pagers from google.cloud.kms_v1.types import resources diff --git a/google/cloud/kms_v1/services/key_management_service/client.py b/google/cloud/kms_v1/services/key_management_service/client.py index f693f31d..d0837727 100644 --- a/google/cloud/kms_v1/services/key_management_service/client.py +++ b/google/cloud/kms_v1/services/key_management_service/client.py @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.kms_v1.services.key_management_service import pagers from google.cloud.kms_v1.types import resources @@ -403,8 +405,15 @@ def __init__( client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ( + "true", + "false", + ): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + use_client_cert = ( + os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" ) client_cert_source_func = None diff --git a/google/cloud/kms_v1/services/key_management_service/transports/base.py b/google/cloud/kms_v1/services/key_management_service/transports/base.py index aa996a8d..9d9d22d3 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/base.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/base.py @@ -18,10 +18,10 @@ import pkg_resources import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore diff --git a/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/google/cloud/kms_v1/services/key_management_service/transports/grpc.py index b8151bfd..0fabb11e 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -16,8 +16,8 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py index 6cefe660..ccce24a4 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -16,8 +16,8 @@ import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore diff --git a/google/cloud/kms_v1/types/resources.py b/google/cloud/kms_v1/types/resources.py index 813a87d1..73b284ca 100644 --- a/google/cloud/kms_v1/types/resources.py +++ b/google/cloud/kms_v1/types/resources.py @@ -141,6 +141,7 @@ class CryptoKey(proto.Message): [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] support automatic rotation. For other keys, this field must be omitted. + This field is a member of `oneof`_ ``rotation_schedule``. version_template (google.cloud.kms_v1.types.CryptoKeyVersionTemplate): A template describing settings for new diff --git a/google/cloud/kms_v1/types/service.py b/google/cloud/kms_v1/types/service.py index 4374489e..b3673654 100644 --- a/google/cloud/kms_v1/types/service.py +++ b/google/cloud/kms_v1/types/service.py @@ -576,6 +576,7 @@ class ImportCryptoKeyVersionRequest(proto.Message): This format is the same as the format produced by PKCS#11 mechanism CKM_RSA_AES_KEY_WRAP. + This field is a member of `oneof`_ ``wrapped_key_material``. """ @@ -1548,14 +1549,17 @@ class Digest(proto.Message): sha256 (bytes): A message digest produced with the SHA-256 algorithm. + This field is a member of `oneof`_ ``digest``. sha384 (bytes): A message digest produced with the SHA-384 algorithm. + This field is a member of `oneof`_ ``digest``. sha512 (bytes): A message digest produced with the SHA-512 algorithm. + This field is a member of `oneof`_ ``digest``. """ diff --git a/tests/unit/gapic/kms_v1/test_key_management_service.py b/tests/unit/gapic/kms_v1/test_key_management_service.py index d3739179..2019f42d 100644 --- a/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -671,7 +671,9 @@ def test_list_key_rings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val def test_list_key_rings_flattened_error(): @@ -709,7 +711,9 @@ async def test_list_key_rings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val @pytest.mark.asyncio @@ -1031,7 +1035,9 @@ def test_list_crypto_keys_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val def test_list_crypto_keys_flattened_error(): @@ -1069,7 +1075,9 @@ async def test_list_crypto_keys_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val @pytest.mark.asyncio @@ -1403,7 +1411,9 @@ def test_list_crypto_key_versions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val def test_list_crypto_key_versions_flattened_error(): @@ -1443,7 +1453,9 @@ async def test_list_crypto_key_versions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val @pytest.mark.asyncio @@ -1797,7 +1809,9 @@ def test_list_import_jobs_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val def test_list_import_jobs_flattened_error(): @@ -1835,7 +1849,9 @@ async def test_list_import_jobs_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val @pytest.mark.asyncio @@ -2147,7 +2163,9 @@ def test_get_key_ring_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_get_key_ring_flattened_error(): @@ -2183,7 +2201,9 @@ async def test_get_key_ring_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -2364,7 +2384,9 @@ def test_get_crypto_key_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_get_crypto_key_flattened_error(): @@ -2400,7 +2422,9 @@ async def test_get_crypto_key_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -2622,7 +2646,9 @@ def test_get_crypto_key_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_get_crypto_key_version_flattened_error(): @@ -2662,7 +2688,9 @@ async def test_get_crypto_key_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -2852,7 +2880,9 @@ def test_get_public_key_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_get_public_key_flattened_error(): @@ -2888,7 +2918,9 @@ async def test_get_public_key_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -3078,7 +3110,9 @@ def test_get_import_job_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_get_import_job_flattened_error(): @@ -3114,7 +3148,9 @@ async def test_get_import_job_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -3286,9 +3322,15 @@ def test_create_key_ring_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].key_ring_id == "key_ring_id_value" - assert args[0].key_ring == resources.KeyRing(name="name_value") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].key_ring_id + mock_val = "key_ring_id_value" + assert arg == mock_val + arg = args[0].key_ring + mock_val = resources.KeyRing(name="name_value") + assert arg == mock_val def test_create_key_ring_flattened_error(): @@ -3331,9 +3373,15 @@ async def test_create_key_ring_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].key_ring_id == "key_ring_id_value" - assert args[0].key_ring == resources.KeyRing(name="name_value") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].key_ring_id + mock_val = "key_ring_id_value" + assert arg == mock_val + arg = args[0].key_ring + mock_val = resources.KeyRing(name="name_value") + assert arg == mock_val @pytest.mark.asyncio @@ -3533,9 +3581,15 @@ def test_create_crypto_key_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].crypto_key_id == "crypto_key_id_value" - assert args[0].crypto_key == resources.CryptoKey(name="name_value") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].crypto_key_id + mock_val = "crypto_key_id_value" + assert arg == mock_val + arg = args[0].crypto_key + mock_val = resources.CryptoKey(name="name_value") + assert arg == mock_val def test_create_crypto_key_flattened_error(): @@ -3580,9 +3634,15 @@ async def test_create_crypto_key_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].crypto_key_id == "crypto_key_id_value" - assert args[0].crypto_key == resources.CryptoKey(name="name_value") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].crypto_key_id + mock_val = "crypto_key_id_value" + assert arg == mock_val + arg = args[0].crypto_key + mock_val = resources.CryptoKey(name="name_value") + assert arg == mock_val @pytest.mark.asyncio @@ -3810,10 +3870,12 @@ def test_create_crypto_key_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].crypto_key_version == resources.CryptoKeyVersion( - name="name_value" - ) + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].crypto_key_version + mock_val = resources.CryptoKeyVersion(name="name_value") + assert arg == mock_val def test_create_crypto_key_version_flattened_error(): @@ -3858,10 +3920,12 @@ async def test_create_crypto_key_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].crypto_key_version == resources.CryptoKeyVersion( - name="name_value" - ) + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].crypto_key_version + mock_val = resources.CryptoKeyVersion(name="name_value") + assert arg == mock_val @pytest.mark.asyncio @@ -4255,9 +4319,15 @@ def test_create_import_job_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].import_job_id == "import_job_id_value" - assert args[0].import_job == resources.ImportJob(name="name_value") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].import_job_id + mock_val = "import_job_id_value" + assert arg == mock_val + arg = args[0].import_job + mock_val = resources.ImportJob(name="name_value") + assert arg == mock_val def test_create_import_job_flattened_error(): @@ -4302,9 +4372,15 @@ async def test_create_import_job_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].import_job_id == "import_job_id_value" - assert args[0].import_job == resources.ImportJob(name="name_value") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].import_job_id + mock_val = "import_job_id_value" + assert arg == mock_val + arg = args[0].import_job + mock_val = resources.ImportJob(name="name_value") + assert arg == mock_val @pytest.mark.asyncio @@ -4507,8 +4583,12 @@ def test_update_crypto_key_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].crypto_key == resources.CryptoKey(name="name_value") - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].crypto_key + mock_val = resources.CryptoKey(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val def test_update_crypto_key_flattened_error(): @@ -4551,8 +4631,12 @@ async def test_update_crypto_key_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].crypto_key == resources.CryptoKey(name="name_value") - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].crypto_key + mock_val = resources.CryptoKey(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val @pytest.mark.asyncio @@ -4785,10 +4869,12 @@ def test_update_crypto_key_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].crypto_key_version == resources.CryptoKeyVersion( - name="name_value" - ) - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].crypto_key_version + mock_val = resources.CryptoKeyVersion(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val def test_update_crypto_key_version_flattened_error(): @@ -4833,10 +4919,12 @@ async def test_update_crypto_key_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].crypto_key_version == resources.CryptoKeyVersion( - name="name_value" - ) - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].crypto_key_version + mock_val = resources.CryptoKeyVersion(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val @pytest.mark.asyncio @@ -5034,8 +5122,12 @@ def test_update_crypto_key_primary_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].crypto_key_version_id == "crypto_key_version_id_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].crypto_key_version_id + mock_val = "crypto_key_version_id_value" + assert arg == mock_val def test_update_crypto_key_primary_version_flattened_error(): @@ -5077,8 +5169,12 @@ async def test_update_crypto_key_primary_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].crypto_key_version_id == "crypto_key_version_id_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].crypto_key_version_id + mock_val = "crypto_key_version_id_value" + assert arg == mock_val @pytest.mark.asyncio @@ -5302,7 +5398,9 @@ def test_destroy_crypto_key_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_destroy_crypto_key_version_flattened_error(): @@ -5342,7 +5440,9 @@ async def test_destroy_crypto_key_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -5564,7 +5664,9 @@ def test_restore_crypto_key_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val def test_restore_crypto_key_version_flattened_error(): @@ -5604,7 +5706,9 @@ async def test_restore_crypto_key_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val @pytest.mark.asyncio @@ -5794,8 +5898,12 @@ def test_encrypt_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].plaintext == b"plaintext_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].plaintext + mock_val = b"plaintext_blob" + assert arg == mock_val def test_encrypt_flattened_error(): @@ -5833,8 +5941,12 @@ async def test_encrypt_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].plaintext == b"plaintext_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].plaintext + mock_val = b"plaintext_blob" + assert arg == mock_val @pytest.mark.asyncio @@ -6016,8 +6128,12 @@ def test_decrypt_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].ciphertext == b"ciphertext_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ciphertext + mock_val = b"ciphertext_blob" + assert arg == mock_val def test_decrypt_flattened_error(): @@ -6057,8 +6173,12 @@ async def test_decrypt_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].ciphertext == b"ciphertext_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ciphertext + mock_val = b"ciphertext_blob" + assert arg == mock_val @pytest.mark.asyncio @@ -6250,8 +6370,12 @@ def test_asymmetric_sign_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].digest == service.Digest(sha256=b"sha256_blob") + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].digest + mock_val = service.Digest(sha256=b"sha256_blob") + assert arg == mock_val def test_asymmetric_sign_flattened_error(): @@ -6293,8 +6417,12 @@ async def test_asymmetric_sign_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].digest == service.Digest(sha256=b"sha256_blob") + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].digest + mock_val = service.Digest(sha256=b"sha256_blob") + assert arg == mock_val @pytest.mark.asyncio @@ -6492,8 +6620,12 @@ def test_asymmetric_decrypt_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].ciphertext == b"ciphertext_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ciphertext + mock_val = b"ciphertext_blob" + assert arg == mock_val def test_asymmetric_decrypt_flattened_error(): @@ -6537,8 +6669,12 @@ async def test_asymmetric_decrypt_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].ciphertext == b"ciphertext_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ciphertext + mock_val = b"ciphertext_blob" + assert arg == mock_val @pytest.mark.asyncio @@ -6726,8 +6862,12 @@ def test_mac_sign_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].data == b"data_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].data + mock_val = b"data_blob" + assert arg == mock_val def test_mac_sign_flattened_error(): @@ -6765,8 +6905,12 @@ async def test_mac_sign_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].data == b"data_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].data + mock_val = b"data_blob" + assert arg == mock_val @pytest.mark.asyncio @@ -6960,9 +7104,15 @@ def test_mac_verify_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].data == b"data_blob" - assert args[0].mac == b"mac_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].data + mock_val = b"data_blob" + assert arg == mock_val + arg = args[0].mac + mock_val = b"mac_blob" + assert arg == mock_val def test_mac_verify_flattened_error(): @@ -7005,9 +7155,15 @@ async def test_mac_verify_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].data == b"data_blob" - assert args[0].mac == b"mac_blob" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].data + mock_val = b"data_blob" + assert arg == mock_val + arg = args[0].mac + mock_val = b"mac_blob" + assert arg == mock_val @pytest.mark.asyncio @@ -7196,9 +7352,15 @@ def test_generate_random_bytes_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].location == "location_value" - assert args[0].length_bytes == 1288 - assert args[0].protection_level == resources.ProtectionLevel.SOFTWARE + arg = args[0].location + mock_val = "location_value" + assert arg == mock_val + arg = args[0].length_bytes + mock_val = 1288 + assert arg == mock_val + arg = args[0].protection_level + mock_val = resources.ProtectionLevel.SOFTWARE + assert arg == mock_val def test_generate_random_bytes_flattened_error(): @@ -7245,9 +7407,15 @@ async def test_generate_random_bytes_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].location == "location_value" - assert args[0].length_bytes == 1288 - assert args[0].protection_level == resources.ProtectionLevel.SOFTWARE + arg = args[0].location + mock_val = "location_value" + assert arg == mock_val + arg = args[0].length_bytes + mock_val = 1288 + assert arg == mock_val + arg = args[0].protection_level + mock_val = resources.ProtectionLevel.SOFTWARE + assert arg == mock_val @pytest.mark.asyncio From fb1bae6c93d231cff4ba5570cf0b47c4cb66dde6 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 11 Nov 2021 12:25:35 -0500 Subject: [PATCH 04/24] chore(python): add .github/CODEOWNERS as a templated file (#208) Source-Link: https://github.com/googleapis/synthtool/commit/c5026b3217973a8db55db8ee85feee0e9a65e295 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:0e18b9475fbeb12d9ad4302283171edebb6baf2dfca1bd215ee3b34ed79d95d7 Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- .github/CODEOWNERS | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index cb89b2e3..7519fa3a 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:ec49167c606648a063d1222220b48119c912562849a0528f35bfb592a9f72737 + digest: sha256:0e18b9475fbeb12d9ad4302283171edebb6baf2dfca1bd215ee3b34ed79d95d7 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 45b962fb..44cc8685 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,9 +3,10 @@ # # For syntax help see: # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax +# Note: This file is autogenerated. To make changes to the codeowner team, please update .repo-metadata.json. -# The @googleapis/yoshi-python is the default owner for changes in this repo -* @googleapis/yoshi-python +# @googleapis/yoshi-python is the default owner for changes in this repo +* @googleapis/yoshi-python - -/samples/**/*.py @DanSanche @googleapis/python-samples-owners +# @googleapis/python-samples-owners is the default owner for samples changes +/samples/ @googleapis/python-samples-owners From ab3476d5e0e0f8afbbc12d84e2d34bcbe60c6aab Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Thu, 11 Nov 2021 15:11:16 -0500 Subject: [PATCH 05/24] chore: add default_version and codeowner_team to .repo-metadata.json (#207) --- .repo-metadata.json | 50 ++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/.repo-metadata.json b/.repo-metadata.json index 75f99e9f..2577b88e 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -1,24 +1,28 @@ { - "name": "cloudkms", - "name_pretty": "Google Cloud Key Management Service", - "product_documentation": "https://cloud.google.com/kms", - "client_documentation": "https://googleapis.dev/python/cloudkms/latest", - "issue_tracker": "https://issuetracker.google.com/savedsearches/5264932", - "release_level": "ga", - "language": "python", - "library_type": "GAPIC_AUTO", - "repo": "googleapis/python-kms", - "distribution_name": "google-cloud-kms", - "api_id": "cloudkms.googleapis.com", - "requires_billing": true, - "client_library": true, - "custom_content": "The Google Cloud KMS API is a service that allows you to keep encryption keys centrally in the cloud, for direct use by cloud services. More info about Cloud KMS can be found at https://cloud.google.com/kms/docs/", - "sample_project_dir": "samples/snippets/", - "samples": [ - {"name": "Quickstart", - "description": "This quickstart shows you how to create and use encryption keys with Cloud Key Management Service.", - "file": "quickstart.py", - "runnable": true, - "custom_content": "More information about the Cloud KMS quickstart is available at https://cloud.google.com/kms/docs/quickstart"} - ] -} \ No newline at end of file + "name": "cloudkms", + "name_pretty": "Google Cloud Key Management Service", + "product_documentation": "https://cloud.google.com/kms", + "client_documentation": "https://googleapis.dev/python/cloudkms/latest", + "issue_tracker": "https://issuetracker.google.com/savedsearches/5264932", + "release_level": "ga", + "language": "python", + "library_type": "GAPIC_AUTO", + "repo": "googleapis/python-kms", + "distribution_name": "google-cloud-kms", + "api_id": "cloudkms.googleapis.com", + "requires_billing": true, + "client_library": true, + "custom_content": "The Google Cloud KMS API is a service that allows you to keep encryption keys centrally in the cloud, for direct use by cloud services. More info about Cloud KMS can be found at https://cloud.google.com/kms/docs/", + "sample_project_dir": "samples/snippets/", + "samples": [ + { + "name": "Quickstart", + "description": "This quickstart shows you how to create and use encryption keys with Cloud Key Management Service.", + "file": "quickstart.py", + "runnable": true, + "custom_content": "More information about the Cloud KMS quickstart is available at https://cloud.google.com/kms/docs/quickstart" + } + ], + "default_version": "v1", + "codeowner_team": "" +} From fe1a1999b03b0b0de7ea3a4ee9a6bcbb55bcae13 Mon Sep 17 00:00:00 2001 From: Dan Lee <71398022+dandhlee@users.noreply.github.com> Date: Thu, 18 Nov 2021 13:04:12 -0500 Subject: [PATCH 06/24] chore: update doc links from googleapis.dev to cloud.google.com (#209) --- .repo-metadata.json | 2 +- README.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.repo-metadata.json b/.repo-metadata.json index 2577b88e..d3cbefa8 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -2,7 +2,7 @@ "name": "cloudkms", "name_pretty": "Google Cloud Key Management Service", "product_documentation": "https://cloud.google.com/kms", - "client_documentation": "https://googleapis.dev/python/cloudkms/latest", + "client_documentation": "https://cloud.google.com/python/docs/reference/cloudkms/latest", "issue_tracker": "https://issuetracker.google.com/savedsearches/5264932", "release_level": "ga", "language": "python", diff --git a/README.rst b/README.rst index fdbdc75c..45703fe0 100644 --- a/README.rst +++ b/README.rst @@ -17,7 +17,7 @@ cloud resources and applications. .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-kms.svg :target: https://pypi.org/project/google-cloud-kms/ .. _Cloud Key Management Service (KMS) API: https://cloud.google.com/kms -.. _Client Library Documentation: https://googleapis.dev/python/cloudkms/latest +.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/cloudkms/latest .. _Product Documentation: https://cloud.google.com/kms Quick Start From d3124878e796fdd7e622eb7381b185d55eb5e87f Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 23 Nov 2021 16:29:34 +0100 Subject: [PATCH 07/24] chore(deps): update dependency cryptography to v36 (#210) --- samples/attestations/requirements.txt | 2 +- samples/snippets/requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/attestations/requirements.txt b/samples/attestations/requirements.txt index 5b16bed4..0032a6fe 100644 --- a/samples/attestations/requirements.txt +++ b/samples/attestations/requirements.txt @@ -1,2 +1,2 @@ -cryptography==35.0.0 +cryptography==36.0.0 pem==21.2.0 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 25fbb41f..56a92969 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,3 +1,3 @@ google-cloud-kms==2.10.1 -cryptography==35.0.0 +cryptography==36.0.0 crcmod==1.7 From b790838c9a1cd735b2e4805fe0ea0d789aac061c Mon Sep 17 00:00:00 2001 From: Anurag Kumar Date: Wed, 8 Dec 2021 21:16:32 +0530 Subject: [PATCH 08/24] chore: add classifiers for python 3.9 and python 3.10 (#211) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit added support for python 3.9 and 3.10 Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly: - [x] Make sure to open an issue as a [bug/issue](https://github.com/googleapis/python-kms/issues/new/choose) before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea - [ ] Ensure the tests and linter pass - [ ] Code coverage does not decrease (if any source code was changed) - [ ] Appropriate docs were updated (if necessary) Fixes #212 🦕 --- setup.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/setup.py b/setup.py index 9850e726..cbd8ee6a 100644 --- a/setup.py +++ b/setup.py @@ -71,6 +71,8 @@ "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", "Operating System :: OS Independent", "Topic :: Internet", ], From fb0215df8fbf8665cab486dadee6e2304ab6546a Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Wed, 15 Dec 2021 12:11:57 +0100 Subject: [PATCH 09/24] chore(deps): update dependency cryptography to v36.0.1 (#216) --- samples/attestations/requirements.txt | 2 +- samples/snippets/requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/attestations/requirements.txt b/samples/attestations/requirements.txt index 0032a6fe..86e5361f 100644 --- a/samples/attestations/requirements.txt +++ b/samples/attestations/requirements.txt @@ -1,2 +1,2 @@ -cryptography==36.0.0 +cryptography==36.0.1 pem==21.2.0 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index 56a92969..e59bb1db 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1,3 +1,3 @@ google-cloud-kms==2.10.1 -cryptography==36.0.0 +cryptography==36.0.1 crcmod==1.7 From 9c16c36d069cabf53905eae8cff110a659f3a584 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 21 Dec 2021 16:45:56 -0500 Subject: [PATCH 10/24] chore: update python-docs-samples link to main branch (#213) Source-Link: https://github.com/googleapis/synthtool/commit/0941ef32b18aff0be34a40404f3971d9f51996e9 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:2f90537dd7df70f6b663cd654b1fa5dee483cf6a4edcfd46072b2775be8a23ec Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- .github/.OwlBot.lock.yaml | 2 +- samples/AUTHORING_GUIDE.md | 2 +- samples/CONTRIBUTING.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 7519fa3a..0b3c8cd9 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:0e18b9475fbeb12d9ad4302283171edebb6baf2dfca1bd215ee3b34ed79d95d7 + digest: sha256:2f90537dd7df70f6b663cd654b1fa5dee483cf6a4edcfd46072b2775be8a23ec diff --git a/samples/AUTHORING_GUIDE.md b/samples/AUTHORING_GUIDE.md index 55c97b32..8249522f 100644 --- a/samples/AUTHORING_GUIDE.md +++ b/samples/AUTHORING_GUIDE.md @@ -1 +1 @@ -See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/samples/CONTRIBUTING.md b/samples/CONTRIBUTING.md index 34c882b6..f5fe2e6b 100644 --- a/samples/CONTRIBUTING.md +++ b/samples/CONTRIBUTING.md @@ -1 +1 @@ -See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/main/CONTRIBUTING.md \ No newline at end of file From f2a172da2ec1db09b7cc9367c6c3ac3c068ad4a4 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 28 Dec 2021 13:18:12 -0500 Subject: [PATCH 11/24] chore: update .repo-metadata.json (#217) --- .repo-metadata.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.repo-metadata.json b/.repo-metadata.json index d3cbefa8..7f2c20f6 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -4,7 +4,7 @@ "product_documentation": "https://cloud.google.com/kms", "client_documentation": "https://cloud.google.com/python/docs/reference/cloudkms/latest", "issue_tracker": "https://issuetracker.google.com/savedsearches/5264932", - "release_level": "ga", + "release_level": "stable", "language": "python", "library_type": "GAPIC_AUTO", "repo": "googleapis/python-kms", @@ -24,5 +24,6 @@ } ], "default_version": "v1", - "codeowner_team": "" + "codeowner_team": "", + "api_shortname": "cloudkms" } From 27fb858f4dd02ea6fdd37f77ce4867488173d181 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 6 Jan 2022 17:14:26 +0000 Subject: [PATCH 12/24] chore: use python-samples-reviewers (#219) --- .github/.OwlBot.lock.yaml | 2 +- .github/CODEOWNERS | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 0b3c8cd9..f33299dd 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:2f90537dd7df70f6b663cd654b1fa5dee483cf6a4edcfd46072b2775be8a23ec + digest: sha256:899d5d7cc340fa8ef9d8ae1a8cfba362c6898584f779e156f25ee828ba824610 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 44cc8685..e446644f 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -8,5 +8,5 @@ # @googleapis/yoshi-python is the default owner for changes in this repo * @googleapis/yoshi-python -# @googleapis/python-samples-owners is the default owner for samples changes -/samples/ @googleapis/python-samples-owners +# @googleapis/python-samples-reviewers is the default owner for samples changes +/samples/ @googleapis/python-samples-reviewers From 60748581abcb3d8f7a9c4a790e822669dfd3091b Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 7 Jan 2022 19:39:34 -0500 Subject: [PATCH 13/24] chore: use gapic-generator-python 0.58.4 (#218) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: use gapic-generator-python 0.58.4 fix: provide appropriate mock values for message body fields committer: dovs PiperOrigin-RevId: 419025932 Source-Link: https://github.com/googleapis/googleapis/commit/73da6697f598f1ba30618924936a59f8e457ec89 Source-Link: https://github.com/googleapis/googleapis-gen/commit/46df624a54b9ed47c1a7eefb7a49413cf7b82f98 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDZkZjYyNGE1NGI5ZWQ0N2MxYTdlZWZiN2E0OTQxM2NmN2I4MmY5OCJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- .../key_management_service/transports/base.py | 1 - .../kms_v1/test_key_management_service.py | 276 +++++------------- 2 files changed, 81 insertions(+), 196 deletions(-) diff --git a/google/cloud/kms_v1/services/key_management_service/transports/base.py b/google/cloud/kms_v1/services/key_management_service/transports/base.py index 9d9d22d3..75aa9335 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/base.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/base.py @@ -105,7 +105,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id diff --git a/tests/unit/gapic/kms_v1/test_key_management_service.py b/tests/unit/gapic/kms_v1/test_key_management_service.py index 2019f42d..b926fb3c 100644 --- a/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -263,20 +263,20 @@ def test_key_management_service_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -345,7 +345,7 @@ def test_key_management_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -444,7 +444,7 @@ def test_key_management_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -479,7 +479,7 @@ def test_key_management_service_client_client_options_credentials_file( options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -512,9 +512,8 @@ def test_key_management_service_client_client_options_from_dict(): ) -def test_list_key_rings( - transport: str = "grpc", request_type=service.ListKeyRingsRequest -): +@pytest.mark.parametrize("request_type", [service.ListKeyRingsRequest, dict,]) +def test_list_key_rings(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -542,10 +541,6 @@ def test_list_key_rings( assert response.total_size == 1086 -def test_list_key_rings_from_dict(): - test_list_key_rings(request_type=dict) - - def test_list_key_rings_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -730,9 +725,9 @@ async def test_list_key_rings_flattened_error_async(): ) -def test_list_key_rings_pager(): +def test_list_key_rings_pager(transport_name: str = "grpc"): client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -770,9 +765,9 @@ def test_list_key_rings_pager(): assert all(isinstance(i, resources.KeyRing) for i in results) -def test_list_key_rings_pages(): +def test_list_key_rings_pages(transport_name: str = "grpc"): client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -876,9 +871,8 @@ async def test_list_key_rings_async_pages(): assert page_.raw_page.next_page_token == token -def test_list_crypto_keys( - transport: str = "grpc", request_type=service.ListCryptoKeysRequest -): +@pytest.mark.parametrize("request_type", [service.ListCryptoKeysRequest, dict,]) +def test_list_crypto_keys(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -906,10 +900,6 @@ def test_list_crypto_keys( assert response.total_size == 1086 -def test_list_crypto_keys_from_dict(): - test_list_crypto_keys(request_type=dict) - - def test_list_crypto_keys_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -1094,9 +1084,9 @@ async def test_list_crypto_keys_flattened_error_async(): ) -def test_list_crypto_keys_pager(): +def test_list_crypto_keys_pager(transport_name: str = "grpc"): client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1134,9 +1124,9 @@ def test_list_crypto_keys_pager(): assert all(isinstance(i, resources.CryptoKey) for i in results) -def test_list_crypto_keys_pages(): +def test_list_crypto_keys_pages(transport_name: str = "grpc"): client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1240,9 +1230,8 @@ async def test_list_crypto_keys_async_pages(): assert page_.raw_page.next_page_token == token -def test_list_crypto_key_versions( - transport: str = "grpc", request_type=service.ListCryptoKeyVersionsRequest -): +@pytest.mark.parametrize("request_type", [service.ListCryptoKeyVersionsRequest, dict,]) +def test_list_crypto_key_versions(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1272,10 +1261,6 @@ def test_list_crypto_key_versions( assert response.total_size == 1086 -def test_list_crypto_key_versions_from_dict(): - test_list_crypto_key_versions(request_type=dict) - - def test_list_crypto_key_versions_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -1472,9 +1457,9 @@ async def test_list_crypto_key_versions_flattened_error_async(): ) -def test_list_crypto_key_versions_pager(): +def test_list_crypto_key_versions_pager(transport_name: str = "grpc"): client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1520,9 +1505,9 @@ def test_list_crypto_key_versions_pager(): assert all(isinstance(i, resources.CryptoKeyVersion) for i in results) -def test_list_crypto_key_versions_pages(): +def test_list_crypto_key_versions_pages(transport_name: str = "grpc"): client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1650,9 +1635,8 @@ async def test_list_crypto_key_versions_async_pages(): assert page_.raw_page.next_page_token == token -def test_list_import_jobs( - transport: str = "grpc", request_type=service.ListImportJobsRequest -): +@pytest.mark.parametrize("request_type", [service.ListImportJobsRequest, dict,]) +def test_list_import_jobs(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1680,10 +1664,6 @@ def test_list_import_jobs( assert response.total_size == 1086 -def test_list_import_jobs_from_dict(): - test_list_import_jobs(request_type=dict) - - def test_list_import_jobs_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -1868,9 +1848,9 @@ async def test_list_import_jobs_flattened_error_async(): ) -def test_list_import_jobs_pager(): +def test_list_import_jobs_pager(transport_name: str = "grpc"): client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1908,9 +1888,9 @@ def test_list_import_jobs_pager(): assert all(isinstance(i, resources.ImportJob) for i in results) -def test_list_import_jobs_pages(): +def test_list_import_jobs_pages(transport_name: str = "grpc"): client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2014,7 +1994,8 @@ async def test_list_import_jobs_async_pages(): assert page_.raw_page.next_page_token == token -def test_get_key_ring(transport: str = "grpc", request_type=service.GetKeyRingRequest): +@pytest.mark.parametrize("request_type", [service.GetKeyRingRequest, dict,]) +def test_get_key_ring(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -2039,10 +2020,6 @@ def test_get_key_ring(transport: str = "grpc", request_type=service.GetKeyRingRe assert response.name == "name_value" -def test_get_key_ring_from_dict(): - test_get_key_ring(request_type=dict) - - def test_get_key_ring_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -2220,9 +2197,8 @@ async def test_get_key_ring_flattened_error_async(): ) -def test_get_crypto_key( - transport: str = "grpc", request_type=service.GetCryptoKeyRequest -): +@pytest.mark.parametrize("request_type", [service.GetCryptoKeyRequest, dict,]) +def test_get_crypto_key(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -2254,10 +2230,6 @@ def test_get_crypto_key( assert response.import_only is True -def test_get_crypto_key_from_dict(): - test_get_crypto_key(request_type=dict) - - def test_get_crypto_key_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -2441,9 +2413,8 @@ async def test_get_crypto_key_flattened_error_async(): ) -def test_get_crypto_key_version( - transport: str = "grpc", request_type=service.GetCryptoKeyVersionRequest -): +@pytest.mark.parametrize("request_type", [service.GetCryptoKeyVersionRequest, dict,]) +def test_get_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -2490,10 +2461,6 @@ def test_get_crypto_key_version( assert response.reimport_eligible is True -def test_get_crypto_key_version_from_dict(): - test_get_crypto_key_version(request_type=dict) - - def test_get_crypto_key_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -2707,9 +2674,8 @@ async def test_get_crypto_key_version_flattened_error_async(): ) -def test_get_public_key( - transport: str = "grpc", request_type=service.GetPublicKeyRequest -): +@pytest.mark.parametrize("request_type", [service.GetPublicKeyRequest, dict,]) +def test_get_public_key(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -2745,10 +2711,6 @@ def test_get_public_key( assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_get_public_key_from_dict(): - test_get_public_key(request_type=dict) - - def test_get_public_key_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -2937,9 +2899,8 @@ async def test_get_public_key_flattened_error_async(): ) -def test_get_import_job( - transport: str = "grpc", request_type=service.GetImportJobRequest -): +@pytest.mark.parametrize("request_type", [service.GetImportJobRequest, dict,]) +def test_get_import_job(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -2975,10 +2936,6 @@ def test_get_import_job( assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION -def test_get_import_job_from_dict(): - test_get_import_job(request_type=dict) - - def test_get_import_job_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -3167,9 +3124,8 @@ async def test_get_import_job_flattened_error_async(): ) -def test_create_key_ring( - transport: str = "grpc", request_type=service.CreateKeyRingRequest -): +@pytest.mark.parametrize("request_type", [service.CreateKeyRingRequest, dict,]) +def test_create_key_ring(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -3194,10 +3150,6 @@ def test_create_key_ring( assert response.name == "name_value" -def test_create_key_ring_from_dict(): - test_create_key_ring(request_type=dict) - - def test_create_key_ring_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -3401,9 +3353,8 @@ async def test_create_key_ring_flattened_error_async(): ) -def test_create_crypto_key( - transport: str = "grpc", request_type=service.CreateCryptoKeyRequest -): +@pytest.mark.parametrize("request_type", [service.CreateCryptoKeyRequest, dict,]) +def test_create_crypto_key(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -3437,10 +3388,6 @@ def test_create_crypto_key( assert response.import_only is True -def test_create_crypto_key_from_dict(): - test_create_crypto_key(request_type=dict) - - def test_create_crypto_key_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -3662,9 +3609,8 @@ async def test_create_crypto_key_flattened_error_async(): ) -def test_create_crypto_key_version( - transport: str = "grpc", request_type=service.CreateCryptoKeyVersionRequest -): +@pytest.mark.parametrize("request_type", [service.CreateCryptoKeyVersionRequest, dict,]) +def test_create_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -3711,10 +3657,6 @@ def test_create_crypto_key_version( assert response.reimport_eligible is True -def test_create_crypto_key_version_from_dict(): - test_create_crypto_key_version(request_type=dict) - - def test_create_crypto_key_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -3944,9 +3886,8 @@ async def test_create_crypto_key_version_flattened_error_async(): ) -def test_import_crypto_key_version( - transport: str = "grpc", request_type=service.ImportCryptoKeyVersionRequest -): +@pytest.mark.parametrize("request_type", [service.ImportCryptoKeyVersionRequest, dict,]) +def test_import_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -3993,10 +3934,6 @@ def test_import_crypto_key_version( assert response.reimport_eligible is True -def test_import_crypto_key_version_from_dict(): - test_import_crypto_key_version(request_type=dict) - - def test_import_crypto_key_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -4130,9 +4067,8 @@ async def test_import_crypto_key_version_field_headers_async(): assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] -def test_create_import_job( - transport: str = "grpc", request_type=service.CreateImportJobRequest -): +@pytest.mark.parametrize("request_type", [service.CreateImportJobRequest, dict,]) +def test_create_import_job(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -4170,10 +4106,6 @@ def test_create_import_job( assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION -def test_create_import_job_from_dict(): - test_create_import_job(request_type=dict) - - def test_create_import_job_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -4400,9 +4332,8 @@ async def test_create_import_job_flattened_error_async(): ) -def test_update_crypto_key( - transport: str = "grpc", request_type=service.UpdateCryptoKeyRequest -): +@pytest.mark.parametrize("request_type", [service.UpdateCryptoKeyRequest, dict,]) +def test_update_crypto_key(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -4436,10 +4367,6 @@ def test_update_crypto_key( assert response.import_only is True -def test_update_crypto_key_from_dict(): - test_update_crypto_key(request_type=dict) - - def test_update_crypto_key_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -4655,9 +4582,8 @@ async def test_update_crypto_key_flattened_error_async(): ) -def test_update_crypto_key_version( - transport: str = "grpc", request_type=service.UpdateCryptoKeyVersionRequest -): +@pytest.mark.parametrize("request_type", [service.UpdateCryptoKeyVersionRequest, dict,]) +def test_update_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -4704,10 +4630,6 @@ def test_update_crypto_key_version( assert response.reimport_eligible is True -def test_update_crypto_key_version_from_dict(): - test_update_crypto_key_version(request_type=dict) - - def test_update_crypto_key_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -4943,9 +4865,10 @@ async def test_update_crypto_key_version_flattened_error_async(): ) -def test_update_crypto_key_primary_version( - transport: str = "grpc", request_type=service.UpdateCryptoKeyPrimaryVersionRequest -): +@pytest.mark.parametrize( + "request_type", [service.UpdateCryptoKeyPrimaryVersionRequest, dict,] +) +def test_update_crypto_key_primary_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -4979,10 +4902,6 @@ def test_update_crypto_key_primary_version( assert response.import_only is True -def test_update_crypto_key_primary_version_from_dict(): - test_update_crypto_key_primary_version(request_type=dict) - - def test_update_crypto_key_primary_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -5193,9 +5112,10 @@ async def test_update_crypto_key_primary_version_flattened_error_async(): ) -def test_destroy_crypto_key_version( - transport: str = "grpc", request_type=service.DestroyCryptoKeyVersionRequest -): +@pytest.mark.parametrize( + "request_type", [service.DestroyCryptoKeyVersionRequest, dict,] +) +def test_destroy_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -5242,10 +5162,6 @@ def test_destroy_crypto_key_version( assert response.reimport_eligible is True -def test_destroy_crypto_key_version_from_dict(): - test_destroy_crypto_key_version(request_type=dict) - - def test_destroy_crypto_key_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -5459,9 +5375,10 @@ async def test_destroy_crypto_key_version_flattened_error_async(): ) -def test_restore_crypto_key_version( - transport: str = "grpc", request_type=service.RestoreCryptoKeyVersionRequest -): +@pytest.mark.parametrize( + "request_type", [service.RestoreCryptoKeyVersionRequest, dict,] +) +def test_restore_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -5508,10 +5425,6 @@ def test_restore_crypto_key_version( assert response.reimport_eligible is True -def test_restore_crypto_key_version_from_dict(): - test_restore_crypto_key_version(request_type=dict) - - def test_restore_crypto_key_version_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -5725,7 +5638,8 @@ async def test_restore_crypto_key_version_flattened_error_async(): ) -def test_encrypt(transport: str = "grpc", request_type=service.EncryptRequest): +@pytest.mark.parametrize("request_type", [service.EncryptRequest, dict,]) +def test_encrypt(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -5760,10 +5674,6 @@ def test_encrypt(transport: str = "grpc", request_type=service.EncryptRequest): assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_encrypt_from_dict(): - test_encrypt(request_type=dict) - - def test_encrypt_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -5963,7 +5873,8 @@ async def test_encrypt_flattened_error_async(): ) -def test_decrypt(transport: str = "grpc", request_type=service.DecryptRequest): +@pytest.mark.parametrize("request_type", [service.DecryptRequest, dict,]) +def test_decrypt(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -5994,10 +5905,6 @@ def test_decrypt(transport: str = "grpc", request_type=service.DecryptRequest): assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_decrypt_from_dict(): - test_decrypt(request_type=dict) - - def test_decrypt_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -6195,9 +6102,8 @@ async def test_decrypt_flattened_error_async(): ) -def test_asymmetric_sign( - transport: str = "grpc", request_type=service.AsymmetricSignRequest -): +@pytest.mark.parametrize("request_type", [service.AsymmetricSignRequest, dict,]) +def test_asymmetric_sign(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -6232,10 +6138,6 @@ def test_asymmetric_sign( assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_asymmetric_sign_from_dict(): - test_asymmetric_sign(request_type=dict) - - def test_asymmetric_sign_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -6441,9 +6343,8 @@ async def test_asymmetric_sign_flattened_error_async(): ) -def test_asymmetric_decrypt( - transport: str = "grpc", request_type=service.AsymmetricDecryptRequest -): +@pytest.mark.parametrize("request_type", [service.AsymmetricDecryptRequest, dict,]) +def test_asymmetric_decrypt(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -6476,10 +6377,6 @@ def test_asymmetric_decrypt( assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_asymmetric_decrypt_from_dict(): - test_asymmetric_decrypt(request_type=dict) - - def test_asymmetric_decrypt_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -6693,7 +6590,8 @@ async def test_asymmetric_decrypt_flattened_error_async(): ) -def test_mac_sign(transport: str = "grpc", request_type=service.MacSignRequest): +@pytest.mark.parametrize("request_type", [service.MacSignRequest, dict,]) +def test_mac_sign(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -6726,10 +6624,6 @@ def test_mac_sign(transport: str = "grpc", request_type=service.MacSignRequest): assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_mac_sign_from_dict(): - test_mac_sign(request_type=dict) - - def test_mac_sign_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -6927,7 +6821,8 @@ async def test_mac_sign_flattened_error_async(): ) -def test_mac_verify(transport: str = "grpc", request_type=service.MacVerifyRequest): +@pytest.mark.parametrize("request_type", [service.MacVerifyRequest, dict,]) +def test_mac_verify(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -6964,10 +6859,6 @@ def test_mac_verify(transport: str = "grpc", request_type=service.MacVerifyReque assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_mac_verify_from_dict(): - test_mac_verify(request_type=dict) - - def test_mac_verify_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -7183,9 +7074,8 @@ async def test_mac_verify_flattened_error_async(): ) -def test_generate_random_bytes( - transport: str = "grpc", request_type=service.GenerateRandomBytesRequest -): +@pytest.mark.parametrize("request_type", [service.GenerateRandomBytesRequest, dict,]) +def test_generate_random_bytes(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -7212,10 +7102,6 @@ def test_generate_random_bytes( assert response.data == b"data_blob" -def test_generate_random_bytes_from_dict(): - test_generate_random_bytes(request_type=dict) - - def test_generate_random_bytes_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -8117,7 +8003,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( From 28c69e37ecf8a15796416628b5efaa2fb78fdb00 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 11 Jan 2022 07:43:31 -0500 Subject: [PATCH 14/24] chore(samples): Add check for tests in directory (#221) Source-Link: https://github.com/googleapis/synthtool/commit/52aef91f8d25223d9dbdb4aebd94ba8eea2101f3 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:36a95b8f494e4674dc9eee9af98961293b51b86b3649942aac800ae6c1f796d4 Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- samples/attestations/noxfile.py | 70 ++++++++++++++++++--------------- samples/snippets/noxfile.py | 70 ++++++++++++++++++--------------- 3 files changed, 79 insertions(+), 63 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index f33299dd..6b8a73b3 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:899d5d7cc340fa8ef9d8ae1a8cfba362c6898584f779e156f25ee828ba824610 + digest: sha256:36a95b8f494e4674dc9eee9af98961293b51b86b3649942aac800ae6c1f796d4 diff --git a/samples/attestations/noxfile.py b/samples/attestations/noxfile.py index 93a9122c..3bbef5d5 100644 --- a/samples/attestations/noxfile.py +++ b/samples/attestations/noxfile.py @@ -14,6 +14,7 @@ from __future__ import print_function +import glob import os from pathlib import Path import sys @@ -184,37 +185,44 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests( session: nox.sessions.Session, post_install: Callable = None ) -> None: - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") - else: - session.install("-r", "requirements-test.txt") - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + # check for presence of tests + test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + if len(test_list) == 0: + print("No tests found, skipping directory.") + else: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") + """Runs py.test for a particular project.""" + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + + if os.path.exists("requirements-test.txt"): + if os.path.exists("constraints-test.txt"): + session.install( + "-r", "requirements-test.txt", "-c", "constraints-test.txt" + ) + else: + session.install("-r", "requirements-test.txt") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 93a9122c..3bbef5d5 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -14,6 +14,7 @@ from __future__ import print_function +import glob import os from pathlib import Path import sys @@ -184,37 +185,44 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests( session: nox.sessions.Session, post_install: Callable = None ) -> None: - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") - else: - session.install("-r", "requirements-test.txt") - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) + # check for presence of tests + test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + if len(test_list) == 0: + print("No tests found, skipping directory.") + else: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") + """Runs py.test for a particular project.""" + if os.path.exists("requirements.txt"): + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") + + if os.path.exists("requirements-test.txt"): + if os.path.exists("constraints-test.txt"): + session.install( + "-r", "requirements-test.txt", "-c", "constraints-test.txt" + ) + else: + session.install("-r", "requirements-test.txt") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars(), + ) @nox.session(python=ALL_VERSIONS) From e67bab1b14f54ae5fa2200417b60920f6b7e2654 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 14 Jan 2022 16:23:23 -0500 Subject: [PATCH 15/24] build: switch to release-please for tagging (#222) Source-Link: https://github.com/googleapis/synthtool/commit/f8077d237e0df2cb0066dfc6e09fc41e1c59646a Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:dfa9b663b32de8b5b327e32c1da665a80de48876558dd58091d8160c60ad7355 Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- .github/release-please.yml | 1 + .github/release-trigger.yml | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 .github/release-trigger.yml diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 6b8a73b3..ff5126c1 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:36a95b8f494e4674dc9eee9af98961293b51b86b3649942aac800ae6c1f796d4 + digest: sha256:dfa9b663b32de8b5b327e32c1da665a80de48876558dd58091d8160c60ad7355 diff --git a/.github/release-please.yml b/.github/release-please.yml index 4507ad05..466597e5 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1 +1,2 @@ releaseType: python +handleGHRelease: true diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml new file mode 100644 index 00000000..d4ca9418 --- /dev/null +++ b/.github/release-trigger.yml @@ -0,0 +1 @@ +enabled: true From 7fbcc3da984facbd45aae43d52c270ab9adb5658 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sun, 16 Jan 2022 10:27:06 -0500 Subject: [PATCH 16/24] chore(python): update release.sh to use keystore (#223) Source-Link: https://github.com/googleapis/synthtool/commit/69fda12e2994f0b595a397e8bb6e3e9f380524eb Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:ae600f36b6bc972b368367b6f83a1d91ec2c82a4a116b383d67d547c56fe6de3 Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/release.sh | 2 +- .kokoro/release/common.cfg | 12 +++++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index ff5126c1..eecb84c2 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:dfa9b663b32de8b5b327e32c1da665a80de48876558dd58091d8160c60ad7355 + digest: sha256:ae600f36b6bc972b368367b6f83a1d91ec2c82a4a116b383d67d547c56fe6de3 diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 478f9fc9..00e882f3 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools export PYTHONUNBUFFERED=1 # Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token") +TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google-cloud-pypi-token-keystore-1") cd github/python-kms python3 setup.py sdist bdist_wheel twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index 47754c53..f5912293 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,8 +23,18 @@ env_vars: { value: "github/python-kms/.kokoro/release.sh" } +# Fetch PyPI password +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google-cloud-pypi-token-keystore-1" + } + } +} + # Tokens needed to report release status back to GitHub env_vars: { key: "SECRET_MANAGER_KEYS" - value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" } From d42716a39ca5f2b36a9b7fa18718613e25c021c1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 18 Jan 2022 20:27:24 -0500 Subject: [PATCH 17/24] chore(python): Noxfile recognizes that tests can live in a folder (#225) Source-Link: https://github.com/googleapis/synthtool/commit/4760d8dce1351d93658cb11d02a1b7ceb23ae5d7 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:f0e4b51deef56bed74d3e2359c583fc104a8d6367da3984fc5c66938db738828 Co-authored-by: Owl Bot --- .github/.OwlBot.lock.yaml | 2 +- samples/attestations/noxfile.py | 1 + samples/snippets/noxfile.py | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index eecb84c2..52d79c11 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:ae600f36b6bc972b368367b6f83a1d91ec2c82a4a116b383d67d547c56fe6de3 + digest: sha256:f0e4b51deef56bed74d3e2359c583fc104a8d6367da3984fc5c66938db738828 diff --git a/samples/attestations/noxfile.py b/samples/attestations/noxfile.py index 3bbef5d5..20cdfc62 100644 --- a/samples/attestations/noxfile.py +++ b/samples/attestations/noxfile.py @@ -187,6 +187,7 @@ def _session_tests( ) -> None: # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + test_list.extend(glob.glob("tests")) if len(test_list) == 0: print("No tests found, skipping directory.") else: diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 3bbef5d5..20cdfc62 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -187,6 +187,7 @@ def _session_tests( ) -> None: # check for presence of tests test_list = glob.glob("*_test.py") + glob.glob("test_*.py") + test_list.extend(glob.glob("tests")) if len(test_list) == 0: print("No tests found, skipping directory.") else: From 4442c5bd6a90a81dafdf770d2c7045709418cae8 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 20 Jan 2022 10:15:29 -0500 Subject: [PATCH 18/24] ci(python): run lint / unit tests / docs as GH actions (#226) * ci(python): run lint / unit tests / docs as GH actions Source-Link: https://github.com/googleapis/synthtool/commit/57be0cdb0b94e1669cee0ca38d790de1dfdbcd44 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:ed1f9983d5a935a89fe8085e8bb97d94e41015252c5b6c9771257cf8624367e6 * add a commit to activate gh actions Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- .github/.OwlBot.lock.yaml | 16 +++++++++- .github/workflows/docs.yml | 38 +++++++++++++++++++++++ .github/workflows/lint.yml | 25 +++++++++++++++ .github/workflows/unittest.yml | 57 ++++++++++++++++++++++++++++++++++ 4 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/docs.yml create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/unittest.yml diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 52d79c11..b668c04d 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,17 @@ +# 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. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:f0e4b51deef56bed74d3e2359c583fc104a8d6367da3984fc5c66938db738828 + digest: sha256:ed1f9983d5a935a89fe8085e8bb97d94e41015252c5b6c9771257cf8624367e6 + diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..f7b8344c --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,38 @@ +on: + pull_request: + branches: + - main +name: docs +jobs: + docs: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run docs + run: | + nox -s docs + docfx: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run docfx + run: | + nox -s docfx diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..1e8b05c3 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,25 @@ +on: + pull_request: + branches: + - main +name: lint +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run lint + run: | + nox -s lint + - name: Run lint_setup_py + run: | + nox -s lint_setup_py diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml new file mode 100644 index 00000000..074ee250 --- /dev/null +++ b/.github/workflows/unittest.yml @@ -0,0 +1,57 @@ +on: + pull_request: + branches: + - main +name: unittest +jobs: + unit: + runs-on: ubuntu-latest + strategy: + matrix: + python: ['3.6', '3.7', '3.8', '3.9', '3.10'] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run unit tests + env: + COVERAGE_FILE: .coverage-${{ matrix.python }} + run: | + nox -s unit-${{ matrix.python }} + - name: Upload coverage results + uses: actions/upload-artifact@v2 + with: + name: coverage-artifacts + path: .coverage-${{ matrix.python }} + + cover: + runs-on: ubuntu-latest + needs: + - unit + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install coverage + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install coverage + - name: Download coverage results + uses: actions/download-artifact@v2 + with: + name: coverage-artifacts + path: .coverage-results/ + - name: Report coverage results + run: | + coverage combine .coverage-results/.coverage* + coverage report --show-missing --fail-under=100 From 3817d7390fddebd137c99865455f0ae145dbcf63 Mon Sep 17 00:00:00 2001 From: pedroysb Date: Fri, 21 Jan 2022 14:26:52 +0100 Subject: [PATCH 19/24] docs(samples): fix typo in verify_asymmetric_ec.py (#227) Co-authored-by: Anthonios Partheniou --- samples/snippets/verify_asymmetric_ec.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/snippets/verify_asymmetric_ec.py b/samples/snippets/verify_asymmetric_ec.py index d29128bd..376f7507 100644 --- a/samples/snippets/verify_asymmetric_ec.py +++ b/samples/snippets/verify_asymmetric_ec.py @@ -55,7 +55,7 @@ def verify_asymmetric_ec(project_id, location_id, key_ring_id, key_id, version_i # Get the public key. public_key = client.get_public_key(request={'name': key_version_name}) - # Extract and parse the public key as a PEM-encoded RSA key. + # Extract and parse the public key as a PEM-encoded EC key. pem = public_key.pem.encode('utf-8') ec_key = serialization.load_pem_public_key(pem, default_backend()) hash_ = hashlib.sha256(message_bytes).digest() From 6ab29927a0a2bd0b484aa335ccd4941cf4c6ccec Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Mon, 24 Jan 2022 13:15:06 -0700 Subject: [PATCH 20/24] chore: make samples 3.6 check optional (#229) --- .github/sync-repo-settings.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml index 3e98ae70..37438d33 100644 --- a/.github/sync-repo-settings.yaml +++ b/.github/sync-repo-settings.yaml @@ -10,6 +10,5 @@ branchProtectionRules: - 'Kokoro' - 'cla/google' - 'Samples - Lint' - - 'Samples - Python 3.6' - 'Samples - Python 3.7' - 'Samples - Python 3.8' From fdf62ae3b3209a1215e0f2f2440add1f01d40907 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 25 Jan 2022 10:06:43 -0500 Subject: [PATCH 21/24] feat: add api key support (#230) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: upgrade gapic-generator-java, gax-java and gapic-generator-python PiperOrigin-RevId: 423842556 Source-Link: https://github.com/googleapis/googleapis/commit/a616ca08f4b1416abbac7bc5dd6d61c791756a81 Source-Link: https://github.com/googleapis/googleapis-gen/commit/29b938c58c1e51d019f2ee539d55dc0a3c86a905 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMjliOTM4YzU4YzFlNTFkMDE5ZjJlZTUzOWQ1NWRjMGEzYzg2YTkwNSJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- .../key_management_service/async_client.py | 39 ++++- .../services/key_management_service/client.py | 128 +++++++++++------ .../kms_v1/test_key_management_service.py | 133 ++++++++++++++++++ 3 files changed, 256 insertions(+), 44 deletions(-) diff --git a/google/cloud/kms_v1/services/key_management_service/async_client.py b/google/cloud/kms_v1/services/key_management_service/async_client.py index e549e6ef..92b44094 100644 --- a/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -16,7 +16,7 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core.client_options import ClientOptions @@ -145,6 +145,43 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return KeyManagementServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> KeyManagementServiceTransport: """Returns the transport used by the client instance. diff --git a/google/cloud/kms_v1/services/key_management_service/client.py b/google/cloud/kms_v1/services/key_management_service/client.py index d0837727..3af40f42 100644 --- a/google/cloud/kms_v1/services/key_management_service/client.py +++ b/google/cloud/kms_v1/services/key_management_service/client.py @@ -353,6 +353,74 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -404,57 +472,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - if os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") not in ( - "true", - "false", - ): - raise ValueError( - "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - ) - use_client_cert = ( - os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true" + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, KeyManagementServiceTransport): # transport is a KeyManagementServiceTransport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -466,6 +499,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, diff --git a/tests/unit/gapic/kms_v1/test_key_management_service.py b/tests/unit/gapic/kms_v1/test_key_management_service.py index b926fb3c..68c2de4e 100644 --- a/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -422,6 +422,87 @@ def test_key_management_service_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", [KeyManagementServiceClient, KeyManagementServiceAsyncClient] +) +@mock.patch.object( + KeyManagementServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(KeyManagementServiceClient), +) +@mock.patch.object( + KeyManagementServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(KeyManagementServiceAsyncClient), +) +def test_key_management_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -7341,6 +7422,25 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + 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 = KeyManagementServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.KeyManagementServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -8543,3 +8643,36 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport), + ( + KeyManagementServiceAsyncClient, + transports.KeyManagementServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) From 97f7ea50a30d1dc1133d7703e6bd90ad209f75a1 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 3 Feb 2022 10:20:44 +0000 Subject: [PATCH 22/24] chore: use gapic-generator-python 0.62.1 (#232) - [ ] Regenerate this pull request now. fix: resolve DuplicateCredentialArgs error when using credentials_file committer: parthea PiperOrigin-RevId: 425964861 Source-Link: https://github.com/googleapis/googleapis/commit/84b1a5a4f6fb2d04905be58e586b8a7a4310a8cf Source-Link: https://github.com/googleapis/googleapis-gen/commit/4fb761bbd8506ac156f49bac5f18306aa8eb3aa8 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNGZiNzYxYmJkODUwNmFjMTU2ZjQ5YmFjNWYxODMwNmFhOGViM2FhOCJ9 --- .../key_management_service/async_client.py | 54 ++++++------- .../services/key_management_service/client.py | 54 ++++++------- .../key_management_service/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 5 +- .../kms_v1/test_key_management_service.py | 76 ++++++++++++++++++- 5 files changed, 136 insertions(+), 58 deletions(-) diff --git a/google/cloud/kms_v1/services/key_management_service/async_client.py b/google/cloud/kms_v1/services/key_management_service/async_client.py index 92b44094..f0d0543a 100644 --- a/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -284,7 +284,7 @@ async def list_key_rings( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -376,7 +376,7 @@ async def list_crypto_keys( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -469,7 +469,7 @@ async def list_crypto_key_versions( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -561,7 +561,7 @@ async def list_import_jobs( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -651,7 +651,7 @@ async def get_key_ring( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -743,7 +743,7 @@ async def get_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -839,7 +839,7 @@ async def get_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -929,7 +929,7 @@ async def get_public_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1056,7 +1056,7 @@ async def get_import_job( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1157,7 +1157,7 @@ async def create_key_ring( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, key_ring_id, key_ring]) if request is not None and has_flattened_params: @@ -1271,7 +1271,7 @@ async def create_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, crypto_key_id, crypto_key]) if request is not None and has_flattened_params: @@ -1386,7 +1386,7 @@ async def create_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, crypto_key_version]) if request is not None and has_flattened_params: @@ -1594,7 +1594,7 @@ async def create_import_job( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, import_job_id, import_job]) if request is not None and has_flattened_params: @@ -1694,7 +1694,7 @@ async def update_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([crypto_key, update_mask]) if request is not None and has_flattened_params: @@ -1813,7 +1813,7 @@ async def update_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([crypto_key_version, update_mask]) if request is not None and has_flattened_params: @@ -1919,7 +1919,7 @@ async def update_crypto_key_primary_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, crypto_key_version_id]) if request is not None and has_flattened_params: @@ -2037,7 +2037,7 @@ async def destroy_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -2142,7 +2142,7 @@ async def restore_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -2252,7 +2252,7 @@ async def encrypt( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, plaintext]) if request is not None and has_flattened_params: @@ -2350,7 +2350,7 @@ async def decrypt( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, ciphertext]) if request is not None and has_flattened_params: @@ -2450,7 +2450,7 @@ async def asymmetric_sign( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, digest]) if request is not None and has_flattened_params: @@ -2550,7 +2550,7 @@ async def asymmetric_decrypt( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, ciphertext]) if request is not None and has_flattened_params: @@ -2648,7 +2648,7 @@ async def mac_sign( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, data]) if request is not None and has_flattened_params: @@ -2752,7 +2752,7 @@ async def mac_verify( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, data, mac]) if request is not None and has_flattened_params: @@ -2824,8 +2824,8 @@ async def generate_random_bytes( location (:class:`str`): The project-specific location in which to generate random bytes. For - example, "projects/my- - project/locations/us-central1". + example, + "projects/my-project/locations/us-central1". This corresponds to the ``location`` field on the ``request`` instance; if ``request`` is provided, this @@ -2860,7 +2860,7 @@ async def generate_random_bytes( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([location, length_bytes, protection_level]) if request is not None and has_flattened_params: diff --git a/google/cloud/kms_v1/services/key_management_service/client.py b/google/cloud/kms_v1/services/key_management_service/client.py index 3af40f42..0966aa0c 100644 --- a/google/cloud/kms_v1/services/key_management_service/client.py +++ b/google/cloud/kms_v1/services/key_management_service/client.py @@ -560,7 +560,7 @@ def list_key_rings( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -642,7 +642,7 @@ def list_crypto_keys( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -725,7 +725,7 @@ def list_crypto_key_versions( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -807,7 +807,7 @@ def list_import_jobs( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -887,7 +887,7 @@ def get_key_ring( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -969,7 +969,7 @@ def get_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1055,7 +1055,7 @@ def get_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1135,7 +1135,7 @@ def get_public_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1252,7 +1252,7 @@ def get_import_job( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1343,7 +1343,7 @@ def create_key_ring( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, key_ring_id, key_ring]) if request is not None and has_flattened_params: @@ -1447,7 +1447,7 @@ def create_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, crypto_key_id, crypto_key]) if request is not None and has_flattened_params: @@ -1552,7 +1552,7 @@ def create_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, crypto_key_version]) if request is not None and has_flattened_params: @@ -1765,7 +1765,7 @@ def create_import_job( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, import_job_id, import_job]) if request is not None and has_flattened_params: @@ -1855,7 +1855,7 @@ def update_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([crypto_key, update_mask]) if request is not None and has_flattened_params: @@ -1964,7 +1964,7 @@ def update_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([crypto_key_version, update_mask]) if request is not None and has_flattened_params: @@ -2062,7 +2062,7 @@ def update_crypto_key_primary_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, crypto_key_version_id]) if request is not None and has_flattened_params: @@ -2172,7 +2172,7 @@ def destroy_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -2269,7 +2269,7 @@ def restore_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -2371,7 +2371,7 @@ def encrypt( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, plaintext]) if request is not None and has_flattened_params: @@ -2459,7 +2459,7 @@ def decrypt( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, ciphertext]) if request is not None and has_flattened_params: @@ -2549,7 +2549,7 @@ def asymmetric_sign( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, digest]) if request is not None and has_flattened_params: @@ -2639,7 +2639,7 @@ def asymmetric_decrypt( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, ciphertext]) if request is not None and has_flattened_params: @@ -2727,7 +2727,7 @@ def mac_sign( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, data]) if request is not None and has_flattened_params: @@ -2821,7 +2821,7 @@ def mac_verify( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, data, mac]) if request is not None and has_flattened_params: @@ -2883,8 +2883,8 @@ def generate_random_bytes( location (str): The project-specific location in which to generate random bytes. For - example, "projects/my- - project/locations/us-central1". + example, + "projects/my-project/locations/us-central1". This corresponds to the ``location`` field on the ``request`` instance; if ``request`` is provided, this @@ -2919,7 +2919,7 @@ def generate_random_bytes( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([location, length_bytes, protection_level]) if request is not None and has_flattened_params: diff --git a/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/google/cloud/kms_v1/services/key_management_service/transports/grpc.py index 0fabb11e..742ac3cf 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -172,8 +172,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py index ccce24a4..659578be 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -217,8 +217,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/tests/unit/gapic/kms_v1/test_key_management_service.py b/tests/unit/gapic/kms_v1/test_key_management_service.py index 68c2de4e..8e44d7a5 100644 --- a/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -539,25 +539,28 @@ def test_key_management_service_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ ( KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", + grpc_helpers, ), ( KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_key_management_service_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) @@ -593,6 +596,75 @@ def test_key_management_service_client_client_options_from_dict(): ) +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + KeyManagementServiceClient, + transports.KeyManagementServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + KeyManagementServiceAsyncClient, + transports.KeyManagementServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_key_management_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize("request_type", [service.ListKeyRingsRequest, dict,]) def test_list_key_rings(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( From eb532f5c84907c12356e549c694c0210e5ad585b Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 3 Feb 2022 05:23:00 -0500 Subject: [PATCH 23/24] feat: add a new EkmService API (#233) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add a new EkmService API PiperOrigin-RevId: 425982419 Source-Link: https://github.com/googleapis/googleapis/commit/8dff5691cc4d4a0c61af8cdef85b6460ae560f0d Source-Link: https://github.com/googleapis/googleapis-gen/commit/b1538df1643922606d00ec0365c1e0a51bfbcabf Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjE1MzhkZjE2NDM5MjI2MDZkMDBlYzAzNjVjMWUwYTUxYmZiY2FiZiJ9 * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- docs/kms_v1/ekm_service.rst | 10 + docs/kms_v1/services.rst | 1 + google/cloud/kms/__init__.py | 18 + google/cloud/kms_v1/__init__.py | 18 + google/cloud/kms_v1/gapic_metadata.json | 54 + .../kms_v1/services/ekm_service/__init__.py | 22 + .../services/ekm_service/async_client.py | 920 ++++++ .../kms_v1/services/ekm_service/client.py | 1104 +++++++ .../kms_v1/services/ekm_service/pagers.py | 155 + .../ekm_service/transports/__init__.py | 33 + .../services/ekm_service/transports/base.py | 267 ++ .../services/ekm_service/transports/grpc.py | 431 +++ .../ekm_service/transports/grpc_asyncio.py | 440 +++ .../key_management_service/async_client.py | 97 +- .../services/key_management_service/client.py | 97 +- google/cloud/kms_v1/types/__init__.py | 16 + google/cloud/kms_v1/types/ekm_service.py | 287 ++ google/cloud/kms_v1/types/resources.py | 58 +- google/cloud/kms_v1/types/service.py | 21 +- scripts/fixup_kms_v1_keywords.py | 4 + tests/unit/gapic/kms_v1/test_ekm_service.py | 2794 +++++++++++++++++ .../kms_v1/test_key_management_service.py | 16 + 22 files changed, 6769 insertions(+), 94 deletions(-) create mode 100644 docs/kms_v1/ekm_service.rst create mode 100644 google/cloud/kms_v1/services/ekm_service/__init__.py create mode 100644 google/cloud/kms_v1/services/ekm_service/async_client.py create mode 100644 google/cloud/kms_v1/services/ekm_service/client.py create mode 100644 google/cloud/kms_v1/services/ekm_service/pagers.py create mode 100644 google/cloud/kms_v1/services/ekm_service/transports/__init__.py create mode 100644 google/cloud/kms_v1/services/ekm_service/transports/base.py create mode 100644 google/cloud/kms_v1/services/ekm_service/transports/grpc.py create mode 100644 google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py create mode 100644 google/cloud/kms_v1/types/ekm_service.py create mode 100644 tests/unit/gapic/kms_v1/test_ekm_service.py diff --git a/docs/kms_v1/ekm_service.rst b/docs/kms_v1/ekm_service.rst new file mode 100644 index 00000000..82f6e2a4 --- /dev/null +++ b/docs/kms_v1/ekm_service.rst @@ -0,0 +1,10 @@ +EkmService +---------------------------- + +.. automodule:: google.cloud.kms_v1.services.ekm_service + :members: + :inherited-members: + +.. automodule:: google.cloud.kms_v1.services.ekm_service.pagers + :members: + :inherited-members: diff --git a/docs/kms_v1/services.rst b/docs/kms_v1/services.rst index 1edbf1d6..141ddfe4 100644 --- a/docs/kms_v1/services.rst +++ b/docs/kms_v1/services.rst @@ -3,4 +3,5 @@ Services for Google Cloud Kms v1 API .. toctree:: :maxdepth: 2 + ekm_service key_management_service diff --git a/google/cloud/kms/__init__.py b/google/cloud/kms/__init__.py index d2f8e067..eaca213b 100644 --- a/google/cloud/kms/__init__.py +++ b/google/cloud/kms/__init__.py @@ -14,6 +14,8 @@ # limitations under the License. # +from google.cloud.kms_v1.services.ekm_service.client import EkmServiceClient +from google.cloud.kms_v1.services.ekm_service.async_client import EkmServiceAsyncClient from google.cloud.kms_v1.services.key_management_service.client import ( KeyManagementServiceClient, ) @@ -21,6 +23,13 @@ KeyManagementServiceAsyncClient, ) +from google.cloud.kms_v1.types.ekm_service import Certificate +from google.cloud.kms_v1.types.ekm_service import CreateEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import EkmConnection +from google.cloud.kms_v1.types.ekm_service import GetEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsRequest +from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsResponse +from google.cloud.kms_v1.types.ekm_service import UpdateEkmConnectionRequest from google.cloud.kms_v1.types.resources import CryptoKey from google.cloud.kms_v1.types.resources import CryptoKeyVersion from google.cloud.kms_v1.types.resources import CryptoKeyVersionTemplate @@ -71,8 +80,17 @@ from google.cloud.kms_v1.types.service import UpdateCryptoKeyVersionRequest __all__ = ( + "EkmServiceClient", + "EkmServiceAsyncClient", "KeyManagementServiceClient", "KeyManagementServiceAsyncClient", + "Certificate", + "CreateEkmConnectionRequest", + "EkmConnection", + "GetEkmConnectionRequest", + "ListEkmConnectionsRequest", + "ListEkmConnectionsResponse", + "UpdateEkmConnectionRequest", "CryptoKey", "CryptoKeyVersion", "CryptoKeyVersionTemplate", diff --git a/google/cloud/kms_v1/__init__.py b/google/cloud/kms_v1/__init__.py index 42ba567c..cc0291a7 100644 --- a/google/cloud/kms_v1/__init__.py +++ b/google/cloud/kms_v1/__init__.py @@ -14,9 +14,18 @@ # limitations under the License. # +from .services.ekm_service import EkmServiceClient +from .services.ekm_service import EkmServiceAsyncClient from .services.key_management_service import KeyManagementServiceClient from .services.key_management_service import KeyManagementServiceAsyncClient +from .types.ekm_service import Certificate +from .types.ekm_service import CreateEkmConnectionRequest +from .types.ekm_service import EkmConnection +from .types.ekm_service import GetEkmConnectionRequest +from .types.ekm_service import ListEkmConnectionsRequest +from .types.ekm_service import ListEkmConnectionsResponse +from .types.ekm_service import UpdateEkmConnectionRequest from .types.resources import CryptoKey from .types.resources import CryptoKeyVersion from .types.resources import CryptoKeyVersionTemplate @@ -67,13 +76,16 @@ from .types.service import UpdateCryptoKeyVersionRequest __all__ = ( + "EkmServiceAsyncClient", "KeyManagementServiceAsyncClient", "AsymmetricDecryptRequest", "AsymmetricDecryptResponse", "AsymmetricSignRequest", "AsymmetricSignResponse", + "Certificate", "CreateCryptoKeyRequest", "CreateCryptoKeyVersionRequest", + "CreateEkmConnectionRequest", "CreateImportJobRequest", "CreateKeyRingRequest", "CryptoKey", @@ -83,6 +95,8 @@ "DecryptResponse", "DestroyCryptoKeyVersionRequest", "Digest", + "EkmConnection", + "EkmServiceClient", "EncryptRequest", "EncryptResponse", "ExternalProtectionLevelOptions", @@ -90,6 +104,7 @@ "GenerateRandomBytesResponse", "GetCryptoKeyRequest", "GetCryptoKeyVersionRequest", + "GetEkmConnectionRequest", "GetImportJobRequest", "GetKeyRingRequest", "GetPublicKeyRequest", @@ -102,6 +117,8 @@ "ListCryptoKeyVersionsResponse", "ListCryptoKeysRequest", "ListCryptoKeysResponse", + "ListEkmConnectionsRequest", + "ListEkmConnectionsResponse", "ListImportJobsRequest", "ListImportJobsResponse", "ListKeyRingsRequest", @@ -117,4 +134,5 @@ "UpdateCryptoKeyPrimaryVersionRequest", "UpdateCryptoKeyRequest", "UpdateCryptoKeyVersionRequest", + "UpdateEkmConnectionRequest", ) diff --git a/google/cloud/kms_v1/gapic_metadata.json b/google/cloud/kms_v1/gapic_metadata.json index 582da425..3b830979 100644 --- a/google/cloud/kms_v1/gapic_metadata.json +++ b/google/cloud/kms_v1/gapic_metadata.json @@ -5,6 +5,60 @@ "protoPackage": "google.cloud.kms.v1", "schema": "1.0", "services": { + "EkmService": { + "clients": { + "grpc": { + "libraryClient": "EkmServiceClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EkmServiceAsyncClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + } + } + } + } + }, "KeyManagementService": { "clients": { "grpc": { diff --git a/google/cloud/kms_v1/services/ekm_service/__init__.py b/google/cloud/kms_v1/services/ekm_service/__init__.py new file mode 100644 index 00000000..211dc4ab --- /dev/null +++ b/google/cloud/kms_v1/services/ekm_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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. +# +from .client import EkmServiceClient +from .async_client import EkmServiceAsyncClient + +__all__ = ( + "EkmServiceClient", + "EkmServiceAsyncClient", +) diff --git a/google/cloud/kms_v1/services/ekm_service/async_client.py b/google/cloud/kms_v1/services/ekm_service/async_client.py new file mode 100644 index 00000000..9aab6c69 --- /dev/null +++ b/google/cloud/kms_v1/services/ekm_service/async_client.py @@ -0,0 +1,920 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport +from .client import EkmServiceClient + + +class EkmServiceAsyncClient: + """Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + """ + + _client: EkmServiceClient + + DEFAULT_ENDPOINT = EkmServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EkmServiceClient.DEFAULT_MTLS_ENDPOINT + + ekm_connection_path = staticmethod(EkmServiceClient.ekm_connection_path) + parse_ekm_connection_path = staticmethod(EkmServiceClient.parse_ekm_connection_path) + service_path = staticmethod(EkmServiceClient.service_path) + parse_service_path = staticmethod(EkmServiceClient.parse_service_path) + common_billing_account_path = staticmethod( + EkmServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + EkmServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(EkmServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(EkmServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(EkmServiceClient.common_organization_path) + parse_common_organization_path = staticmethod( + EkmServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(EkmServiceClient.common_project_path) + parse_common_project_path = staticmethod(EkmServiceClient.parse_common_project_path) + common_location_path = staticmethod(EkmServiceClient.common_location_path) + parse_common_location_path = staticmethod( + EkmServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceAsyncClient: The constructed client. + """ + return EkmServiceClient.from_service_account_info.__func__(EkmServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceAsyncClient: The constructed client. + """ + return EkmServiceClient.from_service_account_file.__func__(EkmServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return EkmServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EkmServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EkmServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(EkmServiceClient).get_transport_class, type(EkmServiceClient) + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EkmServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the ekm service client. + + + Args: + 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. + transport (Union[str, ~.EkmServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EkmServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_ekm_connections( + self, + request: Union[ekm_service.ListEkmConnectionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEkmConnectionsAsyncPager: + r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + + Args: + request (Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListEkmConnections][]. + parent (:class:`str`): + Required. The resource name of the location associated + with the + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.services.ekm_service.pagers.ListEkmConnectionsAsyncPager: + Response message for + [KeyManagementService.ListEkmConnections][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = ekm_service.ListEkmConnectionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_ekm_connections, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEkmConnectionsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_ekm_connection( + self, + request: Union[ekm_service.GetEkmConnectionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + + Args: + request (Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.GetEkmConnection][]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = ekm_service.GetEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_ekm_connection( + self, + request: Union[ekm_service.CreateEkmConnectionRequest, dict] = None, + *, + parent: str = None, + ekm_connection_id: str = None, + ekm_connection: ekm_service.EkmConnection = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + + Args: + request (Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateEkmConnection][]. + parent (:class:`str`): + Required. The resource name of the location associated + with the + [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection_id (:class:`str`): + Required. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``ekm_connection_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection (:class:`google.cloud.kms_v1.types.EkmConnection`): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, ekm_connection_id, ekm_connection]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = ekm_service.CreateEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if ekm_connection_id is not None: + request.ekm_connection_id = ekm_connection_id + if ekm_connection is not None: + request.ekm_connection = ekm_connection + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_ekm_connection( + self, + request: Union[ekm_service.UpdateEkmConnectionRequest, dict] = None, + *, + ekm_connection: ekm_service.EkmConnection = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + + Args: + request (Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateEkmConnection][]. + ekm_connection (:class:`google.cloud.kms_v1.types.EkmConnection`): + Required. + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + updated values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([ekm_connection, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = ekm_service.UpdateEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ekm_connection is not None: + request.ekm_connection = ekm_connection + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("ekm_connection.name", request.ekm_connection.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + + Args: + request (:class:`~.policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example**:: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example**:: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does + not have a policy set. + + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example**:: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example**:: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified permissions against the IAM access control + policy for a function. + + If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + 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: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-kms",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("EkmServiceAsyncClient",) diff --git a/google/cloud/kms_v1/services/ekm_service/client.py b/google/cloud/kms_v1/services/ekm_service/client.py new file mode 100644 index 00000000..4b8e4374 --- /dev/null +++ b/google/cloud/kms_v1/services/ekm_service/client.py @@ -0,0 +1,1104 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EkmServiceGrpcTransport +from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport + + +class EkmServiceClientMeta(type): + """Metaclass for the EkmService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] + _transport_registry["grpc"] = EkmServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[EkmServiceTransport]: + """Returns an appropriate transport class. + + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class EkmServiceClient(metaclass=EkmServiceClientMeta): + """Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudkms.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EkmServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EkmServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def ekm_connection_path(project: str, location: str, ekm_connection: str,) -> str: + """Returns a fully-qualified ekm_connection string.""" + return "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format( + project=project, location=location, ekm_connection=ekm_connection, + ) + + @staticmethod + def parse_ekm_connection_path(path: str) -> Dict[str, str]: + """Parses a ekm_connection path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/ekmConnections/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str, location: str, namespace: str, service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parses a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EkmServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the ekm service client. + + + Args: + 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. + transport (Union[str, EkmServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + 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're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options + ) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EkmServiceTransport): + # transport is a EkmServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_ekm_connections( + self, + request: Union[ekm_service.ListEkmConnectionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEkmConnectionsPager: + r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + + Args: + request (Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListEkmConnections][]. + parent (str): + Required. The resource name of the location associated + with the + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.services.ekm_service.pagers.ListEkmConnectionsPager: + Response message for + [KeyManagementService.ListEkmConnections][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.ListEkmConnectionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.ListEkmConnectionsRequest): + request = ekm_service.ListEkmConnectionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_ekm_connections] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEkmConnectionsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_ekm_connection( + self, + request: Union[ekm_service.GetEkmConnectionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + + Args: + request (Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.GetEkmConnection][]. + name (str): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.GetEkmConnectionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.GetEkmConnectionRequest): + request = ekm_service.GetEkmConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_ekm_connection( + self, + request: Union[ekm_service.CreateEkmConnectionRequest, dict] = None, + *, + parent: str = None, + ekm_connection_id: str = None, + ekm_connection: ekm_service.EkmConnection = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + + Args: + request (Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateEkmConnection][]. + parent (str): + Required. The resource name of the location associated + with the + [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection_id (str): + Required. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``ekm_connection_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, ekm_connection_id, ekm_connection]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.CreateEkmConnectionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.CreateEkmConnectionRequest): + request = ekm_service.CreateEkmConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if ekm_connection_id is not None: + request.ekm_connection_id = ekm_connection_id + if ekm_connection is not None: + request.ekm_connection = ekm_connection + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_ekm_connection( + self, + request: Union[ekm_service.UpdateEkmConnectionRequest, dict] = None, + *, + ekm_connection: ekm_service.EkmConnection = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + + Args: + request (Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateEkmConnection][]. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + updated values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([ekm_connection, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.UpdateEkmConnectionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.UpdateEkmConnectionRequest): + request = ekm_service.UpdateEkmConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ekm_connection is not None: + request.ekm_connection = ekm_connection + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("ekm_connection.name", request.ekm_connection.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example**:: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example**:: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + 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: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example**:: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example**:: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + 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: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-kms",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("EkmServiceClient",) diff --git a/google/cloud/kms_v1/services/ekm_service/pagers.py b/google/cloud/kms_v1/services/ekm_service/pagers.py new file mode 100644 index 00000000..c4134305 --- /dev/null +++ b/google/cloud/kms_v1/services/ekm_service/pagers.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Sequence, + Tuple, + Optional, + Iterator, +) + +from google.cloud.kms_v1.types import ekm_service + + +class ListEkmConnectionsPager: + """A pager for iterating through ``list_ekm_connections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``ekm_connections`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEkmConnections`` requests and continue to iterate + through the ``ekm_connections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., ekm_service.ListEkmConnectionsResponse], + request: ekm_service.ListEkmConnectionsRequest, + response: ekm_service.ListEkmConnectionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.kms_v1.types.ListEkmConnectionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListEkmConnectionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = ekm_service.ListEkmConnectionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[ekm_service.ListEkmConnectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[ekm_service.EkmConnection]: + for page in self.pages: + yield from page.ekm_connections + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEkmConnectionsAsyncPager: + """A pager for iterating through ``list_ekm_connections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``ekm_connections`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEkmConnections`` requests and continue to iterate + through the ``ekm_connections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[ekm_service.ListEkmConnectionsResponse]], + request: ekm_service.ListEkmConnectionsRequest, + response: ekm_service.ListEkmConnectionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.kms_v1.types.ListEkmConnectionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListEkmConnectionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = ekm_service.ListEkmConnectionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[ekm_service.ListEkmConnectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[ekm_service.EkmConnection]: + async def async_generator(): + async for page in self.pages: + for response in page.ekm_connections: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/kms_v1/services/ekm_service/transports/__init__.py b/google/cloud/kms_v1/services/ekm_service/transports/__init__.py new file mode 100644 index 00000000..ee2056a3 --- /dev/null +++ b/google/cloud/kms_v1/services/ekm_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EkmServiceTransport +from .grpc import EkmServiceGrpcTransport +from .grpc_asyncio import EkmServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] +_transport_registry["grpc"] = EkmServiceGrpcTransport +_transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport + +__all__ = ( + "EkmServiceTransport", + "EkmServiceGrpcTransport", + "EkmServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/kms_v1/services/ekm_service/transports/base.py b/google/cloud/kms_v1/services/ekm_service/transports/base.py new file mode 100644 index 00000000..0ab2f36c --- /dev/null +++ b/google/cloud/kms_v1/services/ekm_service/transports/base.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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 abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-kms",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class EkmServiceTransport(abc.ABC): + """Abstract transport class for EkmService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ) + + DEFAULT_HOST: str = "cloudkms.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_ekm_connections: gapic_v1.method.wrap_method( + self.list_ekm_connections, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_ekm_connection: gapic_v1.method.wrap_method( + self.get_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_ekm_connection: gapic_v1.method.wrap_method( + self.create_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_ekm_connection: gapic_v1.method.wrap_method( + self.update_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_ekm_connections( + self, + ) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + Union[ + ekm_service.ListEkmConnectionsResponse, + Awaitable[ekm_service.ListEkmConnectionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_ekm_connection( + self, + ) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + Union[ekm_service.EkmConnection, Awaitable[ekm_service.EkmConnection]], + ]: + raise NotImplementedError() + + @property + def create_ekm_connection( + self, + ) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + Union[ekm_service.EkmConnection, Awaitable[ekm_service.EkmConnection]], + ]: + raise NotImplementedError() + + @property + def update_ekm_connection( + self, + ) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + Union[ekm_service.EkmConnection, Awaitable[ekm_service.EkmConnection]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("EkmServiceTransport",) diff --git a/google/cloud/kms_v1/services/ekm_service/transports/grpc.py b/google/cloud/kms_v1/services/ekm_service/transports/grpc.py new file mode 100644 index 00000000..25eb8a18 --- /dev/null +++ b/google/cloud/kms_v1/services/ekm_service/transports/grpc.py @@ -0,0 +1,431 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO + + +class EkmServiceGrpcTransport(EkmServiceTransport): + """gRPC backend transport for EkmService. + + Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "cloudkms.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> 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. + This argument is ignored if ``channel`` is provided. + 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. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudkms.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_ekm_connections( + self, + ) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], ekm_service.ListEkmConnectionsResponse + ]: + r"""Return a callable for the list ekm connections method over gRPC. + + Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.ListEkmConnectionsRequest], + ~.ListEkmConnectionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_ekm_connections" not in self._stubs: + self._stubs["list_ekm_connections"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/ListEkmConnections", + request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, + response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, + ) + return self._stubs["list_ekm_connections"] + + @property + def get_ekm_connection( + self, + ) -> Callable[[ekm_service.GetEkmConnectionRequest], ekm_service.EkmConnection]: + r"""Return a callable for the get ekm connection method over gRPC. + + Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.GetEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_ekm_connection" not in self._stubs: + self._stubs["get_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/GetEkmConnection", + request_serializer=ekm_service.GetEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs["get_ekm_connection"] + + @property + def create_ekm_connection( + self, + ) -> Callable[[ekm_service.CreateEkmConnectionRequest], ekm_service.EkmConnection]: + r"""Return a callable for the create ekm connection method over gRPC. + + Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + Returns: + Callable[[~.CreateEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_ekm_connection" not in self._stubs: + self._stubs["create_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/CreateEkmConnection", + request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs["create_ekm_connection"] + + @property + def update_ekm_connection( + self, + ) -> Callable[[ekm_service.UpdateEkmConnectionRequest], ekm_service.EkmConnection]: + r"""Return a callable for the update ekm connection method over gRPC. + + Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + Returns: + Callable[[~.UpdateEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_ekm_connection" not in self._stubs: + self._stubs["update_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/UpdateEkmConnection", + request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs["update_ekm_connection"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + self.grpc_channel.close() + + +__all__ = ("EkmServiceGrpcTransport",) diff --git a/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py b/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..6f605381 --- /dev/null +++ b/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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 warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import EkmServiceGrpcTransport + + +class EkmServiceGrpcAsyncIOTransport(EkmServiceTransport): + """gRPC AsyncIO backend transport for EkmService. + + Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "cloudkms.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudkms.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> 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. + This argument is ignored if ``channel`` is provided. + 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_ekm_connections( + self, + ) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + Awaitable[ekm_service.ListEkmConnectionsResponse], + ]: + r"""Return a callable for the list ekm connections method over gRPC. + + Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.ListEkmConnectionsRequest], + Awaitable[~.ListEkmConnectionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_ekm_connections" not in self._stubs: + self._stubs["list_ekm_connections"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/ListEkmConnections", + request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, + response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, + ) + return self._stubs["list_ekm_connections"] + + @property + def get_ekm_connection( + self, + ) -> Callable[ + [ekm_service.GetEkmConnectionRequest], Awaitable[ekm_service.EkmConnection] + ]: + r"""Return a callable for the get ekm connection method over gRPC. + + Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.GetEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_ekm_connection" not in self._stubs: + self._stubs["get_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/GetEkmConnection", + request_serializer=ekm_service.GetEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs["get_ekm_connection"] + + @property + def create_ekm_connection( + self, + ) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], Awaitable[ekm_service.EkmConnection] + ]: + r"""Return a callable for the create ekm connection method over gRPC. + + Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + Returns: + Callable[[~.CreateEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_ekm_connection" not in self._stubs: + self._stubs["create_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/CreateEkmConnection", + request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs["create_ekm_connection"] + + @property + def update_ekm_connection( + self, + ) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], Awaitable[ekm_service.EkmConnection] + ]: + r"""Return a callable for the update ekm connection method over gRPC. + + Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + Returns: + Callable[[~.UpdateEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_ekm_connection" not in self._stubs: + self._stubs["update_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/UpdateEkmConnection", + request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs["update_ekm_connection"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("EkmServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/kms_v1/services/key_management_service/async_client.py b/google/cloud/kms_v1/services/key_management_service/async_client.py index f0d0543a..9d3e4fe4 100644 --- a/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -277,7 +277,7 @@ async def list_key_rings( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsAsyncPager: Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. Iterating over this object will yield results and resolve additional pages automatically. @@ -369,7 +369,7 @@ async def list_crypto_keys( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeysAsyncPager: Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. Iterating over this object will yield results and resolve additional pages automatically. @@ -462,7 +462,7 @@ async def list_crypto_key_versions( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager: Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. Iterating over this object will yield results and resolve additional pages automatically. @@ -554,7 +554,7 @@ async def list_import_jobs( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListImportJobsAsyncPager: Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. Iterating over this object will yield results and resolve additional pages automatically. @@ -645,9 +645,8 @@ async def get_key_ring( Returns: google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. """ # Create or coerce a protobuf request object. @@ -732,8 +731,8 @@ async def get_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -823,8 +822,9 @@ async def get_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -924,7 +924,9 @@ async def get_public_key( Returns: google.cloud.kms_v1.types.PublicKey: - The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via + The public key for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Obtained via [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. """ @@ -1008,7 +1010,8 @@ async def get_import_job( Returns: google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using pre-existing key material, generated outside of Cloud KMS. @@ -1151,9 +1154,8 @@ async def create_key_ring( Returns: google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. """ # Create or coerce a protobuf request object. @@ -1260,8 +1262,8 @@ async def create_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1370,8 +1372,9 @@ async def create_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1456,8 +1459,9 @@ async def import_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1546,7 +1550,8 @@ async def create_import_job( Returns: google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using pre-existing key material, generated outside of Cloud KMS. @@ -1683,8 +1688,8 @@ async def update_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1797,8 +1802,9 @@ async def update_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1908,8 +1914,8 @@ async def update_crypto_key_primary_version( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -2021,8 +2027,9 @@ async def destroy_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2126,8 +2133,9 @@ async def restore_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2248,7 +2256,7 @@ async def encrypt( Returns: google.cloud.kms_v1.types.EncryptResponse: Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. """ # Create or coerce a protobuf request object. @@ -2346,7 +2354,7 @@ async def decrypt( Returns: google.cloud.kms_v1.types.DecryptResponse: Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. """ # Create or coerce a protobuf request object. @@ -2434,6 +2442,10 @@ async def asymmetric_sign( specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + This corresponds to the ``digest`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2446,7 +2458,7 @@ async def asymmetric_sign( Returns: google.cloud.kms_v1.types.AsymmetricSignResponse: Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. """ # Create or coerce a protobuf request object. @@ -2546,7 +2558,7 @@ async def asymmetric_decrypt( Returns: google.cloud.kms_v1.types.AsymmetricDecryptResponse: Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. """ # Create or coerce a protobuf request object. @@ -2644,7 +2656,7 @@ async def mac_sign( Returns: google.cloud.kms_v1.types.MacSignResponse: Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. """ # Create or coerce a protobuf request object. @@ -2748,7 +2760,7 @@ async def mac_verify( Returns: google.cloud.kms_v1.types.MacVerifyResponse: Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. """ # Create or coerce a protobuf request object. @@ -2841,8 +2853,9 @@ async def generate_random_bytes( protection_level (:class:`google.cloud.kms_v1.types.ProtectionLevel`): The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Defaults to - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] + protection level is supported. This corresponds to the ``protection_level`` field on the ``request`` instance; if ``request`` is provided, this @@ -2856,7 +2869,7 @@ async def generate_random_bytes( Returns: google.cloud.kms_v1.types.GenerateRandomBytesResponse: Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/kms_v1/services/key_management_service/client.py b/google/cloud/kms_v1/services/key_management_service/client.py index 0966aa0c..c444d4fa 100644 --- a/google/cloud/kms_v1/services/key_management_service/client.py +++ b/google/cloud/kms_v1/services/key_management_service/client.py @@ -553,7 +553,7 @@ def list_key_rings( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsPager: Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. Iterating over this object will yield results and resolve additional pages automatically. @@ -635,7 +635,7 @@ def list_crypto_keys( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeysPager: Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. Iterating over this object will yield results and resolve additional pages automatically. @@ -718,7 +718,7 @@ def list_crypto_key_versions( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsPager: Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. Iterating over this object will yield results and resolve additional pages automatically. @@ -800,7 +800,7 @@ def list_import_jobs( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListImportJobsPager: Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. Iterating over this object will yield results and resolve additional pages automatically. @@ -881,9 +881,8 @@ def get_key_ring( Returns: google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. """ # Create or coerce a protobuf request object. @@ -958,8 +957,8 @@ def get_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1039,8 +1038,9 @@ def get_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1130,7 +1130,9 @@ def get_public_key( Returns: google.cloud.kms_v1.types.PublicKey: - The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via + The public key for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Obtained via [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. """ @@ -1204,7 +1206,8 @@ def get_import_job( Returns: google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using pre-existing key material, generated outside of Cloud KMS. @@ -1337,9 +1340,8 @@ def create_key_ring( Returns: google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. """ # Create or coerce a protobuf request object. @@ -1436,8 +1438,8 @@ def create_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1536,8 +1538,9 @@ def create_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1624,8 +1627,9 @@ def import_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1717,7 +1721,8 @@ def create_import_job( Returns: google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using pre-existing key material, generated outside of Cloud KMS. @@ -1844,8 +1849,8 @@ def update_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1948,8 +1953,9 @@ def update_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2051,8 +2057,8 @@ def update_crypto_key_primary_version( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -2156,8 +2162,9 @@ def destroy_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2253,8 +2260,9 @@ def restore_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2367,7 +2375,7 @@ def encrypt( Returns: google.cloud.kms_v1.types.EncryptResponse: Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. """ # Create or coerce a protobuf request object. @@ -2455,7 +2463,7 @@ def decrypt( Returns: google.cloud.kms_v1.types.DecryptResponse: Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. """ # Create or coerce a protobuf request object. @@ -2533,6 +2541,10 @@ def asymmetric_sign( specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + This corresponds to the ``digest`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2545,7 +2557,7 @@ def asymmetric_sign( Returns: google.cloud.kms_v1.types.AsymmetricSignResponse: Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. """ # Create or coerce a protobuf request object. @@ -2635,7 +2647,7 @@ def asymmetric_decrypt( Returns: google.cloud.kms_v1.types.AsymmetricDecryptResponse: Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. """ # Create or coerce a protobuf request object. @@ -2723,7 +2735,7 @@ def mac_sign( Returns: google.cloud.kms_v1.types.MacSignResponse: Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. """ # Create or coerce a protobuf request object. @@ -2817,7 +2829,7 @@ def mac_verify( Returns: google.cloud.kms_v1.types.MacVerifyResponse: Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. """ # Create or coerce a protobuf request object. @@ -2900,8 +2912,9 @@ def generate_random_bytes( protection_level (google.cloud.kms_v1.types.ProtectionLevel): The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Defaults to - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] + protection level is supported. This corresponds to the ``protection_level`` field on the ``request`` instance; if ``request`` is provided, this @@ -2915,7 +2928,7 @@ def generate_random_bytes( Returns: google.cloud.kms_v1.types.GenerateRandomBytesResponse: Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/kms_v1/types/__init__.py b/google/cloud/kms_v1/types/__init__.py index 85c10803..1e83b0db 100644 --- a/google/cloud/kms_v1/types/__init__.py +++ b/google/cloud/kms_v1/types/__init__.py @@ -13,6 +13,15 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .ekm_service import ( + Certificate, + CreateEkmConnectionRequest, + EkmConnection, + GetEkmConnectionRequest, + ListEkmConnectionsRequest, + ListEkmConnectionsResponse, + UpdateEkmConnectionRequest, +) from .resources import ( CryptoKey, CryptoKeyVersion, @@ -67,6 +76,13 @@ ) __all__ = ( + "Certificate", + "CreateEkmConnectionRequest", + "EkmConnection", + "GetEkmConnectionRequest", + "ListEkmConnectionsRequest", + "ListEkmConnectionsResponse", + "UpdateEkmConnectionRequest", "CryptoKey", "CryptoKeyVersion", "CryptoKeyVersionTemplate", diff --git a/google/cloud/kms_v1/types/ekm_service.py b/google/cloud/kms_v1/types/ekm_service.py new file mode 100644 index 00000000..42d9cdf0 --- /dev/null +++ b/google/cloud/kms_v1/types/ekm_service.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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 proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.kms.v1", + manifest={ + "ListEkmConnectionsRequest", + "ListEkmConnectionsResponse", + "GetEkmConnectionRequest", + "CreateEkmConnectionRequest", + "UpdateEkmConnectionRequest", + "Certificate", + "EkmConnection", + }, +) + + +class ListEkmConnectionsRequest(proto.Message): + r"""Request message for [KeyManagementService.ListEkmConnections][]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + page_size (int): + Optional. Optional limit on the number of + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + include in the response. Further + [EkmConnections][google.cloud.kms.v1.EkmConnection] can + subsequently be obtained by including the + [ListEkmConnectionsResponse.next_page_token][google.cloud.kms.v1.ListEkmConnectionsResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListEkmConnectionsResponse.next_page_token][google.cloud.kms.v1.ListEkmConnectionsResponse.next_page_token]. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) + order_by = proto.Field(proto.STRING, number=5,) + + +class ListEkmConnectionsResponse(proto.Message): + r"""Response message for [KeyManagementService.ListEkmConnections][]. + + Attributes: + ekm_connections (Sequence[google.cloud.kms_v1.types.EkmConnection]): + The list of + [EkmConnections][google.cloud.kms.v1.EkmConnection]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListEkmConnectionsRequest.page_token][google.cloud.kms.v1.ListEkmConnectionsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [EkmConnections][google.cloud.kms.v1.EkmConnection] that + matched the query. + """ + + @property + def raw_page(self): + return self + + ekm_connections = proto.RepeatedField( + proto.MESSAGE, number=1, message="EkmConnection", + ) + next_page_token = proto.Field(proto.STRING, number=2,) + total_size = proto.Field(proto.INT32, number=3,) + + +class GetEkmConnectionRequest(proto.Message): + r"""Request message for [KeyManagementService.GetEkmConnection][]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.EkmConnection.name] + of the [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + """ + + name = proto.Field(proto.STRING, number=1,) + + +class CreateEkmConnectionRequest(proto.Message): + r"""Request message for [KeyManagementService.CreateEkmConnection][]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + ekm_connection_id (str): + Required. It must be unique within a location and match the + regular expression ``[a-zA-Z0-9_-]{1,63}``. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + """ + + parent = proto.Field(proto.STRING, number=1,) + ekm_connection_id = proto.Field(proto.STRING, number=2,) + ekm_connection = proto.Field(proto.MESSAGE, number=3, message="EkmConnection",) + + +class UpdateEkmConnectionRequest(proto.Message): + r"""Request message for [KeyManagementService.UpdateEkmConnection][]. + + Attributes: + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. [EkmConnection][google.cloud.kms.v1.EkmConnection] + with updated values. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + ekm_connection = proto.Field(proto.MESSAGE, number=1, message="EkmConnection",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + + +class Certificate(proto.Message): + r"""A [Certificate][google.cloud.kms.v1.Certificate] represents an X.509 + certificate used to authenticate HTTPS connections to EKM replicas. + + Attributes: + raw_der (bytes): + Required. The raw certificate bytes in DER + format. + parsed (bool): + Output only. True if the certificate was + parsed successfully. + issuer (str): + Output only. The issuer distinguished name in RFC 2253 + format. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + subject (str): + Output only. The subject distinguished name in RFC 2253 + format. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + subject_alternative_dns_names (Sequence[str]): + Output only. The subject Alternative DNS names. Only present + if [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + not_before_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The certificate is not valid before this time. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + not_after_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The certificate is not valid after this time. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + serial_number (str): + Output only. The certificate serial number as a hex string. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + sha256_fingerprint (str): + Output only. The SHA-256 certificate fingerprint as a hex + string. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + """ + + raw_der = proto.Field(proto.BYTES, number=1,) + parsed = proto.Field(proto.BOOL, number=2,) + issuer = proto.Field(proto.STRING, number=3,) + subject = proto.Field(proto.STRING, number=4,) + subject_alternative_dns_names = proto.RepeatedField(proto.STRING, number=5,) + not_before_time = proto.Field( + proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, + ) + not_after_time = proto.Field( + proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp, + ) + serial_number = proto.Field(proto.STRING, number=8,) + sha256_fingerprint = proto.Field(proto.STRING, number=9,) + + +class EkmConnection(proto.Message): + r"""An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for creating + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], as + well as performing cryptographic operations using keys created + within the [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Attributes: + name (str): + Output only. The resource name for the + [EkmConnection][google.cloud.kms.v1.EkmConnection] in the + format ``projects/*/locations/*/ekmConnections/*``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + [EkmConnection][google.cloud.kms.v1.EkmConnection] was + created. + service_resolvers (Sequence[google.cloud.kms_v1.types.EkmConnection.ServiceResolver]): + A list of + [ServiceResolvers][google.cloud.kms.v1.EkmConnection.ServiceResolver] + where the EKM can be reached. There should be one + ServiceResolver per EKM replica. Currently, only a single + [ServiceResolver][google.cloud.kms.v1.EkmConnection.ServiceResolver] + is supported. + etag (str): + This checksum is computed by the server based + on the value of other fields, and may be sent on + update requests to ensure the client has an + up-to-date value before proceeding. + """ + + class ServiceResolver(proto.Message): + r"""A + [ServiceResolver][google.cloud.kms.v1.EkmConnection.ServiceResolver] + represents an EKM replica that can be reached within an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Attributes: + service_directory_service (str): + Required. The resource name of the Service Directory service + pointing to an EKM replica, in the format + ``projects/*/locations/*/namespaces/*/services/*``. + endpoint_filter (str): + Optional. The filter applied to the endpoints + of the resolved service. If no filter is + specified, all endpoints will be considered. An + endpoint will be chosen arbitrarily from the + filtered list for each request. + For endpoint filter syntax and examples, see + https://cloud.google.com/service-directory/docs/reference/rpc/google.cloud.servicedirectory.v1#resolveservicerequest. + hostname (str): + Required. The hostname of the EKM replica + used at TLS and HTTP layers. + server_certificates (Sequence[google.cloud.kms_v1.types.Certificate]): + Required. A list of leaf server certificates + used to authenticate HTTPS connections to the + EKM replica. + """ + + service_directory_service = proto.Field(proto.STRING, number=1,) + endpoint_filter = proto.Field(proto.STRING, number=2,) + hostname = proto.Field(proto.STRING, number=3,) + server_certificates = proto.RepeatedField( + proto.MESSAGE, number=4, message="Certificate", + ) + + name = proto.Field(proto.STRING, number=1,) + create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + service_resolvers = proto.RepeatedField( + proto.MESSAGE, number=3, message=ServiceResolver, + ) + etag = proto.Field(proto.STRING, number=5,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/kms_v1/types/resources.py b/google/cloud/kms_v1/types/resources.py index 73b284ca..6737af3c 100644 --- a/google/cloud/kms_v1/types/resources.py +++ b/google/cloud/kms_v1/types/resources.py @@ -46,6 +46,7 @@ class ProtectionLevel(proto.Enum): SOFTWARE = 1 HSM = 2 EXTERNAL = 3 + EXTERNAL_VPC = 4 class KeyRing(proto.Message): @@ -166,6 +167,23 @@ class CryptoKey(proto.Message): [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. If not specified at creation time, the default duration is 24 hours. + crypto_key_backend (str): + Immutable. The resource name of the backend environment + where the key material for all + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + associated with this + [CryptoKey][google.cloud.kms.v1.CryptoKey] reside and where + all related cryptographic operations are performed. Only + applicable if + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + have a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + with the resource name in the format + ``projects/*/locations/*/ekmConnections/*``. Note, this list + is non-exhaustive and may apply to additional + [ProtectionLevels][google.cloud.kms.v1.ProtectionLevel] in + the future. """ class CryptoKeyPurpose(proto.Enum): @@ -203,6 +221,7 @@ class CryptoKeyPurpose(proto.Enum): destroy_scheduled_duration = proto.Field( proto.MESSAGE, number=14, message=duration_pb2.Duration, ) + crypto_key_backend = proto.Field(proto.STRING, number=15,) class CryptoKeyVersionTemplate(proto.Message): @@ -253,6 +272,9 @@ class KeyOperationAttestation(proto.Message): content (bytes): Output only. The attestation data provided by the HSM when the key operation was performed. + cert_chains (google.cloud.kms_v1.types.KeyOperationAttestation.CertificateChains): + Output only. The certificate chains needed to + validate the attestation """ class AttestationFormat(proto.Enum): @@ -261,8 +283,30 @@ class AttestationFormat(proto.Enum): CAVIUM_V1_COMPRESSED = 3 CAVIUM_V2_COMPRESSED = 4 + class CertificateChains(proto.Message): + r"""Certificate chains needed to verify the attestation. + Certificates in chains are PEM-encoded and are ordered based on + https://tools.ietf.org/html/rfc5246#section-7.4.2. + + Attributes: + cavium_certs (Sequence[str]): + Cavium certificate chain corresponding to the + attestation. + google_card_certs (Sequence[str]): + Google card certificate chain corresponding + to the attestation. + google_partition_certs (Sequence[str]): + Google partition certificate chain + corresponding to the attestation. + """ + + cavium_certs = proto.RepeatedField(proto.STRING, number=1,) + google_card_certs = proto.RepeatedField(proto.STRING, number=2,) + google_partition_certs = proto.RepeatedField(proto.STRING, number=3,) + format = proto.Field(proto.ENUM, number=4, enum=AttestationFormat,) content = proto.Field(proto.BYTES, number=5,) + cert_chains = proto.Field(proto.MESSAGE, number=6, message=CertificateChains,) class CryptoKeyVersion(proto.Message): @@ -347,7 +391,9 @@ class CryptoKeyVersion(proto.Message): [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that are specific to the [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] - protection level. + protection level and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + protection levels. reimport_eligible (bool): Output only. Whether or not this key version is eligible for reimport, by being specified as a target in @@ -689,16 +735,24 @@ class ExternalProtectionLevelOptions(proto.Message): [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that are specific to the [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] protection - level. + level and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + protection levels. Attributes: external_key_uri (str): The URI for an external resource that this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents. + ekm_connection_key_path (str): + The path to the external key material on the EKM when using + [EkmConnection][google.cloud.kms.v1.EkmConnection] e.g., + "v0/my/key". Set this field instead of external_key_uri when + using an [EkmConnection][google.cloud.kms.v1.EkmConnection]. """ external_key_uri = proto.Field(proto.STRING, number=1,) + ekm_connection_key_path = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/kms_v1/types/service.py b/google/cloud/kms_v1/types/service.py index b3673654..3c79c548 100644 --- a/google/cloud/kms_v1/types/service.py +++ b/google/cloud/kms_v1/types/service.py @@ -560,8 +560,9 @@ class ImportCryptoKeyVersionRequest(proto.Message):
  1. An ephemeral AES-256 wrapping key wrapped with the - [public_key][google.cloud.kms.v1.ImportJob.public_key] using RSAES-OAEP with SHA-1, - MGF1 with SHA-1, and an empty label. + [public_key][google.cloud.kms.v1.ImportJob.public_key] using + RSAES-OAEP with SHA-1/SHA-256, MGF1 with SHA-1/SHA-256, and an + empty label.
  2. The key to be imported, wrapped with the ephemeral AES-256 key using AES-KWP (RFC 5649). @@ -878,6 +879,10 @@ class AsymmetricSignRequest(proto.Message): produced with the same digest algorithm as specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. @@ -900,10 +905,9 @@ class AsymmetricSignRequest(proto.Message): exceed 2^32-1, and can be safely downconverted to uint32 in languages that support this type. data (bytes): - Optional. This field will only be honored for RAW_PKCS1 - keys. The data to sign. A digest is computed over the data - that will be signed, PKCS #1 padding is applied to the - digest directly and then encrypted. + Optional. The data to sign. It can't be supplied if + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] + is supplied. data_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]. @@ -1100,8 +1104,9 @@ class GenerateRandomBytesRequest(proto.Message): maximum 1024 bytes. protection_level (google.cloud.kms_v1.types.ProtectionLevel): The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Defaults to - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] protection + level is supported. """ location = proto.Field(proto.STRING, number=1,) diff --git a/scripts/fixup_kms_v1_keywords.py b/scripts/fixup_kms_v1_keywords.py index 1c0a208b..df767766 100644 --- a/scripts/fixup_kms_v1_keywords.py +++ b/scripts/fixup_kms_v1_keywords.py @@ -43,6 +43,7 @@ class kmsCallTransformer(cst.CSTTransformer): 'asymmetric_sign': ('name', 'digest', 'digest_crc32c', 'data', 'data_crc32c', ), 'create_crypto_key': ('parent', 'crypto_key_id', 'crypto_key', 'skip_initial_version_creation', ), 'create_crypto_key_version': ('parent', 'crypto_key_version', ), + 'create_ekm_connection': ('parent', 'ekm_connection_id', 'ekm_connection', ), 'create_import_job': ('parent', 'import_job_id', 'import_job', ), 'create_key_ring': ('parent', 'key_ring_id', 'key_ring', ), 'decrypt': ('name', 'ciphertext', 'additional_authenticated_data', 'ciphertext_crc32c', 'additional_authenticated_data_crc32c', ), @@ -51,12 +52,14 @@ class kmsCallTransformer(cst.CSTTransformer): 'generate_random_bytes': ('location', 'length_bytes', 'protection_level', ), 'get_crypto_key': ('name', ), 'get_crypto_key_version': ('name', ), + 'get_ekm_connection': ('name', ), 'get_import_job': ('name', ), 'get_key_ring': ('name', ), 'get_public_key': ('name', ), 'import_crypto_key_version': ('parent', 'algorithm', 'import_job', 'crypto_key_version', 'rsa_aes_wrapped_key', ), 'list_crypto_keys': ('parent', 'page_size', 'page_token', 'version_view', 'filter', 'order_by', ), 'list_crypto_key_versions': ('parent', 'page_size', 'page_token', 'view', 'filter', 'order_by', ), + 'list_ekm_connections': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_import_jobs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_key_rings': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'mac_sign': ('name', 'data', 'data_crc32c', ), @@ -65,6 +68,7 @@ class kmsCallTransformer(cst.CSTTransformer): 'update_crypto_key': ('crypto_key', 'update_mask', ), 'update_crypto_key_primary_version': ('name', 'crypto_key_version_id', ), 'update_crypto_key_version': ('crypto_key_version', 'update_mask', ), + 'update_ekm_connection': ('ekm_connection', 'update_mask', ), 'get_iam_policy': ('resource', 'options', ), 'set_iam_policy': ('resource', 'policy', ), 'test_iam_permissions': ('resource', 'permissions', ), diff --git a/tests/unit/gapic/kms_v1/test_ekm_service.py b/tests/unit/gapic/kms_v1/test_ekm_service.py new file mode 100644 index 00000000..2f00f3a8 --- /dev/null +++ b/tests/unit/gapic/kms_v1/test_ekm_service.py @@ -0,0 +1,2794 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 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 os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.kms_v1.services.ekm_service import EkmServiceAsyncClient +from google.cloud.kms_v1.services.ekm_service import EkmServiceClient +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.services.ekm_service import transports +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EkmServiceClient._get_default_mtls_endpoint(None) is None + assert ( + EkmServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + EkmServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + EkmServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EkmServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert EkmServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [EkmServiceClient, EkmServiceAsyncClient,]) +def test_ekm_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "cloudkms.googleapis.com:443" + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.EkmServiceGrpcTransport, "grpc"), + (transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_ekm_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [EkmServiceClient, EkmServiceAsyncClient,]) +def test_ekm_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "cloudkms.googleapis.com:443" + + +def test_ekm_service_client_get_transport_class(): + transport = EkmServiceClient.get_transport_class() + available_transports = [ + transports.EkmServiceGrpcTransport, + ] + assert transport in available_transports + + transport = EkmServiceClient.get_transport_class("grpc") + assert transport == transports.EkmServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient) +) +@mock.patch.object( + EkmServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EkmServiceAsyncClient), +) +def test_ekm_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(EkmServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(EkmServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "true"), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "false"), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient) +) +@mock.patch.object( + EkmServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EkmServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_ekm_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [EkmServiceClient, EkmServiceAsyncClient]) +@mock.patch.object( + EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient) +) +@mock.patch.object( + EkmServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EkmServiceAsyncClient), +) +def test_ekm_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_ekm_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_ekm_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_ekm_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = EkmServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_ekm_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ekm_service.ListEkmConnectionsRequest, dict,]) +def test_list_ekm_connections(request_type, transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + response = client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.ListEkmConnectionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEkmConnectionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +def test_list_ekm_connections_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + client.list_ekm_connections() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.ListEkmConnectionsRequest() + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async( + transport: str = "grpc_asyncio", request_type=ekm_service.ListEkmConnectionsRequest +): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.ListEkmConnectionsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + ) + response = await client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.ListEkmConnectionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEkmConnectionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_from_dict(): + await test_list_ekm_connections_async(request_type=dict) + + +def test_list_ekm_connections_field_headers(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.ListEkmConnectionsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + call.return_value = ekm_service.ListEkmConnectionsResponse() + client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_ekm_connections_field_headers_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.ListEkmConnectionsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.ListEkmConnectionsResponse() + ) + await client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_ekm_connections_flattened(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_ekm_connections(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_ekm_connections_flattened_error(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_ekm_connections( + ekm_service.ListEkmConnectionsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_ekm_connections_flattened_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.ListEkmConnectionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_ekm_connections(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_ekm_connections_flattened_error_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_ekm_connections( + ekm_service.ListEkmConnectionsRequest(), parent="parent_value", + ) + + +def test_list_ekm_connections_pager(transport_name: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token="abc", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], next_page_token="def", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ekm_service.EkmConnection(),], next_page_token="ghi", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_ekm_connections(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, ekm_service.EkmConnection) for i in results) + + +def test_list_ekm_connections_pages(transport_name: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token="abc", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], next_page_token="def", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ekm_service.EkmConnection(),], next_page_token="ghi", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + pages = list(client.list_ekm_connections(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_pager(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token="abc", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], next_page_token="def", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ekm_service.EkmConnection(),], next_page_token="ghi", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_ekm_connections(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, ekm_service.EkmConnection) for i in responses) + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_pages(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token="abc", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], next_page_token="def", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ekm_service.EkmConnection(),], next_page_token="ghi", + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_ekm_connections(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ekm_service.GetEkmConnectionRequest, dict,]) +def test_get_ekm_connection(request_type, transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name="name_value", etag="etag_value", + ) + response = client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.GetEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_get_ekm_connection_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), "__call__" + ) as call: + client.get_ekm_connection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.GetEkmConnectionRequest() + + +@pytest.mark.asyncio +async def test_get_ekm_connection_async( + transport: str = "grpc_asyncio", request_type=ekm_service.GetEkmConnectionRequest +): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection(name="name_value", etag="etag_value",) + ) + response = await client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.GetEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_ekm_connection_async_from_dict(): + await test_get_ekm_connection_async(request_type=dict) + + +def test_get_ekm_connection_field_headers(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.GetEkmConnectionRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), "__call__" + ) as call: + call.return_value = ekm_service.EkmConnection() + client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.GetEkmConnectionRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) + await client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_ekm_connection_flattened(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_ekm_connection(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_ekm_connection_flattened_error(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_ekm_connection( + ekm_service.GetEkmConnectionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_ekm_connection(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_ekm_connection( + ekm_service.GetEkmConnectionRequest(), name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", [ekm_service.CreateEkmConnectionRequest, dict,] +) +def test_create_ekm_connection(request_type, transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name="name_value", etag="etag_value", + ) + response = client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.CreateEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_create_ekm_connection_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), "__call__" + ) as call: + client.create_ekm_connection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.CreateEkmConnectionRequest() + + +@pytest.mark.asyncio +async def test_create_ekm_connection_async( + transport: str = "grpc_asyncio", request_type=ekm_service.CreateEkmConnectionRequest +): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection(name="name_value", etag="etag_value",) + ) + response = await client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.CreateEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_create_ekm_connection_async_from_dict(): + await test_create_ekm_connection_async(request_type=dict) + + +def test_create_ekm_connection_field_headers(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.CreateEkmConnectionRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), "__call__" + ) as call: + call.return_value = ekm_service.EkmConnection() + client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.CreateEkmConnectionRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) + await client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_ekm_connection_flattened(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_ekm_connection( + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].ekm_connection_id + mock_val = "ekm_connection_id_value" + assert arg == mock_val + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name="name_value") + assert arg == mock_val + + +def test_create_ekm_connection_flattened_error(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_ekm_connection( + ekm_service.CreateEkmConnectionRequest(), + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_ekm_connection( + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].ekm_connection_id + mock_val = "ekm_connection_id_value" + assert arg == mock_val + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_ekm_connection( + ekm_service.CreateEkmConnectionRequest(), + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", [ekm_service.UpdateEkmConnectionRequest, dict,] +) +def test_update_ekm_connection(request_type, transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name="name_value", etag="etag_value", + ) + response = client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.UpdateEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_update_ekm_connection_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), "__call__" + ) as call: + client.update_ekm_connection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.UpdateEkmConnectionRequest() + + +@pytest.mark.asyncio +async def test_update_ekm_connection_async( + transport: str = "grpc_asyncio", request_type=ekm_service.UpdateEkmConnectionRequest +): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection(name="name_value", etag="etag_value",) + ) + response = await client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.UpdateEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_update_ekm_connection_async_from_dict(): + await test_update_ekm_connection_async(request_type=dict) + + +def test_update_ekm_connection_field_headers(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.UpdateEkmConnectionRequest() + + request.ekm_connection.name = "ekm_connection.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), "__call__" + ) as call: + call.return_value = ekm_service.EkmConnection() + client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "ekm_connection.name=ekm_connection.name/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.UpdateEkmConnectionRequest() + + request.ekm_connection.name = "ekm_connection.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) + await client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "ekm_connection.name=ekm_connection.name/value", + ) in kw["metadata"] + + +def test_update_ekm_connection_flattened(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_ekm_connection( + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_ekm_connection_flattened_error(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_ekm_connection( + ekm_service.UpdateEkmConnectionRequest(), + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_ekm_connection( + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_ekm_connection( + ekm_service.UpdateEkmConnectionRequest(), + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EkmServiceClient(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 = EkmServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EkmServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EkmServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport,], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.EkmServiceGrpcTransport,) + + +def test_ekm_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EkmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_ekm_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EkmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_ekm_connections", + "get_ekm_connection", + "create_ekm_connection", + "update_ekm_connection", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_ekm_service_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.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EkmServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id="octopus", + ) + + +def test_ekm_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EkmServiceTransport() + adc.assert_called_once() + + +def test_ekm_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EkmServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport,], +) +def test_ekm_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EkmServiceGrpcTransport, grpc_helpers), + (transports.EkmServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_ekm_service_host_no_port(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com" + ), + ) + assert client.transport._host == "cloudkms.googleapis.com:443" + + +def test_ekm_service_host_with_port(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com:8000" + ), + ) + assert client.transport._host == "cloudkms.googleapis.com:8000" + + +def test_ekm_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EkmServiceGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_ekm_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EkmServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_ekm_connection_path(): + project = "squid" + location = "clam" + ekm_connection = "whelk" + expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format( + project=project, location=location, ekm_connection=ekm_connection, + ) + actual = EkmServiceClient.ekm_connection_path(project, location, ekm_connection) + assert expected == actual + + +def test_parse_ekm_connection_path(): + expected = { + "project": "octopus", + "location": "oyster", + "ekm_connection": "nudibranch", + } + path = EkmServiceClient.ekm_connection_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_ekm_connection_path(path) + assert expected == actual + + +def test_service_path(): + project = "cuttlefish" + location = "mussel" + namespace = "winkle" + service = "nautilus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + actual = EkmServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "scallop", + "location": "abalone", + "namespace": "squid", + "service": "clam", + } + path = EkmServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_service_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = EkmServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = EkmServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder,) + actual = EkmServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = EkmServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization,) + actual = EkmServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = EkmServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project,) + actual = EkmServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = EkmServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = EkmServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = EkmServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.EkmServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.EkmServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = EkmServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_set_iam_policy(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/tests/unit/gapic/kms_v1/test_key_management_service.py b/tests/unit/gapic/kms_v1/test_key_management_service.py index 8e44d7a5..f05188f8 100644 --- a/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -2367,6 +2367,7 @@ def test_get_crypto_key(request_type, transport: str = "grpc"): name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", rotation_period=duration_pb2.Duration(seconds=751), ) response = client.get_crypto_key(request) @@ -2381,6 +2382,7 @@ def test_get_crypto_key(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" def test_get_crypto_key_empty_call(): @@ -2418,6 +2420,7 @@ async def test_get_crypto_key_async( name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.get_crypto_key(request) @@ -2432,6 +2435,7 @@ async def test_get_crypto_key_async( assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio @@ -3525,6 +3529,7 @@ def test_create_crypto_key(request_type, transport: str = "grpc"): name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", rotation_period=duration_pb2.Duration(seconds=751), ) response = client.create_crypto_key(request) @@ -3539,6 +3544,7 @@ def test_create_crypto_key(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" def test_create_crypto_key_empty_call(): @@ -3580,6 +3586,7 @@ async def test_create_crypto_key_async( name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.create_crypto_key(request) @@ -3594,6 +3601,7 @@ async def test_create_crypto_key_async( assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio @@ -4504,6 +4512,7 @@ def test_update_crypto_key(request_type, transport: str = "grpc"): name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", rotation_period=duration_pb2.Duration(seconds=751), ) response = client.update_crypto_key(request) @@ -4518,6 +4527,7 @@ def test_update_crypto_key(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" def test_update_crypto_key_empty_call(): @@ -4559,6 +4569,7 @@ async def test_update_crypto_key_async( name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.update_crypto_key(request) @@ -4573,6 +4584,7 @@ async def test_update_crypto_key_async( assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio @@ -5039,6 +5051,7 @@ def test_update_crypto_key_primary_version(request_type, transport: str = "grpc" name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", rotation_period=duration_pb2.Duration(seconds=751), ) response = client.update_crypto_key_primary_version(request) @@ -5053,6 +5066,7 @@ def test_update_crypto_key_primary_version(request_type, transport: str = "grpc" assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" def test_update_crypto_key_primary_version_empty_call(): @@ -5095,6 +5109,7 @@ async def test_update_crypto_key_primary_version_async( name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.update_crypto_key_primary_version(request) @@ -5109,6 +5124,7 @@ async def test_update_crypto_key_primary_version_async( assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio From 5b1069a730125532ea61eea3bcdc3484b7ac2e80 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 3 Feb 2022 11:50:43 +0000 Subject: [PATCH 24/24] chore(main): release 2.11.0 (#228) :robot: I have created a release *beep* *boop* --- ## [2.11.0](https://github.com/googleapis/python-kms/compare/v2.10.1...v2.11.0) (2022-02-03) ### Features * add a new EkmService API ([#233](https://github.com/googleapis/python-kms/issues/233)) ([eb532f5](https://github.com/googleapis/python-kms/commit/eb532f5c84907c12356e549c694c0210e5ad585b)) * add api key support ([#230](https://github.com/googleapis/python-kms/issues/230)) ([fdf62ae](https://github.com/googleapis/python-kms/commit/fdf62ae3b3209a1215e0f2f2440add1f01d40907)) ### Bug Fixes * resolve DuplicateCredentialArgs error when using credentials_file ([97f7ea5](https://github.com/googleapis/python-kms/commit/97f7ea50a30d1dc1133d7703e6bd90ad209f75a1)) ### Documentation * **samples:** fix typo in verify_asymmetric_ec.py ([#227](https://github.com/googleapis/python-kms/issues/227)) ([3817d73](https://github.com/googleapis/python-kms/commit/3817d7390fddebd137c99865455f0ae145dbcf63)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 18 ++++++++++++++++++ setup.py | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f31ab66..0c6ba976 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ [1]: https://pypi.org/project/google-cloud-kms/#history +## [2.11.0](https://github.com/googleapis/python-kms/compare/v2.10.1...v2.11.0) (2022-02-03) + + +### Features + +* add a new EkmService API ([#233](https://github.com/googleapis/python-kms/issues/233)) ([eb532f5](https://github.com/googleapis/python-kms/commit/eb532f5c84907c12356e549c694c0210e5ad585b)) +* add api key support ([#230](https://github.com/googleapis/python-kms/issues/230)) ([fdf62ae](https://github.com/googleapis/python-kms/commit/fdf62ae3b3209a1215e0f2f2440add1f01d40907)) + + +### Bug Fixes + +* resolve DuplicateCredentialArgs error when using credentials_file ([97f7ea5](https://github.com/googleapis/python-kms/commit/97f7ea50a30d1dc1133d7703e6bd90ad209f75a1)) + + +### Documentation + +* **samples:** fix typo in verify_asymmetric_ec.py ([#227](https://github.com/googleapis/python-kms/issues/227)) ([3817d73](https://github.com/googleapis/python-kms/commit/3817d7390fddebd137c99865455f0ae145dbcf63)) + ### [2.10.1](https://www.github.com/googleapis/python-kms/compare/v2.10.0...v2.10.1) (2021-11-01) diff --git a/setup.py b/setup.py index cbd8ee6a..8c4ddd9d 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name = "google-cloud-kms" description = "Cloud Key Management Service (KMS) API client library" -version = "2.10.1" +version = "2.11.0" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ # NOTE: Maintainers, please do not require google-api-core>=2.x.x