From de3ec2ef49202acfe627580f93274c8ef8f91176 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 24 Jan 2022 20:26:29 +0000 Subject: [PATCH 1/2] 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 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + owl-bot-staging/v1/docs/conf.py | 376 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/docs/kms_v1/key_management_service.rst | 10 + owl-bot-staging/v1/docs/kms_v1/services.rst | 6 + owl-bot-staging/v1/docs/kms_v1/types.rst | 7 + .../v1/google/cloud/kms/__init__.py | 119 + owl-bot-staging/v1/google/cloud/kms/py.typed | 2 + .../v1/google/cloud/kms_v1/__init__.py | 120 + .../google/cloud/kms_v1/gapic_metadata.json | 283 + .../v1/google/cloud/kms_v1/py.typed | 2 + .../google/cloud/kms_v1/services/__init__.py | 15 + .../key_management_service/__init__.py | 22 + .../key_management_service/async_client.py | 3184 ++++++ .../services/key_management_service/client.py | 3254 ++++++ .../services/key_management_service/pagers.py | 503 + .../transports/__init__.py | 33 + .../key_management_service/transports/base.py | 696 ++ .../key_management_service/transports/grpc.py | 1115 +++ .../transports/grpc_asyncio.py | 1120 +++ .../v1/google/cloud/kms_v1/types/__init__.py | 118 + .../v1/google/cloud/kms_v1/types/resources.py | 843 ++ .../v1/google/cloud/kms_v1/types/service.py | 1974 ++++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../v1/scripts/fixup_kms_v1_keywords.py | 204 + owl-bot-staging/v1/setup.py | 55 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../v1/tests/unit/gapic/kms_v1/__init__.py | 16 + .../kms_v1/test_key_management_service.py | 8912 +++++++++++++++++ 34 files changed, 23247 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/docs/kms_v1/key_management_service.rst create mode 100644 owl-bot-staging/v1/docs/kms_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/kms_v1/types.rst create mode 100644 owl-bot-staging/v1/google/cloud/kms/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/kms/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/types/service.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/kms_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..6bc3e283 --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/kms/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 00000000..97846726 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/kms *.py +recursive-include google/cloud/kms_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..9574e81c --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Kms API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Kms API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 00000000..e69a1dd2 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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. +# +# +# google-cloud-kms documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-kms" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-kms-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-kms.tex", + u"google-cloud-kms Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-kms", + u"Google Cloud Kms Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-kms", + u"google-cloud-kms Documentation", + author, + "google-cloud-kms", + "GAPIC library for Google Cloud Kms API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 00000000..ce6aa927 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + kms_v1/services + kms_v1/types diff --git a/owl-bot-staging/v1/docs/kms_v1/key_management_service.rst b/owl-bot-staging/v1/docs/kms_v1/key_management_service.rst new file mode 100644 index 00000000..b34ce028 --- /dev/null +++ b/owl-bot-staging/v1/docs/kms_v1/key_management_service.rst @@ -0,0 +1,10 @@ +KeyManagementService +-------------------------------------- + +.. automodule:: google.cloud.kms_v1.services.key_management_service + :members: + :inherited-members: + +.. automodule:: google.cloud.kms_v1.services.key_management_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/kms_v1/services.rst b/owl-bot-staging/v1/docs/kms_v1/services.rst new file mode 100644 index 00000000..1edbf1d6 --- /dev/null +++ b/owl-bot-staging/v1/docs/kms_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Kms v1 API +==================================== +.. toctree:: + :maxdepth: 2 + + key_management_service diff --git a/owl-bot-staging/v1/docs/kms_v1/types.rst b/owl-bot-staging/v1/docs/kms_v1/types.rst new file mode 100644 index 00000000..fe1026e9 --- /dev/null +++ b/owl-bot-staging/v1/docs/kms_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Kms v1 API +================================= + +.. automodule:: google.cloud.kms_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/kms/__init__.py b/owl-bot-staging/v1/google/cloud/kms/__init__.py new file mode 100644 index 00000000..77107dbb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms/__init__.py @@ -0,0 +1,119 @@ +# -*- 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 google.cloud.kms_v1.services.key_management_service.client import KeyManagementServiceClient +from google.cloud.kms_v1.services.key_management_service.async_client import KeyManagementServiceAsyncClient + +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 +from google.cloud.kms_v1.types.resources import ExternalProtectionLevelOptions +from google.cloud.kms_v1.types.resources import ImportJob +from google.cloud.kms_v1.types.resources import KeyOperationAttestation +from google.cloud.kms_v1.types.resources import KeyRing +from google.cloud.kms_v1.types.resources import PublicKey +from google.cloud.kms_v1.types.resources import ProtectionLevel +from google.cloud.kms_v1.types.service import AsymmetricDecryptRequest +from google.cloud.kms_v1.types.service import AsymmetricDecryptResponse +from google.cloud.kms_v1.types.service import AsymmetricSignRequest +from google.cloud.kms_v1.types.service import AsymmetricSignResponse +from google.cloud.kms_v1.types.service import CreateCryptoKeyRequest +from google.cloud.kms_v1.types.service import CreateCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import CreateImportJobRequest +from google.cloud.kms_v1.types.service import CreateKeyRingRequest +from google.cloud.kms_v1.types.service import DecryptRequest +from google.cloud.kms_v1.types.service import DecryptResponse +from google.cloud.kms_v1.types.service import DestroyCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import Digest +from google.cloud.kms_v1.types.service import EncryptRequest +from google.cloud.kms_v1.types.service import EncryptResponse +from google.cloud.kms_v1.types.service import GenerateRandomBytesRequest +from google.cloud.kms_v1.types.service import GenerateRandomBytesResponse +from google.cloud.kms_v1.types.service import GetCryptoKeyRequest +from google.cloud.kms_v1.types.service import GetCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import GetImportJobRequest +from google.cloud.kms_v1.types.service import GetKeyRingRequest +from google.cloud.kms_v1.types.service import GetPublicKeyRequest +from google.cloud.kms_v1.types.service import ImportCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import ListCryptoKeysRequest +from google.cloud.kms_v1.types.service import ListCryptoKeysResponse +from google.cloud.kms_v1.types.service import ListCryptoKeyVersionsRequest +from google.cloud.kms_v1.types.service import ListCryptoKeyVersionsResponse +from google.cloud.kms_v1.types.service import ListImportJobsRequest +from google.cloud.kms_v1.types.service import ListImportJobsResponse +from google.cloud.kms_v1.types.service import ListKeyRingsRequest +from google.cloud.kms_v1.types.service import ListKeyRingsResponse +from google.cloud.kms_v1.types.service import LocationMetadata +from google.cloud.kms_v1.types.service import MacSignRequest +from google.cloud.kms_v1.types.service import MacSignResponse +from google.cloud.kms_v1.types.service import MacVerifyRequest +from google.cloud.kms_v1.types.service import MacVerifyResponse +from google.cloud.kms_v1.types.service import RestoreCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import UpdateCryptoKeyPrimaryVersionRequest +from google.cloud.kms_v1.types.service import UpdateCryptoKeyRequest +from google.cloud.kms_v1.types.service import UpdateCryptoKeyVersionRequest + +__all__ = ('KeyManagementServiceClient', + 'KeyManagementServiceAsyncClient', + 'CryptoKey', + 'CryptoKeyVersion', + 'CryptoKeyVersionTemplate', + 'ExternalProtectionLevelOptions', + 'ImportJob', + 'KeyOperationAttestation', + 'KeyRing', + 'PublicKey', + 'ProtectionLevel', + 'AsymmetricDecryptRequest', + 'AsymmetricDecryptResponse', + 'AsymmetricSignRequest', + 'AsymmetricSignResponse', + 'CreateCryptoKeyRequest', + 'CreateCryptoKeyVersionRequest', + 'CreateImportJobRequest', + 'CreateKeyRingRequest', + 'DecryptRequest', + 'DecryptResponse', + 'DestroyCryptoKeyVersionRequest', + 'Digest', + 'EncryptRequest', + 'EncryptResponse', + 'GenerateRandomBytesRequest', + 'GenerateRandomBytesResponse', + 'GetCryptoKeyRequest', + 'GetCryptoKeyVersionRequest', + 'GetImportJobRequest', + 'GetKeyRingRequest', + 'GetPublicKeyRequest', + 'ImportCryptoKeyVersionRequest', + 'ListCryptoKeysRequest', + 'ListCryptoKeysResponse', + 'ListCryptoKeyVersionsRequest', + 'ListCryptoKeyVersionsResponse', + 'ListImportJobsRequest', + 'ListImportJobsResponse', + 'ListKeyRingsRequest', + 'ListKeyRingsResponse', + 'LocationMetadata', + 'MacSignRequest', + 'MacSignResponse', + 'MacVerifyRequest', + 'MacVerifyResponse', + 'RestoreCryptoKeyVersionRequest', + 'UpdateCryptoKeyPrimaryVersionRequest', + 'UpdateCryptoKeyRequest', + 'UpdateCryptoKeyVersionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/kms/py.typed b/owl-bot-staging/v1/google/cloud/kms/py.typed new file mode 100644 index 00000000..3720b5f2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-kms package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/__init__.py new file mode 100644 index 00000000..23e95304 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/__init__.py @@ -0,0 +1,120 @@ +# -*- 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 .services.key_management_service import KeyManagementServiceClient +from .services.key_management_service import KeyManagementServiceAsyncClient + +from .types.resources import CryptoKey +from .types.resources import CryptoKeyVersion +from .types.resources import CryptoKeyVersionTemplate +from .types.resources import ExternalProtectionLevelOptions +from .types.resources import ImportJob +from .types.resources import KeyOperationAttestation +from .types.resources import KeyRing +from .types.resources import PublicKey +from .types.resources import ProtectionLevel +from .types.service import AsymmetricDecryptRequest +from .types.service import AsymmetricDecryptResponse +from .types.service import AsymmetricSignRequest +from .types.service import AsymmetricSignResponse +from .types.service import CreateCryptoKeyRequest +from .types.service import CreateCryptoKeyVersionRequest +from .types.service import CreateImportJobRequest +from .types.service import CreateKeyRingRequest +from .types.service import DecryptRequest +from .types.service import DecryptResponse +from .types.service import DestroyCryptoKeyVersionRequest +from .types.service import Digest +from .types.service import EncryptRequest +from .types.service import EncryptResponse +from .types.service import GenerateRandomBytesRequest +from .types.service import GenerateRandomBytesResponse +from .types.service import GetCryptoKeyRequest +from .types.service import GetCryptoKeyVersionRequest +from .types.service import GetImportJobRequest +from .types.service import GetKeyRingRequest +from .types.service import GetPublicKeyRequest +from .types.service import ImportCryptoKeyVersionRequest +from .types.service import ListCryptoKeysRequest +from .types.service import ListCryptoKeysResponse +from .types.service import ListCryptoKeyVersionsRequest +from .types.service import ListCryptoKeyVersionsResponse +from .types.service import ListImportJobsRequest +from .types.service import ListImportJobsResponse +from .types.service import ListKeyRingsRequest +from .types.service import ListKeyRingsResponse +from .types.service import LocationMetadata +from .types.service import MacSignRequest +from .types.service import MacSignResponse +from .types.service import MacVerifyRequest +from .types.service import MacVerifyResponse +from .types.service import RestoreCryptoKeyVersionRequest +from .types.service import UpdateCryptoKeyPrimaryVersionRequest +from .types.service import UpdateCryptoKeyRequest +from .types.service import UpdateCryptoKeyVersionRequest + +__all__ = ( + 'KeyManagementServiceAsyncClient', +'AsymmetricDecryptRequest', +'AsymmetricDecryptResponse', +'AsymmetricSignRequest', +'AsymmetricSignResponse', +'CreateCryptoKeyRequest', +'CreateCryptoKeyVersionRequest', +'CreateImportJobRequest', +'CreateKeyRingRequest', +'CryptoKey', +'CryptoKeyVersion', +'CryptoKeyVersionTemplate', +'DecryptRequest', +'DecryptResponse', +'DestroyCryptoKeyVersionRequest', +'Digest', +'EncryptRequest', +'EncryptResponse', +'ExternalProtectionLevelOptions', +'GenerateRandomBytesRequest', +'GenerateRandomBytesResponse', +'GetCryptoKeyRequest', +'GetCryptoKeyVersionRequest', +'GetImportJobRequest', +'GetKeyRingRequest', +'GetPublicKeyRequest', +'ImportCryptoKeyVersionRequest', +'ImportJob', +'KeyManagementServiceClient', +'KeyOperationAttestation', +'KeyRing', +'ListCryptoKeyVersionsRequest', +'ListCryptoKeyVersionsResponse', +'ListCryptoKeysRequest', +'ListCryptoKeysResponse', +'ListImportJobsRequest', +'ListImportJobsResponse', +'ListKeyRingsRequest', +'ListKeyRingsResponse', +'LocationMetadata', +'MacSignRequest', +'MacSignResponse', +'MacVerifyRequest', +'MacVerifyResponse', +'ProtectionLevel', +'PublicKey', +'RestoreCryptoKeyVersionRequest', +'UpdateCryptoKeyPrimaryVersionRequest', +'UpdateCryptoKeyRequest', +'UpdateCryptoKeyVersionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json new file mode 100644 index 00000000..582da425 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json @@ -0,0 +1,283 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.kms_v1", + "protoPackage": "google.cloud.kms.v1", + "schema": "1.0", + "services": { + "KeyManagementService": { + "clients": { + "grpc": { + "libraryClient": "KeyManagementServiceClient", + "rpcs": { + "AsymmetricDecrypt": { + "methods": [ + "asymmetric_decrypt" + ] + }, + "AsymmetricSign": { + "methods": [ + "asymmetric_sign" + ] + }, + "CreateCryptoKey": { + "methods": [ + "create_crypto_key" + ] + }, + "CreateCryptoKeyVersion": { + "methods": [ + "create_crypto_key_version" + ] + }, + "CreateImportJob": { + "methods": [ + "create_import_job" + ] + }, + "CreateKeyRing": { + "methods": [ + "create_key_ring" + ] + }, + "Decrypt": { + "methods": [ + "decrypt" + ] + }, + "DestroyCryptoKeyVersion": { + "methods": [ + "destroy_crypto_key_version" + ] + }, + "Encrypt": { + "methods": [ + "encrypt" + ] + }, + "GenerateRandomBytes": { + "methods": [ + "generate_random_bytes" + ] + }, + "GetCryptoKey": { + "methods": [ + "get_crypto_key" + ] + }, + "GetCryptoKeyVersion": { + "methods": [ + "get_crypto_key_version" + ] + }, + "GetImportJob": { + "methods": [ + "get_import_job" + ] + }, + "GetKeyRing": { + "methods": [ + "get_key_ring" + ] + }, + "GetPublicKey": { + "methods": [ + "get_public_key" + ] + }, + "ImportCryptoKeyVersion": { + "methods": [ + "import_crypto_key_version" + ] + }, + "ListCryptoKeyVersions": { + "methods": [ + "list_crypto_key_versions" + ] + }, + "ListCryptoKeys": { + "methods": [ + "list_crypto_keys" + ] + }, + "ListImportJobs": { + "methods": [ + "list_import_jobs" + ] + }, + "ListKeyRings": { + "methods": [ + "list_key_rings" + ] + }, + "MacSign": { + "methods": [ + "mac_sign" + ] + }, + "MacVerify": { + "methods": [ + "mac_verify" + ] + }, + "RestoreCryptoKeyVersion": { + "methods": [ + "restore_crypto_key_version" + ] + }, + "UpdateCryptoKey": { + "methods": [ + "update_crypto_key" + ] + }, + "UpdateCryptoKeyPrimaryVersion": { + "methods": [ + "update_crypto_key_primary_version" + ] + }, + "UpdateCryptoKeyVersion": { + "methods": [ + "update_crypto_key_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "KeyManagementServiceAsyncClient", + "rpcs": { + "AsymmetricDecrypt": { + "methods": [ + "asymmetric_decrypt" + ] + }, + "AsymmetricSign": { + "methods": [ + "asymmetric_sign" + ] + }, + "CreateCryptoKey": { + "methods": [ + "create_crypto_key" + ] + }, + "CreateCryptoKeyVersion": { + "methods": [ + "create_crypto_key_version" + ] + }, + "CreateImportJob": { + "methods": [ + "create_import_job" + ] + }, + "CreateKeyRing": { + "methods": [ + "create_key_ring" + ] + }, + "Decrypt": { + "methods": [ + "decrypt" + ] + }, + "DestroyCryptoKeyVersion": { + "methods": [ + "destroy_crypto_key_version" + ] + }, + "Encrypt": { + "methods": [ + "encrypt" + ] + }, + "GenerateRandomBytes": { + "methods": [ + "generate_random_bytes" + ] + }, + "GetCryptoKey": { + "methods": [ + "get_crypto_key" + ] + }, + "GetCryptoKeyVersion": { + "methods": [ + "get_crypto_key_version" + ] + }, + "GetImportJob": { + "methods": [ + "get_import_job" + ] + }, + "GetKeyRing": { + "methods": [ + "get_key_ring" + ] + }, + "GetPublicKey": { + "methods": [ + "get_public_key" + ] + }, + "ImportCryptoKeyVersion": { + "methods": [ + "import_crypto_key_version" + ] + }, + "ListCryptoKeyVersions": { + "methods": [ + "list_crypto_key_versions" + ] + }, + "ListCryptoKeys": { + "methods": [ + "list_crypto_keys" + ] + }, + "ListImportJobs": { + "methods": [ + "list_import_jobs" + ] + }, + "ListKeyRings": { + "methods": [ + "list_key_rings" + ] + }, + "MacSign": { + "methods": [ + "mac_sign" + ] + }, + "MacVerify": { + "methods": [ + "mac_verify" + ] + }, + "RestoreCryptoKeyVersion": { + "methods": [ + "restore_crypto_key_version" + ] + }, + "UpdateCryptoKey": { + "methods": [ + "update_crypto_key" + ] + }, + "UpdateCryptoKeyPrimaryVersion": { + "methods": [ + "update_crypto_key_primary_version" + ] + }, + "UpdateCryptoKeyVersion": { + "methods": [ + "update_crypto_key_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/py.typed b/owl-bot-staging/v1/google/cloud/kms_v1/py.typed new file mode 100644 index 00000000..3720b5f2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-kms package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/__init__.py new file mode 100644 index 00000000..5952e44c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_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 KeyManagementServiceClient +from .async_client import KeyManagementServiceAsyncClient + +__all__ = ( + 'KeyManagementServiceClient', + 'KeyManagementServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py new file mode 100644 index 00000000..500147a2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -0,0 +1,3184 @@ +# -*- 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.key_management_service import pagers +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport +from .client import KeyManagementServiceClient + + +class KeyManagementServiceAsyncClient: + """Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + """ + + _client: KeyManagementServiceClient + + DEFAULT_ENDPOINT = KeyManagementServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT + + crypto_key_path = staticmethod(KeyManagementServiceClient.crypto_key_path) + parse_crypto_key_path = staticmethod(KeyManagementServiceClient.parse_crypto_key_path) + crypto_key_version_path = staticmethod(KeyManagementServiceClient.crypto_key_version_path) + parse_crypto_key_version_path = staticmethod(KeyManagementServiceClient.parse_crypto_key_version_path) + import_job_path = staticmethod(KeyManagementServiceClient.import_job_path) + parse_import_job_path = staticmethod(KeyManagementServiceClient.parse_import_job_path) + key_ring_path = staticmethod(KeyManagementServiceClient.key_ring_path) + parse_key_ring_path = staticmethod(KeyManagementServiceClient.parse_key_ring_path) + public_key_path = staticmethod(KeyManagementServiceClient.public_key_path) + parse_public_key_path = staticmethod(KeyManagementServiceClient.parse_public_key_path) + common_billing_account_path = staticmethod(KeyManagementServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(KeyManagementServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(KeyManagementServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(KeyManagementServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(KeyManagementServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(KeyManagementServiceClient.parse_common_organization_path) + common_project_path = staticmethod(KeyManagementServiceClient.common_project_path) + parse_common_project_path = staticmethod(KeyManagementServiceClient.parse_common_project_path) + common_location_path = staticmethod(KeyManagementServiceClient.common_location_path) + parse_common_location_path = staticmethod(KeyManagementServiceClient.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: + KeyManagementServiceAsyncClient: The constructed client. + """ + return KeyManagementServiceClient.from_service_account_info.__func__(KeyManagementServiceAsyncClient, 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: + KeyManagementServiceAsyncClient: The constructed client. + """ + return KeyManagementServiceClient.from_service_account_file.__func__(KeyManagementServiceAsyncClient, 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 KeyManagementServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> KeyManagementServiceTransport: + """Returns the transport used by the client instance. + + Returns: + KeyManagementServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(KeyManagementServiceClient).get_transport_class, type(KeyManagementServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, KeyManagementServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the key management 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, ~.KeyManagementServiceTransport]): 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 = KeyManagementServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_key_rings(self, + request: Union[service.ListKeyRingsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKeyRingsAsyncPager: + r"""Lists [KeyRings][google.cloud.kms.v1.KeyRing]. + + Args: + request (Union[google.cloud.kms_v1.types.ListKeyRingsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + parent (:class:`str`): + Required. The resource name of the location associated + with the [KeyRings][google.cloud.kms.v1.KeyRing], 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.key_management_service.pagers.ListKeyRingsAsyncPager: + Response message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.ListKeyRingsRequest(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_key_rings, + 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.ListKeyRingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_crypto_keys(self, + request: Union[service.ListCryptoKeysRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCryptoKeysAsyncPager: + r"""Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + Args: + request (Union[google.cloud.kms_v1.types.ListCryptoKeysRequest, dict]): + The request object. Request message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + parent (:class:`str`): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + + 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.key_management_service.pagers.ListCryptoKeysAsyncPager: + Response message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.ListCryptoKeysRequest(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_crypto_keys, + 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.ListCryptoKeysAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_crypto_key_versions(self, + request: Union[service.ListCryptoKeyVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCryptoKeyVersionsAsyncPager: + r"""Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + Args: + request (Union[google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + parent (:class:`str`): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in + the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + + 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.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager: + Response message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.ListCryptoKeyVersionsRequest(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_crypto_key_versions, + 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.ListCryptoKeyVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_import_jobs(self, + request: Union[service.ListImportJobsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListImportJobsAsyncPager: + r"""Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. + + Args: + request (Union[google.cloud.kms_v1.types.ListImportJobsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + parent (:class:`str`): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + + 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.key_management_service.pagers.ListImportJobsAsyncPager: + Response message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.ListImportJobsRequest(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_import_jobs, + 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.ListImportJobsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_key_ring(self, + request: Union[service.GetKeyRingRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyRing: + r"""Returns metadata for a given + [KeyRing][google.cloud.kms.v1.KeyRing]. + + Args: + request (Union[google.cloud.kms_v1.types.GetKeyRingRequest, dict]): + The request object. Request message for + [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. + name (:class:`str`): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the [KeyRing][google.cloud.kms.v1.KeyRing] 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.KeyRing: + 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. + # Sanity 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 = service.GetKeyRingRequest(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_key_ring, + 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 get_crypto_key(self, + request: Union[service.GetCryptoKeyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Returns metadata for a given + [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its + [primary][google.cloud.kms.v1.CryptoKey.primary] + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Args: + request (Union[google.cloud.kms_v1.types.GetCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. + name (:class:`str`): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] 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.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] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.GetCryptoKeyRequest(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_crypto_key, + 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 get_crypto_key_version(self, + request: Union[service.GetCryptoKeyVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Returns metadata for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Args: + request (Union[google.cloud.kms_v1.types.GetCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.GetCryptoKeyVersionRequest(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_crypto_key_version, + 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 get_public_key(self, + request: Union[service.GetPublicKeyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.PublicKey: + r"""Returns the public key for the given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] + or + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + Args: + request (Union[google.cloud.kms_v1.types.GetPublicKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key 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.PublicKey: + The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.GetPublicKeyRequest(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_public_key, + 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 get_import_job(self, + request: Union[service.GetImportJobRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ImportJob: + r"""Returns metadata for a given + [ImportJob][google.cloud.kms.v1.ImportJob]. + + Args: + request (Union[google.cloud.kms_v1.types.GetImportJobRequest, dict]): + The request object. Request message for + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. + name (:class:`str`): + Required. The [name][google.cloud.kms.v1.ImportJob.name] + of the [ImportJob][google.cloud.kms.v1.ImportJob] 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.ImportJob: + 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. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.GetImportJobRequest(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_import_job, + 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_key_ring(self, + request: Union[service.CreateKeyRingRequest, dict] = None, + *, + parent: str = None, + key_ring_id: str = None, + key_ring: resources.KeyRing = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyRing: + r"""Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given + Project and Location. + + Args: + request (Union[google.cloud.kms_v1.types.CreateKeyRingRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. + parent (:class:`str`): + Required. The resource name of the location associated + with the [KeyRings][google.cloud.kms.v1.KeyRing], in the + format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_ring_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 ``key_ring_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_ring (:class:`google.cloud.kms_v1.types.KeyRing`): + Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with + initial field values. + + This corresponds to the ``key_ring`` 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.KeyRing: + 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. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.CreateKeyRingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_ring_id is not None: + request.key_ring_id = key_ring_id + if key_ring is not None: + request.key_ring = key_ring + + # 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_key_ring, + 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 create_crypto_key(self, + request: Union[service.CreateCryptoKeyRequest, dict] = None, + *, + parent: str = None, + crypto_key_id: str = None, + crypto_key: resources.CryptoKey = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and + [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] + are required. + + Args: + request (Union[google.cloud.kms_v1.types.CreateCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. + parent (:class:`str`): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the KeyRing associated with the + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_id (:class:`str`): + Required. It must be unique within a KeyRing and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``crypto_key_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): + Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] + with initial field values. + + This corresponds to the ``crypto_key`` 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.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] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.CreateCryptoKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if crypto_key_id is not None: + request.crypto_key_id = crypto_key_id + if crypto_key is not None: + request.crypto_key = crypto_key + + # 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_crypto_key, + 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 create_crypto_key_version(self, + request: Union[service.CreateCryptoKeyVersionRequest, dict] = None, + *, + parent: str = None, + crypto_key_version: resources.CryptoKeyVersion = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Create a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The server will assign the next sequential id. If unset, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. + + Args: + request (Union[google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. + parent (:class:`str`): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] + associated with the + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): + Required. A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with initial field values. + + This corresponds to the ``crypto_key_version`` 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.CreateCryptoKeyVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if crypto_key_version is not None: + request.crypto_key_version = crypto_key_version + + # 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_crypto_key_version, + 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 import_crypto_key_version(self, + request: Union[service.ImportCryptoKeyVersionRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Args: + request (Union[google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + request = service.ImportCryptoKeyVersionRequest(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.import_crypto_key_version, + 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 create_import_job(self, + request: Union[service.CreateImportJobRequest, dict] = None, + *, + parent: str = None, + import_job_id: str = None, + import_job: resources.ImportJob = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ImportJob: + r"""Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] + is required. + + Args: + request (Union[google.cloud.kms_v1.types.CreateImportJobRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. + parent (:class:`str`): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the [KeyRing][google.cloud.kms.v1.KeyRing] associated + with the [ImportJobs][google.cloud.kms.v1.ImportJob]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + import_job_id (:class:`str`): + Required. It must be unique within a KeyRing and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``import_job_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + import_job (:class:`google.cloud.kms_v1.types.ImportJob`): + Required. An [ImportJob][google.cloud.kms.v1.ImportJob] + with initial field values. + + This corresponds to the ``import_job`` 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.ImportJob: + 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. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.CreateImportJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if import_job_id is not None: + request.import_job_id = import_job_id + if import_job is not None: + request.import_job = import_job + + # 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_import_job, + 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_crypto_key(self, + request: Union[service.UpdateCryptoKeyRequest, dict] = None, + *, + crypto_key: resources.CryptoKey = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. + crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): + Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] + with updated values. + + This corresponds to the ``crypto_key`` 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.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] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.UpdateCryptoKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if crypto_key is not None: + request.crypto_key = crypto_key + 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_crypto_key, + 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(( + ("crypto_key.name", request.crypto_key.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_crypto_key_version(self, + request: Union[service.UpdateCryptoKeyVersionRequest, dict] = None, + *, + crypto_key_version: resources.CryptoKeyVersion = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Update a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + metadata. + + [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be + changed between + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + and + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + using this method. See + [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] + and + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to move between other states. + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. + crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): + Required. + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with updated values. + + This corresponds to the ``crypto_key_version`` 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.UpdateCryptoKeyVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if crypto_key_version is not None: + request.crypto_key_version = crypto_key_version + 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_crypto_key_version, + 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(( + ("crypto_key_version.name", request.crypto_key_version.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_crypto_key_primary_version(self, + request: Union[service.UpdateCryptoKeyPrimaryVersionRequest, dict] = None, + *, + name: str = None, + crypto_key_version_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Update the version of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Returns an error if called on a key whose purpose is not + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + name (:class:`str`): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_version_id (:class:`str`): + Required. The id of the child + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use as primary. + + This corresponds to the ``crypto_key_version_id`` 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.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] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.UpdateCryptoKeyPrimaryVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if crypto_key_version_id is not None: + request.crypto_key_version_id = crypto_key_version_id + + # 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_crypto_key_primary_version, + 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 destroy_crypto_key_version(self, + request: Union[service.DestroyCryptoKeyVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Schedule a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for + destruction. + + Upon calling this method, + [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] + will be set to + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be set to the time + [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] + in the future. At that time, the + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will + automatically change to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], + and the key material will be irrevocably destroyed. + + Before the + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + is reached, + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + may be called to reverse the process. + + Args: + request (Union[google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to destroy. + + 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.DestroyCryptoKeyVersionRequest(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.destroy_crypto_key_version, + 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 restore_crypto_key_version(self, + request: Union[service.RestoreCryptoKeyVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Restore a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state. + + Upon restoration of the CryptoKeyVersion, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be cleared. + + Args: + request (Union[google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to restore. + + 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 = service.RestoreCryptoKeyVersionRequest(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.restore_crypto_key_version, + 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 encrypt(self, + request: Union[service.EncryptRequest, dict] = None, + *, + name: str = None, + plaintext: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.EncryptResponse: + r"""Encrypts data, so that it can only be recovered by a call to + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Args: + request (Union[google.cloud.kms_v1.types.EncryptRequest, dict]): + The request object. Request message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + name (:class:`str`): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] or + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for encryption. + + If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is + specified, the server will use its [primary + version][google.cloud.kms.v1.CryptoKey.primary]. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + plaintext (:class:`bytes`): + Required. The data to encrypt. Must be no larger than + 64KiB. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For + [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] + keys, the plaintext must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger + than 8KiB. + + This corresponds to the ``plaintext`` 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.EncryptResponse: + Response message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.EncryptRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if plaintext is not None: + request.plaintext = plaintext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.encrypt, + 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 decrypt(self, + request: Union[service.DecryptRequest, dict] = None, + *, + name: str = None, + ciphertext: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.DecryptResponse: + r"""Decrypts data that was protected by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Args: + request (Union[google.cloud.kms_v1.types.DecryptRequest, dict]): + The request object. Request message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + name (:class:`str`): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for + decryption. The server will choose the appropriate + version. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ciphertext (:class:`bytes`): + Required. The encrypted data originally returned in + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + + This corresponds to the ``ciphertext`` 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.DecryptResponse: + Response message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.DecryptRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ciphertext is not None: + request.ciphertext = ciphertext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.decrypt, + 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 asymmetric_sign(self, + request: Union[service.AsymmetricSignRequest, dict] = None, + *, + name: str = None, + digest: service.Digest = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricSignResponse: + r"""Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_SIGN, producing a signature that can be verified with + the public key retrieved from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Args: + request (Union[google.cloud.kms_v1.types.AsymmetricSignRequest, dict]): + The request object. Request message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for signing. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + digest (:class:`google.cloud.kms_v1.types.Digest`): + Optional. The digest of the data to sign. The digest + must be produced with the same digest algorithm as + specified by the key version's + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + + This corresponds to the ``digest`` 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.AsymmetricSignResponse: + Response message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.AsymmetricSignRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if digest is not None: + request.digest = digest + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.asymmetric_sign, + 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 asymmetric_decrypt(self, + request: Union[service.AsymmetricDecryptRequest, dict] = None, + *, + name: str = None, + ciphertext: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricDecryptResponse: + r"""Decrypts data that was encrypted with a public key retrieved + from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] + corresponding to a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_DECRYPT. + + Args: + request (Union[google.cloud.kms_v1.types.AsymmetricDecryptRequest, dict]): + The request object. Request message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for decryption. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ciphertext (:class:`bytes`): + Required. The data encrypted with the named + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + public key using OAEP. + + This corresponds to the ``ciphertext`` 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.AsymmetricDecryptResponse: + Response message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.AsymmetricDecryptRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ciphertext is not None: + request.ciphertext = ciphertext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.asymmetric_decrypt, + 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 mac_sign(self, + request: Union[service.MacSignRequest, dict] = None, + *, + name: str = None, + data: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacSignResponse: + r"""Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + producing a tag that can be verified by another source with the + same key. + + Args: + request (Union[google.cloud.kms_v1.types.MacSignRequest, dict]): + The request object. Request message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for signing. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (:class:`bytes`): + Required. The data to sign. The MAC + tag is computed over this data field + based on the specific algorithm. + + This corresponds to the ``data`` 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.MacSignResponse: + Response message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.MacSignRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mac_sign, + 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 mac_verify(self, + request: Union[service.MacVerifyRequest, dict] = None, + *, + name: str = None, + data: bytes = None, + mac: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacVerifyResponse: + r"""Verifies MAC tag using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + and returns a response that indicates whether or not the + verification was successful. + + Args: + request (Union[google.cloud.kms_v1.types.MacVerifyRequest, dict]): + The request object. Request message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for verification. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (:class:`bytes`): + Required. The data used previously as a + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] + to generate the MAC tag. + + This corresponds to the ``data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mac (:class:`bytes`): + Required. The signature to verify. + This corresponds to the ``mac`` 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.MacVerifyResponse: + Response message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.MacVerifyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + if mac is not None: + request.mac = mac + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.mac_verify, + 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 generate_random_bytes(self, + request: Union[service.GenerateRandomBytesRequest, dict] = None, + *, + location: str = None, + length_bytes: int = None, + protection_level: resources.ProtectionLevel = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateRandomBytesResponse: + r"""Generate random bytes using the Cloud KMS randomness + source in the provided location. + + Args: + request (Union[google.cloud.kms_v1.types.GenerateRandomBytesRequest, dict]): + The request object. Request message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + location (:class:`str`): + The project-specific location in + which to generate random bytes. For + example, "projects/my- + project/locations/us-central1". + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + length_bytes (:class:`int`): + The length in bytes of the amount of + randomness to retrieve. Minimum 8 + bytes, maximum 1024 bytes. + + This corresponds to the ``length_bytes`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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]. + + This corresponds to the ``protection_level`` 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.GenerateRandomBytesResponse: + Response message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = service.GenerateRandomBytesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if length_bytes is not None: + request.length_bytes = length_bytes + if protection_level is not None: + request.protection_level = protection_level + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_random_bytes, + 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(( + ("location", request.location), + )), + ) + + # 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__ = ( + "KeyManagementServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py new file mode 100644 index 00000000..1d8ad469 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py @@ -0,0 +1,3254 @@ +# -*- 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.key_management_service import pagers +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import KeyManagementServiceGrpcTransport +from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport + + +class KeyManagementServiceClientMeta(type): + """Metaclass for the KeyManagementService 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[KeyManagementServiceTransport]] + _transport_registry["grpc"] = KeyManagementServiceGrpcTransport + _transport_registry["grpc_asyncio"] = KeyManagementServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[KeyManagementServiceTransport]: + """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 KeyManagementServiceClient(metaclass=KeyManagementServiceClientMeta): + """Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + """ + + @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: + KeyManagementServiceClient: 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: + KeyManagementServiceClient: 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) -> KeyManagementServiceTransport: + """Returns the transport used by the client instance. + + Returns: + KeyManagementServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str,str]: + """Parses a crypto_key path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str,str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def import_job_path(project: str,location: str,key_ring: str,import_job: str,) -> str: + """Returns a fully-qualified import_job string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format(project=project, location=location, key_ring=key_ring, import_job=import_job, ) + + @staticmethod + def parse_import_job_path(path: str) -> Dict[str,str]: + """Parses a import_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/importJobs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def key_ring_path(project: str,location: str,key_ring: str,) -> str: + """Returns a fully-qualified key_ring string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}".format(project=project, location=location, key_ring=key_ring, ) + + @staticmethod + def parse_key_ring_path(path: str) -> Dict[str,str]: + """Parses a key_ring path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def public_key_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: + """Returns a fully-qualified public_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + + @staticmethod + def parse_public_key_path(path: str) -> Dict[str,str]: + """Parses a public_key path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)/publicKey$", 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, KeyManagementServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the key management 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, KeyManagementServiceTransport]): 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, KeyManagementServiceTransport): + # transport is a KeyManagementServiceTransport 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_key_rings(self, + request: Union[service.ListKeyRingsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListKeyRingsPager: + r"""Lists [KeyRings][google.cloud.kms.v1.KeyRing]. + + Args: + request (Union[google.cloud.kms_v1.types.ListKeyRingsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + parent (str): + Required. The resource name of the location associated + with the [KeyRings][google.cloud.kms.v1.KeyRing], 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.key_management_service.pagers.ListKeyRingsPager: + Response message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.ListKeyRingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListKeyRingsRequest): + request = service.ListKeyRingsRequest(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_key_rings] + + # 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.ListKeyRingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_crypto_keys(self, + request: Union[service.ListCryptoKeysRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCryptoKeysPager: + r"""Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + Args: + request (Union[google.cloud.kms_v1.types.ListCryptoKeysRequest, dict]): + The request object. Request message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + parent (str): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + + 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.key_management_service.pagers.ListCryptoKeysPager: + Response message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.ListCryptoKeysRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListCryptoKeysRequest): + request = service.ListCryptoKeysRequest(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_crypto_keys] + + # 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.ListCryptoKeysPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_crypto_key_versions(self, + request: Union[service.ListCryptoKeyVersionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCryptoKeyVersionsPager: + r"""Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + Args: + request (Union[google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + parent (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in + the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + + 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.key_management_service.pagers.ListCryptoKeyVersionsPager: + Response message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.ListCryptoKeyVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListCryptoKeyVersionsRequest): + request = service.ListCryptoKeyVersionsRequest(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_crypto_key_versions] + + # 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.ListCryptoKeyVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_import_jobs(self, + request: Union[service.ListImportJobsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListImportJobsPager: + r"""Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. + + Args: + request (Union[google.cloud.kms_v1.types.ListImportJobsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + parent (str): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + + 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.key_management_service.pagers.ListImportJobsPager: + Response message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.ListImportJobsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ListImportJobsRequest): + request = service.ListImportJobsRequest(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_import_jobs] + + # 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.ListImportJobsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_key_ring(self, + request: Union[service.GetKeyRingRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyRing: + r"""Returns metadata for a given + [KeyRing][google.cloud.kms.v1.KeyRing]. + + Args: + request (Union[google.cloud.kms_v1.types.GetKeyRingRequest, dict]): + The request object. Request message for + [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. + name (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the [KeyRing][google.cloud.kms.v1.KeyRing] 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.KeyRing: + 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. + # Sanity 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 service.GetKeyRingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetKeyRingRequest): + request = service.GetKeyRingRequest(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_key_ring] + + # 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 get_crypto_key(self, + request: Union[service.GetCryptoKeyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Returns metadata for a given + [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its + [primary][google.cloud.kms.v1.CryptoKey.primary] + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Args: + request (Union[google.cloud.kms_v1.types.GetCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. + name (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] 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.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] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.GetCryptoKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetCryptoKeyRequest): + request = service.GetCryptoKeyRequest(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_crypto_key] + + # 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 get_crypto_key_version(self, + request: Union[service.GetCryptoKeyVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Returns metadata for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Args: + request (Union[google.cloud.kms_v1.types.GetCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.GetCryptoKeyVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetCryptoKeyVersionRequest): + request = service.GetCryptoKeyVersionRequest(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_crypto_key_version] + + # 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 get_public_key(self, + request: Union[service.GetPublicKeyRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.PublicKey: + r"""Returns the public key for the given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] + or + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + Args: + request (Union[google.cloud.kms_v1.types.GetPublicKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key 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.PublicKey: + The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.GetPublicKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetPublicKeyRequest): + request = service.GetPublicKeyRequest(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_public_key] + + # 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 get_import_job(self, + request: Union[service.GetImportJobRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ImportJob: + r"""Returns metadata for a given + [ImportJob][google.cloud.kms.v1.ImportJob]. + + Args: + request (Union[google.cloud.kms_v1.types.GetImportJobRequest, dict]): + The request object. Request message for + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. + name (str): + Required. The [name][google.cloud.kms.v1.ImportJob.name] + of the [ImportJob][google.cloud.kms.v1.ImportJob] 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.ImportJob: + 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. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.GetImportJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetImportJobRequest): + request = service.GetImportJobRequest(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_import_job] + + # 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_key_ring(self, + request: Union[service.CreateKeyRingRequest, dict] = None, + *, + parent: str = None, + key_ring_id: str = None, + key_ring: resources.KeyRing = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyRing: + r"""Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given + Project and Location. + + Args: + request (Union[google.cloud.kms_v1.types.CreateKeyRingRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. + parent (str): + Required. The resource name of the location associated + with the [KeyRings][google.cloud.kms.v1.KeyRing], in the + format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_ring_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 ``key_ring_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_ring (google.cloud.kms_v1.types.KeyRing): + Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with + initial field values. + + This corresponds to the ``key_ring`` 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.KeyRing: + 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. + # Sanity 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: + 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 service.CreateKeyRingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateKeyRingRequest): + request = service.CreateKeyRingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_ring_id is not None: + request.key_ring_id = key_ring_id + if key_ring is not None: + request.key_ring = key_ring + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_key_ring] + + # 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 create_crypto_key(self, + request: Union[service.CreateCryptoKeyRequest, dict] = None, + *, + parent: str = None, + crypto_key_id: str = None, + crypto_key: resources.CryptoKey = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and + [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] + are required. + + Args: + request (Union[google.cloud.kms_v1.types.CreateCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. + parent (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the KeyRing associated with the + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_id (str): + Required. It must be unique within a KeyRing and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``crypto_key_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key (google.cloud.kms_v1.types.CryptoKey): + Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] + with initial field values. + + This corresponds to the ``crypto_key`` 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.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] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.CreateCryptoKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateCryptoKeyRequest): + request = service.CreateCryptoKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if crypto_key_id is not None: + request.crypto_key_id = crypto_key_id + if crypto_key is not None: + request.crypto_key = crypto_key + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_crypto_key] + + # 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 create_crypto_key_version(self, + request: Union[service.CreateCryptoKeyVersionRequest, dict] = None, + *, + parent: str = None, + crypto_key_version: resources.CryptoKeyVersion = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Create a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The server will assign the next sequential id. If unset, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. + + Args: + request (Union[google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. + parent (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] + associated with the + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): + Required. A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with initial field values. + + This corresponds to the ``crypto_key_version`` 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.CreateCryptoKeyVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateCryptoKeyVersionRequest): + request = service.CreateCryptoKeyVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if crypto_key_version is not None: + request.crypto_key_version = crypto_key_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_crypto_key_version] + + # 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 import_crypto_key_version(self, + request: Union[service.ImportCryptoKeyVersionRequest, dict] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Args: + request (Union[google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a service.ImportCryptoKeyVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.ImportCryptoKeyVersionRequest): + request = service.ImportCryptoKeyVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_crypto_key_version] + + # 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 create_import_job(self, + request: Union[service.CreateImportJobRequest, dict] = None, + *, + parent: str = None, + import_job_id: str = None, + import_job: resources.ImportJob = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ImportJob: + r"""Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] + is required. + + Args: + request (Union[google.cloud.kms_v1.types.CreateImportJobRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. + parent (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the [KeyRing][google.cloud.kms.v1.KeyRing] associated + with the [ImportJobs][google.cloud.kms.v1.ImportJob]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + import_job_id (str): + Required. It must be unique within a KeyRing and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``import_job_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + import_job (google.cloud.kms_v1.types.ImportJob): + Required. An [ImportJob][google.cloud.kms.v1.ImportJob] + with initial field values. + + This corresponds to the ``import_job`` 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.ImportJob: + 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. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.CreateImportJobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.CreateImportJobRequest): + request = service.CreateImportJobRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if import_job_id is not None: + request.import_job_id = import_job_id + if import_job is not None: + request.import_job = import_job + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_import_job] + + # 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_crypto_key(self, + request: Union[service.UpdateCryptoKeyRequest, dict] = None, + *, + crypto_key: resources.CryptoKey = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. + crypto_key (google.cloud.kms_v1.types.CryptoKey): + Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] + with updated values. + + This corresponds to the ``crypto_key`` 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.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] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.UpdateCryptoKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateCryptoKeyRequest): + request = service.UpdateCryptoKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if crypto_key is not None: + request.crypto_key = crypto_key + 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_crypto_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("crypto_key.name", request.crypto_key.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_crypto_key_version(self, + request: Union[service.UpdateCryptoKeyVersionRequest, dict] = None, + *, + crypto_key_version: resources.CryptoKeyVersion = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Update a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + metadata. + + [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be + changed between + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + and + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + using this method. See + [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] + and + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to move between other states. + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): + Required. + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with updated values. + + This corresponds to the ``crypto_key_version`` 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.UpdateCryptoKeyVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateCryptoKeyVersionRequest): + request = service.UpdateCryptoKeyVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if crypto_key_version is not None: + request.crypto_key_version = crypto_key_version + 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_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("crypto_key_version.name", request.crypto_key_version.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_crypto_key_primary_version(self, + request: Union[service.UpdateCryptoKeyPrimaryVersionRequest, dict] = None, + *, + name: str = None, + crypto_key_version_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Update the version of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Returns an error if called on a key whose purpose is not + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_version_id (str): + Required. The id of the child + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use as primary. + + This corresponds to the ``crypto_key_version_id`` 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.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] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.UpdateCryptoKeyPrimaryVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.UpdateCryptoKeyPrimaryVersionRequest): + request = service.UpdateCryptoKeyPrimaryVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if crypto_key_version_id is not None: + request.crypto_key_version_id = crypto_key_version_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_crypto_key_primary_version] + + # 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 destroy_crypto_key_version(self, + request: Union[service.DestroyCryptoKeyVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Schedule a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for + destruction. + + Upon calling this method, + [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] + will be set to + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be set to the time + [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] + in the future. At that time, the + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will + automatically change to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], + and the key material will be irrevocably destroyed. + + Before the + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + is reached, + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + may be called to reverse the process. + + Args: + request (Union[google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to destroy. + + 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.DestroyCryptoKeyVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DestroyCryptoKeyVersionRequest): + request = service.DestroyCryptoKeyVersionRequest(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.destroy_crypto_key_version] + + # 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 restore_crypto_key_version(self, + request: Union[service.RestoreCryptoKeyVersionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Restore a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state. + + Upon restoration of the CryptoKeyVersion, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be cleared. + + Args: + request (Union[google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to restore. + + 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.CryptoKeyVersion: + 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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # Sanity 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 service.RestoreCryptoKeyVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.RestoreCryptoKeyVersionRequest): + request = service.RestoreCryptoKeyVersionRequest(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.restore_crypto_key_version] + + # 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 encrypt(self, + request: Union[service.EncryptRequest, dict] = None, + *, + name: str = None, + plaintext: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.EncryptResponse: + r"""Encrypts data, so that it can only be recovered by a call to + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Args: + request (Union[google.cloud.kms_v1.types.EncryptRequest, dict]): + The request object. Request message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] or + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for encryption. + + If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is + specified, the server will use its [primary + version][google.cloud.kms.v1.CryptoKey.primary]. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + plaintext (bytes): + Required. The data to encrypt. Must be no larger than + 64KiB. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For + [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] + keys, the plaintext must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger + than 8KiB. + + This corresponds to the ``plaintext`` 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.EncryptResponse: + Response message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.EncryptRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.EncryptRequest): + request = service.EncryptRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if plaintext is not None: + request.plaintext = plaintext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.encrypt] + + # 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 decrypt(self, + request: Union[service.DecryptRequest, dict] = None, + *, + name: str = None, + ciphertext: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.DecryptResponse: + r"""Decrypts data that was protected by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Args: + request (Union[google.cloud.kms_v1.types.DecryptRequest, dict]): + The request object. Request message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for + decryption. The server will choose the appropriate + version. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ciphertext (bytes): + Required. The encrypted data originally returned in + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + + This corresponds to the ``ciphertext`` 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.DecryptResponse: + Response message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.DecryptRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.DecryptRequest): + request = service.DecryptRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ciphertext is not None: + request.ciphertext = ciphertext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.decrypt] + + # 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 asymmetric_sign(self, + request: Union[service.AsymmetricSignRequest, dict] = None, + *, + name: str = None, + digest: service.Digest = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricSignResponse: + r"""Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_SIGN, producing a signature that can be verified with + the public key retrieved from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Args: + request (Union[google.cloud.kms_v1.types.AsymmetricSignRequest, dict]): + The request object. Request message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for signing. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + digest (google.cloud.kms_v1.types.Digest): + Optional. The digest of the data to sign. The digest + must be produced with the same digest algorithm as + specified by the key version's + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + + This corresponds to the ``digest`` 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.AsymmetricSignResponse: + Response message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.AsymmetricSignRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.AsymmetricSignRequest): + request = service.AsymmetricSignRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if digest is not None: + request.digest = digest + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.asymmetric_sign] + + # 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 asymmetric_decrypt(self, + request: Union[service.AsymmetricDecryptRequest, dict] = None, + *, + name: str = None, + ciphertext: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricDecryptResponse: + r"""Decrypts data that was encrypted with a public key retrieved + from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] + corresponding to a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_DECRYPT. + + Args: + request (Union[google.cloud.kms_v1.types.AsymmetricDecryptRequest, dict]): + The request object. Request message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for decryption. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ciphertext (bytes): + Required. The data encrypted with the named + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + public key using OAEP. + + This corresponds to the ``ciphertext`` 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.AsymmetricDecryptResponse: + Response message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.AsymmetricDecryptRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.AsymmetricDecryptRequest): + request = service.AsymmetricDecryptRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ciphertext is not None: + request.ciphertext = ciphertext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.asymmetric_decrypt] + + # 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 mac_sign(self, + request: Union[service.MacSignRequest, dict] = None, + *, + name: str = None, + data: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacSignResponse: + r"""Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + producing a tag that can be verified by another source with the + same key. + + Args: + request (Union[google.cloud.kms_v1.types.MacSignRequest, dict]): + The request object. Request message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for signing. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (bytes): + Required. The data to sign. The MAC + tag is computed over this data field + based on the specific algorithm. + + This corresponds to the ``data`` 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.MacSignResponse: + Response message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.MacSignRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.MacSignRequest): + request = service.MacSignRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mac_sign] + + # 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 mac_verify(self, + request: Union[service.MacVerifyRequest, dict] = None, + *, + name: str = None, + data: bytes = None, + mac: bytes = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacVerifyResponse: + r"""Verifies MAC tag using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + and returns a response that indicates whether or not the + verification was successful. + + Args: + request (Union[google.cloud.kms_v1.types.MacVerifyRequest, dict]): + The request object. Request message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for verification. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (bytes): + Required. The data used previously as a + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] + to generate the MAC tag. + + This corresponds to the ``data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mac (bytes): + Required. The signature to verify. + This corresponds to the ``mac`` 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.MacVerifyResponse: + Response message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.MacVerifyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.MacVerifyRequest): + request = service.MacVerifyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + if mac is not None: + request.mac = mac + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mac_verify] + + # 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 generate_random_bytes(self, + request: Union[service.GenerateRandomBytesRequest, dict] = None, + *, + location: str = None, + length_bytes: int = None, + protection_level: resources.ProtectionLevel = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateRandomBytesResponse: + r"""Generate random bytes using the Cloud KMS randomness + source in the provided location. + + Args: + request (Union[google.cloud.kms_v1.types.GenerateRandomBytesRequest, dict]): + The request object. Request message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + location (str): + The project-specific location in + which to generate random bytes. For + example, "projects/my- + project/locations/us-central1". + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + length_bytes (int): + The length in bytes of the amount of + randomness to retrieve. Minimum 8 + bytes, maximum 1024 bytes. + + This corresponds to the ``length_bytes`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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]. + + This corresponds to the ``protection_level`` 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.GenerateRandomBytesResponse: + Response message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + """ + # Create or coerce a protobuf request object. + # Sanity 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: + 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 service.GenerateRandomBytesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GenerateRandomBytesRequest): + request = service.GenerateRandomBytesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if length_bytes is not None: + request.length_bytes = length_bytes + if protection_level is not None: + request.protection_level = protection_level + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_random_bytes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("location", request.location), + )), + ) + + # 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__ = ( + "KeyManagementServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/pagers.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/pagers.py new file mode 100644 index 00000000..0be3e030 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/pagers.py @@ -0,0 +1,503 @@ +# -*- 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 resources +from google.cloud.kms_v1.types import service + + +class ListKeyRingsPager: + """A pager for iterating through ``list_key_rings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``key_rings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListKeyRings`` requests and continue to iterate + through the ``key_rings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` + 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[..., service.ListKeyRingsResponse], + request: service.ListKeyRingsRequest, + response: service.ListKeyRingsResponse, + *, + 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.ListKeyRingsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListKeyRingsResponse): + 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 = service.ListKeyRingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListKeyRingsResponse]: + 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[resources.KeyRing]: + for page in self.pages: + yield from page.key_rings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKeyRingsAsyncPager: + """A pager for iterating through ``list_key_rings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``key_rings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKeyRings`` requests and continue to iterate + through the ``key_rings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` + 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[service.ListKeyRingsResponse]], + request: service.ListKeyRingsRequest, + response: service.ListKeyRingsResponse, + *, + 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.ListKeyRingsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListKeyRingsResponse): + 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 = service.ListKeyRingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListKeyRingsResponse]: + 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[resources.KeyRing]: + async def async_generator(): + async for page in self.pages: + for response in page.key_rings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCryptoKeysPager: + """A pager for iterating through ``list_crypto_keys`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crypto_keys`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCryptoKeys`` requests and continue to iterate + through the ``crypto_keys`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` + 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[..., service.ListCryptoKeysResponse], + request: service.ListCryptoKeysRequest, + response: service.ListCryptoKeysResponse, + *, + 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.ListCryptoKeysRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListCryptoKeysResponse): + 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 = service.ListCryptoKeysRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListCryptoKeysResponse]: + 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[resources.CryptoKey]: + for page in self.pages: + yield from page.crypto_keys + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCryptoKeysAsyncPager: + """A pager for iterating through ``list_crypto_keys`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crypto_keys`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCryptoKeys`` requests and continue to iterate + through the ``crypto_keys`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` + 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[service.ListCryptoKeysResponse]], + request: service.ListCryptoKeysRequest, + response: service.ListCryptoKeysResponse, + *, + 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.ListCryptoKeysRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListCryptoKeysResponse): + 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 = service.ListCryptoKeysRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListCryptoKeysResponse]: + 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[resources.CryptoKey]: + async def async_generator(): + async for page in self.pages: + for response in page.crypto_keys: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCryptoKeyVersionsPager: + """A pager for iterating through ``list_crypto_key_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crypto_key_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCryptoKeyVersions`` requests and continue to iterate + through the ``crypto_key_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` + 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[..., service.ListCryptoKeyVersionsResponse], + request: service.ListCryptoKeyVersionsRequest, + response: service.ListCryptoKeyVersionsResponse, + *, + 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.ListCryptoKeyVersionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): + 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 = service.ListCryptoKeyVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListCryptoKeyVersionsResponse]: + 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[resources.CryptoKeyVersion]: + for page in self.pages: + yield from page.crypto_key_versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCryptoKeyVersionsAsyncPager: + """A pager for iterating through ``list_crypto_key_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crypto_key_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCryptoKeyVersions`` requests and continue to iterate + through the ``crypto_key_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` + 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[service.ListCryptoKeyVersionsResponse]], + request: service.ListCryptoKeyVersionsRequest, + response: service.ListCryptoKeyVersionsResponse, + *, + 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.ListCryptoKeyVersionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): + 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 = service.ListCryptoKeyVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListCryptoKeyVersionsResponse]: + 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[resources.CryptoKeyVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.crypto_key_versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListImportJobsPager: + """A pager for iterating through ``list_import_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``import_jobs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListImportJobs`` requests and continue to iterate + through the ``import_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` + 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[..., service.ListImportJobsResponse], + request: service.ListImportJobsRequest, + response: service.ListImportJobsResponse, + *, + 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.ListImportJobsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListImportJobsResponse): + 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 = service.ListImportJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListImportJobsResponse]: + 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[resources.ImportJob]: + for page in self.pages: + yield from page.import_jobs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListImportJobsAsyncPager: + """A pager for iterating through ``list_import_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``import_jobs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListImportJobs`` requests and continue to iterate + through the ``import_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` + 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[service.ListImportJobsResponse]], + request: service.ListImportJobsRequest, + response: service.ListImportJobsResponse, + *, + 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.ListImportJobsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListImportJobsResponse): + 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 = service.ListImportJobsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListImportJobsResponse]: + 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[resources.ImportJob]: + async def async_generator(): + async for page in self.pages: + for response in page.import_jobs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py new file mode 100644 index 00000000..291c245a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_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 KeyManagementServiceTransport +from .grpc import KeyManagementServiceGrpcTransport +from .grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[KeyManagementServiceTransport]] +_transport_registry['grpc'] = KeyManagementServiceGrpcTransport +_transport_registry['grpc_asyncio'] = KeyManagementServiceGrpcAsyncIOTransport + +__all__ = ( + 'KeyManagementServiceTransport', + 'KeyManagementServiceGrpcTransport', + 'KeyManagementServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py new file mode 100644 index 00000000..0b72c663 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py @@ -0,0 +1,696 @@ +# -*- 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 resources +from google.cloud.kms_v1.types import 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 KeyManagementServiceTransport(abc.ABC): + """Abstract transport class for KeyManagementService.""" + + 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_key_rings: gapic_v1.method.wrap_method( + self.list_key_rings, + 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.list_crypto_keys: gapic_v1.method.wrap_method( + self.list_crypto_keys, + 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.list_crypto_key_versions: gapic_v1.method.wrap_method( + self.list_crypto_key_versions, + 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.list_import_jobs: gapic_v1.method.wrap_method( + self.list_import_jobs, + 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_key_ring: gapic_v1.method.wrap_method( + self.get_key_ring, + 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_crypto_key: gapic_v1.method.wrap_method( + self.get_crypto_key, + 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_crypto_key_version: gapic_v1.method.wrap_method( + self.get_crypto_key_version, + 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_public_key: gapic_v1.method.wrap_method( + self.get_public_key, + 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_import_job: gapic_v1.method.wrap_method( + self.get_import_job, + 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_key_ring: gapic_v1.method.wrap_method( + self.create_key_ring, + 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_crypto_key: gapic_v1.method.wrap_method( + self.create_crypto_key, + 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_crypto_key_version: gapic_v1.method.wrap_method( + self.create_crypto_key_version, + default_timeout=60.0, + client_info=client_info, + ), + self.import_crypto_key_version: gapic_v1.method.wrap_method( + self.import_crypto_key_version, + default_timeout=60.0, + client_info=client_info, + ), + self.create_import_job: gapic_v1.method.wrap_method( + self.create_import_job, + 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_crypto_key: gapic_v1.method.wrap_method( + self.update_crypto_key, + 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_crypto_key_version: gapic_v1.method.wrap_method( + self.update_crypto_key_version, + 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_crypto_key_primary_version: gapic_v1.method.wrap_method( + self.update_crypto_key_primary_version, + 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.destroy_crypto_key_version: gapic_v1.method.wrap_method( + self.destroy_crypto_key_version, + 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.restore_crypto_key_version: gapic_v1.method.wrap_method( + self.restore_crypto_key_version, + 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.encrypt: gapic_v1.method.wrap_method( + self.encrypt, + 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.decrypt: gapic_v1.method.wrap_method( + self.decrypt, + 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.asymmetric_sign: gapic_v1.method.wrap_method( + self.asymmetric_sign, + 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.asymmetric_decrypt: gapic_v1.method.wrap_method( + self.asymmetric_decrypt, + 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.mac_sign: gapic_v1.method.wrap_method( + self.mac_sign, + 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.mac_verify: gapic_v1.method.wrap_method( + self.mac_verify, + 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.generate_random_bytes: gapic_v1.method.wrap_method( + self.generate_random_bytes, + 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_key_rings(self) -> Callable[ + [service.ListKeyRingsRequest], + Union[ + service.ListKeyRingsResponse, + Awaitable[service.ListKeyRingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_crypto_keys(self) -> Callable[ + [service.ListCryptoKeysRequest], + Union[ + service.ListCryptoKeysResponse, + Awaitable[service.ListCryptoKeysResponse] + ]]: + raise NotImplementedError() + + @property + def list_crypto_key_versions(self) -> Callable[ + [service.ListCryptoKeyVersionsRequest], + Union[ + service.ListCryptoKeyVersionsResponse, + Awaitable[service.ListCryptoKeyVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def list_import_jobs(self) -> Callable[ + [service.ListImportJobsRequest], + Union[ + service.ListImportJobsResponse, + Awaitable[service.ListImportJobsResponse] + ]]: + raise NotImplementedError() + + @property + def get_key_ring(self) -> Callable[ + [service.GetKeyRingRequest], + Union[ + resources.KeyRing, + Awaitable[resources.KeyRing] + ]]: + raise NotImplementedError() + + @property + def get_crypto_key(self) -> Callable[ + [service.GetCryptoKeyRequest], + Union[ + resources.CryptoKey, + Awaitable[resources.CryptoKey] + ]]: + raise NotImplementedError() + + @property + def get_crypto_key_version(self) -> Callable[ + [service.GetCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def get_public_key(self) -> Callable[ + [service.GetPublicKeyRequest], + Union[ + resources.PublicKey, + Awaitable[resources.PublicKey] + ]]: + raise NotImplementedError() + + @property + def get_import_job(self) -> Callable[ + [service.GetImportJobRequest], + Union[ + resources.ImportJob, + Awaitable[resources.ImportJob] + ]]: + raise NotImplementedError() + + @property + def create_key_ring(self) -> Callable[ + [service.CreateKeyRingRequest], + Union[ + resources.KeyRing, + Awaitable[resources.KeyRing] + ]]: + raise NotImplementedError() + + @property + def create_crypto_key(self) -> Callable[ + [service.CreateCryptoKeyRequest], + Union[ + resources.CryptoKey, + Awaitable[resources.CryptoKey] + ]]: + raise NotImplementedError() + + @property + def create_crypto_key_version(self) -> Callable[ + [service.CreateCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def import_crypto_key_version(self) -> Callable[ + [service.ImportCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def create_import_job(self) -> Callable[ + [service.CreateImportJobRequest], + Union[ + resources.ImportJob, + Awaitable[resources.ImportJob] + ]]: + raise NotImplementedError() + + @property + def update_crypto_key(self) -> Callable[ + [service.UpdateCryptoKeyRequest], + Union[ + resources.CryptoKey, + Awaitable[resources.CryptoKey] + ]]: + raise NotImplementedError() + + @property + def update_crypto_key_version(self) -> Callable[ + [service.UpdateCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def update_crypto_key_primary_version(self) -> Callable[ + [service.UpdateCryptoKeyPrimaryVersionRequest], + Union[ + resources.CryptoKey, + Awaitable[resources.CryptoKey] + ]]: + raise NotImplementedError() + + @property + def destroy_crypto_key_version(self) -> Callable[ + [service.DestroyCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def restore_crypto_key_version(self) -> Callable[ + [service.RestoreCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def encrypt(self) -> Callable[ + [service.EncryptRequest], + Union[ + service.EncryptResponse, + Awaitable[service.EncryptResponse] + ]]: + raise NotImplementedError() + + @property + def decrypt(self) -> Callable[ + [service.DecryptRequest], + Union[ + service.DecryptResponse, + Awaitable[service.DecryptResponse] + ]]: + raise NotImplementedError() + + @property + def asymmetric_sign(self) -> Callable[ + [service.AsymmetricSignRequest], + Union[ + service.AsymmetricSignResponse, + Awaitable[service.AsymmetricSignResponse] + ]]: + raise NotImplementedError() + + @property + def asymmetric_decrypt(self) -> Callable[ + [service.AsymmetricDecryptRequest], + Union[ + service.AsymmetricDecryptResponse, + Awaitable[service.AsymmetricDecryptResponse] + ]]: + raise NotImplementedError() + + @property + def mac_sign(self) -> Callable[ + [service.MacSignRequest], + Union[ + service.MacSignResponse, + Awaitable[service.MacSignResponse] + ]]: + raise NotImplementedError() + + @property + def mac_verify(self) -> Callable[ + [service.MacVerifyRequest], + Union[ + service.MacVerifyResponse, + Awaitable[service.MacVerifyResponse] + ]]: + raise NotImplementedError() + + @property + def generate_random_bytes(self) -> Callable[ + [service.GenerateRandomBytesRequest], + Union[ + service.GenerateRandomBytesResponse, + Awaitable[service.GenerateRandomBytesResponse] + ]]: + 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__ = ( + 'KeyManagementServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py new file mode 100644 index 00000000..c360a411 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -0,0 +1,1115 @@ +# -*- 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 resources +from google.cloud.kms_v1.types import service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO + + +class KeyManagementServiceGrpcTransport(KeyManagementServiceTransport): + """gRPC backend transport for KeyManagementService. + + Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + + 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, + credentials=self._credentials, + credentials_file=credentials_file, + 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_key_rings(self) -> Callable[ + [service.ListKeyRingsRequest], + service.ListKeyRingsResponse]: + r"""Return a callable for the list key rings method over gRPC. + + Lists [KeyRings][google.cloud.kms.v1.KeyRing]. + + Returns: + Callable[[~.ListKeyRingsRequest], + ~.ListKeyRingsResponse]: + 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_key_rings' not in self._stubs: + self._stubs['list_key_rings'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListKeyRings', + request_serializer=service.ListKeyRingsRequest.serialize, + response_deserializer=service.ListKeyRingsResponse.deserialize, + ) + return self._stubs['list_key_rings'] + + @property + def list_crypto_keys(self) -> Callable[ + [service.ListCryptoKeysRequest], + service.ListCryptoKeysResponse]: + r"""Return a callable for the list crypto keys method over gRPC. + + Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.ListCryptoKeysRequest], + ~.ListCryptoKeysResponse]: + 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_crypto_keys' not in self._stubs: + self._stubs['list_crypto_keys'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys', + request_serializer=service.ListCryptoKeysRequest.serialize, + response_deserializer=service.ListCryptoKeysResponse.deserialize, + ) + return self._stubs['list_crypto_keys'] + + @property + def list_crypto_key_versions(self) -> Callable[ + [service.ListCryptoKeyVersionsRequest], + service.ListCryptoKeyVersionsResponse]: + r"""Return a callable for the list crypto key versions method over gRPC. + + Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.ListCryptoKeyVersionsRequest], + ~.ListCryptoKeyVersionsResponse]: + 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_crypto_key_versions' not in self._stubs: + self._stubs['list_crypto_key_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions', + request_serializer=service.ListCryptoKeyVersionsRequest.serialize, + response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize, + ) + return self._stubs['list_crypto_key_versions'] + + @property + def list_import_jobs(self) -> Callable[ + [service.ListImportJobsRequest], + service.ListImportJobsResponse]: + r"""Return a callable for the list import jobs method over gRPC. + + Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. + + Returns: + Callable[[~.ListImportJobsRequest], + ~.ListImportJobsResponse]: + 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_import_jobs' not in self._stubs: + self._stubs['list_import_jobs'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListImportJobs', + request_serializer=service.ListImportJobsRequest.serialize, + response_deserializer=service.ListImportJobsResponse.deserialize, + ) + return self._stubs['list_import_jobs'] + + @property + def get_key_ring(self) -> Callable[ + [service.GetKeyRingRequest], + resources.KeyRing]: + r"""Return a callable for the get key ring method over gRPC. + + Returns metadata for a given + [KeyRing][google.cloud.kms.v1.KeyRing]. + + Returns: + Callable[[~.GetKeyRingRequest], + ~.KeyRing]: + 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_key_ring' not in self._stubs: + self._stubs['get_key_ring'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetKeyRing', + request_serializer=service.GetKeyRingRequest.serialize, + response_deserializer=resources.KeyRing.deserialize, + ) + return self._stubs['get_key_ring'] + + @property + def get_crypto_key(self) -> Callable[ + [service.GetCryptoKeyRequest], + resources.CryptoKey]: + r"""Return a callable for the get crypto key method over gRPC. + + Returns metadata for a given + [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its + [primary][google.cloud.kms.v1.CryptoKey.primary] + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.GetCryptoKeyRequest], + ~.CryptoKey]: + 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_crypto_key' not in self._stubs: + self._stubs['get_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetCryptoKey', + request_serializer=service.GetCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['get_crypto_key'] + + @property + def get_crypto_key_version(self) -> Callable[ + [service.GetCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the get crypto key version method over gRPC. + + Returns metadata for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.GetCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + 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_crypto_key_version' not in self._stubs: + self._stubs['get_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion', + request_serializer=service.GetCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['get_crypto_key_version'] + + @property + def get_public_key(self) -> Callable[ + [service.GetPublicKeyRequest], + resources.PublicKey]: + r"""Return a callable for the get public key method over gRPC. + + Returns the public key for the given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] + or + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + Returns: + Callable[[~.GetPublicKeyRequest], + ~.PublicKey]: + 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_public_key' not in self._stubs: + self._stubs['get_public_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetPublicKey', + request_serializer=service.GetPublicKeyRequest.serialize, + response_deserializer=resources.PublicKey.deserialize, + ) + return self._stubs['get_public_key'] + + @property + def get_import_job(self) -> Callable[ + [service.GetImportJobRequest], + resources.ImportJob]: + r"""Return a callable for the get import job method over gRPC. + + Returns metadata for a given + [ImportJob][google.cloud.kms.v1.ImportJob]. + + Returns: + Callable[[~.GetImportJobRequest], + ~.ImportJob]: + 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_import_job' not in self._stubs: + self._stubs['get_import_job'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetImportJob', + request_serializer=service.GetImportJobRequest.serialize, + response_deserializer=resources.ImportJob.deserialize, + ) + return self._stubs['get_import_job'] + + @property + def create_key_ring(self) -> Callable[ + [service.CreateKeyRingRequest], + resources.KeyRing]: + r"""Return a callable for the create key ring method over gRPC. + + Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given + Project and Location. + + Returns: + Callable[[~.CreateKeyRingRequest], + ~.KeyRing]: + 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_key_ring' not in self._stubs: + self._stubs['create_key_ring'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateKeyRing', + request_serializer=service.CreateKeyRingRequest.serialize, + response_deserializer=resources.KeyRing.deserialize, + ) + return self._stubs['create_key_ring'] + + @property + def create_crypto_key(self) -> Callable[ + [service.CreateCryptoKeyRequest], + resources.CryptoKey]: + r"""Return a callable for the create crypto key method over gRPC. + + Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and + [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] + are required. + + Returns: + Callable[[~.CreateCryptoKeyRequest], + ~.CryptoKey]: + 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_crypto_key' not in self._stubs: + self._stubs['create_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey', + request_serializer=service.CreateCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['create_crypto_key'] + + @property + def create_crypto_key_version(self) -> Callable[ + [service.CreateCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the create crypto key version method over gRPC. + + Create a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The server will assign the next sequential id. If unset, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. + + Returns: + Callable[[~.CreateCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + 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_crypto_key_version' not in self._stubs: + self._stubs['create_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion', + request_serializer=service.CreateCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['create_crypto_key_version'] + + @property + def import_crypto_key_version(self) -> Callable[ + [service.ImportCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the import crypto key version method over gRPC. + + Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.ImportCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + 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 'import_crypto_key_version' not in self._stubs: + self._stubs['import_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion', + request_serializer=service.ImportCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['import_crypto_key_version'] + + @property + def create_import_job(self) -> Callable[ + [service.CreateImportJobRequest], + resources.ImportJob]: + r"""Return a callable for the create import job method over gRPC. + + Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] + is required. + + Returns: + Callable[[~.CreateImportJobRequest], + ~.ImportJob]: + 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_import_job' not in self._stubs: + self._stubs['create_import_job'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateImportJob', + request_serializer=service.CreateImportJobRequest.serialize, + response_deserializer=resources.ImportJob.deserialize, + ) + return self._stubs['create_import_job'] + + @property + def update_crypto_key(self) -> Callable[ + [service.UpdateCryptoKeyRequest], + resources.CryptoKey]: + r"""Return a callable for the update crypto key method over gRPC. + + Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.UpdateCryptoKeyRequest], + ~.CryptoKey]: + 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_crypto_key' not in self._stubs: + self._stubs['update_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey', + request_serializer=service.UpdateCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['update_crypto_key'] + + @property + def update_crypto_key_version(self) -> Callable[ + [service.UpdateCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the update crypto key version method over gRPC. + + Update a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + metadata. + + [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be + changed between + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + and + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + using this method. See + [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] + and + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to move between other states. + + Returns: + Callable[[~.UpdateCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + 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_crypto_key_version' not in self._stubs: + self._stubs['update_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion', + request_serializer=service.UpdateCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['update_crypto_key_version'] + + @property + def update_crypto_key_primary_version(self) -> Callable[ + [service.UpdateCryptoKeyPrimaryVersionRequest], + resources.CryptoKey]: + r"""Return a callable for the update crypto key primary + version method over gRPC. + + Update the version of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Returns an error if called on a key whose purpose is not + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.UpdateCryptoKeyPrimaryVersionRequest], + ~.CryptoKey]: + 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_crypto_key_primary_version' not in self._stubs: + self._stubs['update_crypto_key_primary_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion', + request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['update_crypto_key_primary_version'] + + @property + def destroy_crypto_key_version(self) -> Callable[ + [service.DestroyCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the destroy crypto key version method over gRPC. + + Schedule a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for + destruction. + + Upon calling this method, + [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] + will be set to + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be set to the time + [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] + in the future. At that time, the + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will + automatically change to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], + and the key material will be irrevocably destroyed. + + Before the + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + is reached, + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + may be called to reverse the process. + + Returns: + Callable[[~.DestroyCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + 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 'destroy_crypto_key_version' not in self._stubs: + self._stubs['destroy_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion', + request_serializer=service.DestroyCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['destroy_crypto_key_version'] + + @property + def restore_crypto_key_version(self) -> Callable[ + [service.RestoreCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the restore crypto key version method over gRPC. + + Restore a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state. + + Upon restoration of the CryptoKeyVersion, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be cleared. + + Returns: + Callable[[~.RestoreCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + 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 'restore_crypto_key_version' not in self._stubs: + self._stubs['restore_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion', + request_serializer=service.RestoreCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['restore_crypto_key_version'] + + @property + def encrypt(self) -> Callable[ + [service.EncryptRequest], + service.EncryptResponse]: + r"""Return a callable for the encrypt method over gRPC. + + Encrypts data, so that it can only be recovered by a call to + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.EncryptRequest], + ~.EncryptResponse]: + 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 'encrypt' not in self._stubs: + self._stubs['encrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/Encrypt', + request_serializer=service.EncryptRequest.serialize, + response_deserializer=service.EncryptResponse.deserialize, + ) + return self._stubs['encrypt'] + + @property + def decrypt(self) -> Callable[ + [service.DecryptRequest], + service.DecryptResponse]: + r"""Return a callable for the decrypt method over gRPC. + + Decrypts data that was protected by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.DecryptRequest], + ~.DecryptResponse]: + 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 'decrypt' not in self._stubs: + self._stubs['decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/Decrypt', + request_serializer=service.DecryptRequest.serialize, + response_deserializer=service.DecryptResponse.deserialize, + ) + return self._stubs['decrypt'] + + @property + def asymmetric_sign(self) -> Callable[ + [service.AsymmetricSignRequest], + service.AsymmetricSignResponse]: + r"""Return a callable for the asymmetric sign method over gRPC. + + Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_SIGN, producing a signature that can be verified with + the public key retrieved from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Returns: + Callable[[~.AsymmetricSignRequest], + ~.AsymmetricSignResponse]: + 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 'asymmetric_sign' not in self._stubs: + self._stubs['asymmetric_sign'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/AsymmetricSign', + request_serializer=service.AsymmetricSignRequest.serialize, + response_deserializer=service.AsymmetricSignResponse.deserialize, + ) + return self._stubs['asymmetric_sign'] + + @property + def asymmetric_decrypt(self) -> Callable[ + [service.AsymmetricDecryptRequest], + service.AsymmetricDecryptResponse]: + r"""Return a callable for the asymmetric decrypt method over gRPC. + + Decrypts data that was encrypted with a public key retrieved + from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] + corresponding to a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_DECRYPT. + + Returns: + Callable[[~.AsymmetricDecryptRequest], + ~.AsymmetricDecryptResponse]: + 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 'asymmetric_decrypt' not in self._stubs: + self._stubs['asymmetric_decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt', + request_serializer=service.AsymmetricDecryptRequest.serialize, + response_deserializer=service.AsymmetricDecryptResponse.deserialize, + ) + return self._stubs['asymmetric_decrypt'] + + @property + def mac_sign(self) -> Callable[ + [service.MacSignRequest], + service.MacSignResponse]: + r"""Return a callable for the mac sign method over gRPC. + + Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + producing a tag that can be verified by another source with the + same key. + + Returns: + Callable[[~.MacSignRequest], + ~.MacSignResponse]: + 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 'mac_sign' not in self._stubs: + self._stubs['mac_sign'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/MacSign', + request_serializer=service.MacSignRequest.serialize, + response_deserializer=service.MacSignResponse.deserialize, + ) + return self._stubs['mac_sign'] + + @property + def mac_verify(self) -> Callable[ + [service.MacVerifyRequest], + service.MacVerifyResponse]: + r"""Return a callable for the mac verify method over gRPC. + + Verifies MAC tag using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + and returns a response that indicates whether or not the + verification was successful. + + Returns: + Callable[[~.MacVerifyRequest], + ~.MacVerifyResponse]: + 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 'mac_verify' not in self._stubs: + self._stubs['mac_verify'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/MacVerify', + request_serializer=service.MacVerifyRequest.serialize, + response_deserializer=service.MacVerifyResponse.deserialize, + ) + return self._stubs['mac_verify'] + + @property + def generate_random_bytes(self) -> Callable[ + [service.GenerateRandomBytesRequest], + service.GenerateRandomBytesResponse]: + r"""Return a callable for the generate random bytes method over gRPC. + + Generate random bytes using the Cloud KMS randomness + source in the provided location. + + Returns: + Callable[[~.GenerateRandomBytesRequest], + ~.GenerateRandomBytesResponse]: + 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 'generate_random_bytes' not in self._stubs: + self._stubs['generate_random_bytes'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes', + request_serializer=service.GenerateRandomBytesRequest.serialize, + response_deserializer=service.GenerateRandomBytesResponse.deserialize, + ) + return self._stubs['generate_random_bytes'] + + @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__ = ( + 'KeyManagementServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..169f387e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -0,0 +1,1120 @@ +# -*- 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 resources +from google.cloud.kms_v1.types import service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import KeyManagementServiceGrpcTransport + + +class KeyManagementServiceGrpcAsyncIOTransport(KeyManagementServiceTransport): + """gRPC AsyncIO backend transport for KeyManagementService. + + Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + + 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, + credentials=self._credentials, + credentials_file=credentials_file, + 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_key_rings(self) -> Callable[ + [service.ListKeyRingsRequest], + Awaitable[service.ListKeyRingsResponse]]: + r"""Return a callable for the list key rings method over gRPC. + + Lists [KeyRings][google.cloud.kms.v1.KeyRing]. + + Returns: + Callable[[~.ListKeyRingsRequest], + Awaitable[~.ListKeyRingsResponse]]: + 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_key_rings' not in self._stubs: + self._stubs['list_key_rings'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListKeyRings', + request_serializer=service.ListKeyRingsRequest.serialize, + response_deserializer=service.ListKeyRingsResponse.deserialize, + ) + return self._stubs['list_key_rings'] + + @property + def list_crypto_keys(self) -> Callable[ + [service.ListCryptoKeysRequest], + Awaitable[service.ListCryptoKeysResponse]]: + r"""Return a callable for the list crypto keys method over gRPC. + + Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.ListCryptoKeysRequest], + Awaitable[~.ListCryptoKeysResponse]]: + 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_crypto_keys' not in self._stubs: + self._stubs['list_crypto_keys'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys', + request_serializer=service.ListCryptoKeysRequest.serialize, + response_deserializer=service.ListCryptoKeysResponse.deserialize, + ) + return self._stubs['list_crypto_keys'] + + @property + def list_crypto_key_versions(self) -> Callable[ + [service.ListCryptoKeyVersionsRequest], + Awaitable[service.ListCryptoKeyVersionsResponse]]: + r"""Return a callable for the list crypto key versions method over gRPC. + + Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.ListCryptoKeyVersionsRequest], + Awaitable[~.ListCryptoKeyVersionsResponse]]: + 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_crypto_key_versions' not in self._stubs: + self._stubs['list_crypto_key_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions', + request_serializer=service.ListCryptoKeyVersionsRequest.serialize, + response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize, + ) + return self._stubs['list_crypto_key_versions'] + + @property + def list_import_jobs(self) -> Callable[ + [service.ListImportJobsRequest], + Awaitable[service.ListImportJobsResponse]]: + r"""Return a callable for the list import jobs method over gRPC. + + Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. + + Returns: + Callable[[~.ListImportJobsRequest], + Awaitable[~.ListImportJobsResponse]]: + 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_import_jobs' not in self._stubs: + self._stubs['list_import_jobs'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListImportJobs', + request_serializer=service.ListImportJobsRequest.serialize, + response_deserializer=service.ListImportJobsResponse.deserialize, + ) + return self._stubs['list_import_jobs'] + + @property + def get_key_ring(self) -> Callable[ + [service.GetKeyRingRequest], + Awaitable[resources.KeyRing]]: + r"""Return a callable for the get key ring method over gRPC. + + Returns metadata for a given + [KeyRing][google.cloud.kms.v1.KeyRing]. + + Returns: + Callable[[~.GetKeyRingRequest], + Awaitable[~.KeyRing]]: + 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_key_ring' not in self._stubs: + self._stubs['get_key_ring'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetKeyRing', + request_serializer=service.GetKeyRingRequest.serialize, + response_deserializer=resources.KeyRing.deserialize, + ) + return self._stubs['get_key_ring'] + + @property + def get_crypto_key(self) -> Callable[ + [service.GetCryptoKeyRequest], + Awaitable[resources.CryptoKey]]: + r"""Return a callable for the get crypto key method over gRPC. + + Returns metadata for a given + [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its + [primary][google.cloud.kms.v1.CryptoKey.primary] + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.GetCryptoKeyRequest], + Awaitable[~.CryptoKey]]: + 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_crypto_key' not in self._stubs: + self._stubs['get_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetCryptoKey', + request_serializer=service.GetCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['get_crypto_key'] + + @property + def get_crypto_key_version(self) -> Callable[ + [service.GetCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the get crypto key version method over gRPC. + + Returns metadata for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.GetCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + 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_crypto_key_version' not in self._stubs: + self._stubs['get_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion', + request_serializer=service.GetCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['get_crypto_key_version'] + + @property + def get_public_key(self) -> Callable[ + [service.GetPublicKeyRequest], + Awaitable[resources.PublicKey]]: + r"""Return a callable for the get public key method over gRPC. + + Returns the public key for the given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] + or + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + Returns: + Callable[[~.GetPublicKeyRequest], + Awaitable[~.PublicKey]]: + 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_public_key' not in self._stubs: + self._stubs['get_public_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetPublicKey', + request_serializer=service.GetPublicKeyRequest.serialize, + response_deserializer=resources.PublicKey.deserialize, + ) + return self._stubs['get_public_key'] + + @property + def get_import_job(self) -> Callable[ + [service.GetImportJobRequest], + Awaitable[resources.ImportJob]]: + r"""Return a callable for the get import job method over gRPC. + + Returns metadata for a given + [ImportJob][google.cloud.kms.v1.ImportJob]. + + Returns: + Callable[[~.GetImportJobRequest], + Awaitable[~.ImportJob]]: + 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_import_job' not in self._stubs: + self._stubs['get_import_job'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetImportJob', + request_serializer=service.GetImportJobRequest.serialize, + response_deserializer=resources.ImportJob.deserialize, + ) + return self._stubs['get_import_job'] + + @property + def create_key_ring(self) -> Callable[ + [service.CreateKeyRingRequest], + Awaitable[resources.KeyRing]]: + r"""Return a callable for the create key ring method over gRPC. + + Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given + Project and Location. + + Returns: + Callable[[~.CreateKeyRingRequest], + Awaitable[~.KeyRing]]: + 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_key_ring' not in self._stubs: + self._stubs['create_key_ring'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateKeyRing', + request_serializer=service.CreateKeyRingRequest.serialize, + response_deserializer=resources.KeyRing.deserialize, + ) + return self._stubs['create_key_ring'] + + @property + def create_crypto_key(self) -> Callable[ + [service.CreateCryptoKeyRequest], + Awaitable[resources.CryptoKey]]: + r"""Return a callable for the create crypto key method over gRPC. + + Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and + [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] + are required. + + Returns: + Callable[[~.CreateCryptoKeyRequest], + Awaitable[~.CryptoKey]]: + 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_crypto_key' not in self._stubs: + self._stubs['create_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey', + request_serializer=service.CreateCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['create_crypto_key'] + + @property + def create_crypto_key_version(self) -> Callable[ + [service.CreateCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the create crypto key version method over gRPC. + + Create a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The server will assign the next sequential id. If unset, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. + + Returns: + Callable[[~.CreateCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + 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_crypto_key_version' not in self._stubs: + self._stubs['create_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion', + request_serializer=service.CreateCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['create_crypto_key_version'] + + @property + def import_crypto_key_version(self) -> Callable[ + [service.ImportCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the import crypto key version method over gRPC. + + Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.ImportCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + 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 'import_crypto_key_version' not in self._stubs: + self._stubs['import_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion', + request_serializer=service.ImportCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['import_crypto_key_version'] + + @property + def create_import_job(self) -> Callable[ + [service.CreateImportJobRequest], + Awaitable[resources.ImportJob]]: + r"""Return a callable for the create import job method over gRPC. + + Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] + is required. + + Returns: + Callable[[~.CreateImportJobRequest], + Awaitable[~.ImportJob]]: + 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_import_job' not in self._stubs: + self._stubs['create_import_job'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateImportJob', + request_serializer=service.CreateImportJobRequest.serialize, + response_deserializer=resources.ImportJob.deserialize, + ) + return self._stubs['create_import_job'] + + @property + def update_crypto_key(self) -> Callable[ + [service.UpdateCryptoKeyRequest], + Awaitable[resources.CryptoKey]]: + r"""Return a callable for the update crypto key method over gRPC. + + Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.UpdateCryptoKeyRequest], + Awaitable[~.CryptoKey]]: + 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_crypto_key' not in self._stubs: + self._stubs['update_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey', + request_serializer=service.UpdateCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['update_crypto_key'] + + @property + def update_crypto_key_version(self) -> Callable[ + [service.UpdateCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the update crypto key version method over gRPC. + + Update a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + metadata. + + [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be + changed between + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + and + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + using this method. See + [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] + and + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to move between other states. + + Returns: + Callable[[~.UpdateCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + 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_crypto_key_version' not in self._stubs: + self._stubs['update_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion', + request_serializer=service.UpdateCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['update_crypto_key_version'] + + @property + def update_crypto_key_primary_version(self) -> Callable[ + [service.UpdateCryptoKeyPrimaryVersionRequest], + Awaitable[resources.CryptoKey]]: + r"""Return a callable for the update crypto key primary + version method over gRPC. + + Update the version of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Returns an error if called on a key whose purpose is not + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.UpdateCryptoKeyPrimaryVersionRequest], + Awaitable[~.CryptoKey]]: + 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_crypto_key_primary_version' not in self._stubs: + self._stubs['update_crypto_key_primary_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion', + request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['update_crypto_key_primary_version'] + + @property + def destroy_crypto_key_version(self) -> Callable[ + [service.DestroyCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the destroy crypto key version method over gRPC. + + Schedule a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for + destruction. + + Upon calling this method, + [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] + will be set to + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be set to the time + [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] + in the future. At that time, the + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will + automatically change to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], + and the key material will be irrevocably destroyed. + + Before the + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + is reached, + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + may be called to reverse the process. + + Returns: + Callable[[~.DestroyCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + 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 'destroy_crypto_key_version' not in self._stubs: + self._stubs['destroy_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion', + request_serializer=service.DestroyCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['destroy_crypto_key_version'] + + @property + def restore_crypto_key_version(self) -> Callable[ + [service.RestoreCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the restore crypto key version method over gRPC. + + Restore a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state. + + Upon restoration of the CryptoKeyVersion, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be cleared. + + Returns: + Callable[[~.RestoreCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + 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 'restore_crypto_key_version' not in self._stubs: + self._stubs['restore_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion', + request_serializer=service.RestoreCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['restore_crypto_key_version'] + + @property + def encrypt(self) -> Callable[ + [service.EncryptRequest], + Awaitable[service.EncryptResponse]]: + r"""Return a callable for the encrypt method over gRPC. + + Encrypts data, so that it can only be recovered by a call to + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.EncryptRequest], + Awaitable[~.EncryptResponse]]: + 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 'encrypt' not in self._stubs: + self._stubs['encrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/Encrypt', + request_serializer=service.EncryptRequest.serialize, + response_deserializer=service.EncryptResponse.deserialize, + ) + return self._stubs['encrypt'] + + @property + def decrypt(self) -> Callable[ + [service.DecryptRequest], + Awaitable[service.DecryptResponse]]: + r"""Return a callable for the decrypt method over gRPC. + + Decrypts data that was protected by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.DecryptRequest], + Awaitable[~.DecryptResponse]]: + 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 'decrypt' not in self._stubs: + self._stubs['decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/Decrypt', + request_serializer=service.DecryptRequest.serialize, + response_deserializer=service.DecryptResponse.deserialize, + ) + return self._stubs['decrypt'] + + @property + def asymmetric_sign(self) -> Callable[ + [service.AsymmetricSignRequest], + Awaitable[service.AsymmetricSignResponse]]: + r"""Return a callable for the asymmetric sign method over gRPC. + + Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_SIGN, producing a signature that can be verified with + the public key retrieved from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Returns: + Callable[[~.AsymmetricSignRequest], + Awaitable[~.AsymmetricSignResponse]]: + 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 'asymmetric_sign' not in self._stubs: + self._stubs['asymmetric_sign'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/AsymmetricSign', + request_serializer=service.AsymmetricSignRequest.serialize, + response_deserializer=service.AsymmetricSignResponse.deserialize, + ) + return self._stubs['asymmetric_sign'] + + @property + def asymmetric_decrypt(self) -> Callable[ + [service.AsymmetricDecryptRequest], + Awaitable[service.AsymmetricDecryptResponse]]: + r"""Return a callable for the asymmetric decrypt method over gRPC. + + Decrypts data that was encrypted with a public key retrieved + from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] + corresponding to a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_DECRYPT. + + Returns: + Callable[[~.AsymmetricDecryptRequest], + Awaitable[~.AsymmetricDecryptResponse]]: + 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 'asymmetric_decrypt' not in self._stubs: + self._stubs['asymmetric_decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt', + request_serializer=service.AsymmetricDecryptRequest.serialize, + response_deserializer=service.AsymmetricDecryptResponse.deserialize, + ) + return self._stubs['asymmetric_decrypt'] + + @property + def mac_sign(self) -> Callable[ + [service.MacSignRequest], + Awaitable[service.MacSignResponse]]: + r"""Return a callable for the mac sign method over gRPC. + + Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + producing a tag that can be verified by another source with the + same key. + + Returns: + Callable[[~.MacSignRequest], + Awaitable[~.MacSignResponse]]: + 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 'mac_sign' not in self._stubs: + self._stubs['mac_sign'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/MacSign', + request_serializer=service.MacSignRequest.serialize, + response_deserializer=service.MacSignResponse.deserialize, + ) + return self._stubs['mac_sign'] + + @property + def mac_verify(self) -> Callable[ + [service.MacVerifyRequest], + Awaitable[service.MacVerifyResponse]]: + r"""Return a callable for the mac verify method over gRPC. + + Verifies MAC tag using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + and returns a response that indicates whether or not the + verification was successful. + + Returns: + Callable[[~.MacVerifyRequest], + Awaitable[~.MacVerifyResponse]]: + 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 'mac_verify' not in self._stubs: + self._stubs['mac_verify'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/MacVerify', + request_serializer=service.MacVerifyRequest.serialize, + response_deserializer=service.MacVerifyResponse.deserialize, + ) + return self._stubs['mac_verify'] + + @property + def generate_random_bytes(self) -> Callable[ + [service.GenerateRandomBytesRequest], + Awaitable[service.GenerateRandomBytesResponse]]: + r"""Return a callable for the generate random bytes method over gRPC. + + Generate random bytes using the Cloud KMS randomness + source in the provided location. + + Returns: + Callable[[~.GenerateRandomBytesRequest], + Awaitable[~.GenerateRandomBytesResponse]]: + 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 'generate_random_bytes' not in self._stubs: + self._stubs['generate_random_bytes'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes', + request_serializer=service.GenerateRandomBytesRequest.serialize, + response_deserializer=service.GenerateRandomBytesResponse.deserialize, + ) + return self._stubs['generate_random_bytes'] + + @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__ = ( + 'KeyManagementServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py new file mode 100644 index 00000000..edc01123 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py @@ -0,0 +1,118 @@ +# -*- 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 .resources import ( + CryptoKey, + CryptoKeyVersion, + CryptoKeyVersionTemplate, + ExternalProtectionLevelOptions, + ImportJob, + KeyOperationAttestation, + KeyRing, + PublicKey, + ProtectionLevel, +) +from .service import ( + AsymmetricDecryptRequest, + AsymmetricDecryptResponse, + AsymmetricSignRequest, + AsymmetricSignResponse, + CreateCryptoKeyRequest, + CreateCryptoKeyVersionRequest, + CreateImportJobRequest, + CreateKeyRingRequest, + DecryptRequest, + DecryptResponse, + DestroyCryptoKeyVersionRequest, + Digest, + EncryptRequest, + EncryptResponse, + GenerateRandomBytesRequest, + GenerateRandomBytesResponse, + GetCryptoKeyRequest, + GetCryptoKeyVersionRequest, + GetImportJobRequest, + GetKeyRingRequest, + GetPublicKeyRequest, + ImportCryptoKeyVersionRequest, + ListCryptoKeysRequest, + ListCryptoKeysResponse, + ListCryptoKeyVersionsRequest, + ListCryptoKeyVersionsResponse, + ListImportJobsRequest, + ListImportJobsResponse, + ListKeyRingsRequest, + ListKeyRingsResponse, + LocationMetadata, + MacSignRequest, + MacSignResponse, + MacVerifyRequest, + MacVerifyResponse, + RestoreCryptoKeyVersionRequest, + UpdateCryptoKeyPrimaryVersionRequest, + UpdateCryptoKeyRequest, + UpdateCryptoKeyVersionRequest, +) + +__all__ = ( + 'CryptoKey', + 'CryptoKeyVersion', + 'CryptoKeyVersionTemplate', + 'ExternalProtectionLevelOptions', + 'ImportJob', + 'KeyOperationAttestation', + 'KeyRing', + 'PublicKey', + 'ProtectionLevel', + 'AsymmetricDecryptRequest', + 'AsymmetricDecryptResponse', + 'AsymmetricSignRequest', + 'AsymmetricSignResponse', + 'CreateCryptoKeyRequest', + 'CreateCryptoKeyVersionRequest', + 'CreateImportJobRequest', + 'CreateKeyRingRequest', + 'DecryptRequest', + 'DecryptResponse', + 'DestroyCryptoKeyVersionRequest', + 'Digest', + 'EncryptRequest', + 'EncryptResponse', + 'GenerateRandomBytesRequest', + 'GenerateRandomBytesResponse', + 'GetCryptoKeyRequest', + 'GetCryptoKeyVersionRequest', + 'GetImportJobRequest', + 'GetKeyRingRequest', + 'GetPublicKeyRequest', + 'ImportCryptoKeyVersionRequest', + 'ListCryptoKeysRequest', + 'ListCryptoKeysResponse', + 'ListCryptoKeyVersionsRequest', + 'ListCryptoKeyVersionsResponse', + 'ListImportJobsRequest', + 'ListImportJobsResponse', + 'ListKeyRingsRequest', + 'ListKeyRingsResponse', + 'LocationMetadata', + 'MacSignRequest', + 'MacSignResponse', + 'MacVerifyRequest', + 'MacVerifyResponse', + 'RestoreCryptoKeyVersionRequest', + 'UpdateCryptoKeyPrimaryVersionRequest', + 'UpdateCryptoKeyRequest', + 'UpdateCryptoKeyVersionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py b/owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py new file mode 100644 index 00000000..5abdc1ca --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py @@ -0,0 +1,843 @@ +# -*- 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 duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.kms.v1', + manifest={ + 'ProtectionLevel', + 'KeyRing', + 'CryptoKey', + 'CryptoKeyVersionTemplate', + 'KeyOperationAttestation', + 'CryptoKeyVersion', + 'PublicKey', + 'ImportJob', + 'ExternalProtectionLevelOptions', + }, +) + + +class ProtectionLevel(proto.Enum): + r"""[ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] specifies how + cryptographic operations are performed. For more information, see + [Protection levels] + (https://cloud.google.com/kms/docs/algorithms#protection_levels). + """ + PROTECTION_LEVEL_UNSPECIFIED = 0 + SOFTWARE = 1 + HSM = 2 + EXTERNAL = 3 + + +class KeyRing(proto.Message): + r"""A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical + grouping of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + Attributes: + name (str): + Output only. The resource name for the + [KeyRing][google.cloud.kms.v1.KeyRing] in the format + ``projects/*/locations/*/keyRings/*``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [KeyRing][google.cloud.kms.v1.KeyRing] was created. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + create_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class CryptoKey(proto.Message): + r"""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 [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic operations. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The resource name for this + [CryptoKey][google.cloud.kms.v1.CryptoKey] in the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + primary (google.cloud.kms_v1.types.CryptoKeyVersion): + Output only. A copy of the "primary" + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + that will be used by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] + when this [CryptoKey][google.cloud.kms.v1.CryptoKey] is + given in + [EncryptRequest.name][google.cloud.kms.v1.EncryptRequest.name]. + + The [CryptoKey][google.cloud.kms.v1.CryptoKey]'s primary + version can be updated via + [UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + + Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] + may have a primary. For other keys, this field will be + omitted. + purpose (google.cloud.kms_v1.types.CryptoKey.CryptoKeyPurpose): + Immutable. The immutable purpose of this + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [CryptoKey][google.cloud.kms.v1.CryptoKey] was created. + next_rotation_time (google.protobuf.timestamp_pb2.Timestamp): + At + [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time], + the Key Management Service will automatically: + + 1. Create a new version of this + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + 2. Mark the new version as primary. + + Key rotations performed manually via + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + and + [UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion] + do not affect + [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time]. + + Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] + support automatic rotation. For other keys, this field must + be omitted. + rotation_period (google.protobuf.duration_pb2.Duration): + [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] + will be advanced by this period when the service + automatically rotates a key. Must be at least 24 hours and + at most 876,000 hours. + + If + [rotation_period][google.cloud.kms.v1.CryptoKey.rotation_period] + is set, + [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] + must also be set. + + Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] + [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 + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + instances. The properties of new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + instances created by either + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + or auto-rotation are controlled by this template. + labels (Sequence[google.cloud.kms_v1.types.CryptoKey.LabelsEntry]): + Labels with user-defined metadata. For more information, see + `Labeling + Keys `__. + import_only (bool): + Immutable. Whether this key may contain + imported versions only. + destroy_scheduled_duration (google.protobuf.duration_pb2.Duration): + Immutable. The period of time that versions of this key + spend in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state before transitioning to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. + If not specified at creation time, the default duration is + 24 hours. + """ + class CryptoKeyPurpose(proto.Enum): + r"""[CryptoKeyPurpose][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose] + describes the cryptographic capabilities of a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. A given key can only be + used for the operations allowed by its purpose. For more + information, see `Key + purposes `__. + """ + CRYPTO_KEY_PURPOSE_UNSPECIFIED = 0 + ENCRYPT_DECRYPT = 1 + ASYMMETRIC_SIGN = 5 + ASYMMETRIC_DECRYPT = 6 + MAC = 9 + + name = proto.Field( + proto.STRING, + number=1, + ) + primary = proto.Field( + proto.MESSAGE, + number=2, + message='CryptoKeyVersion', + ) + purpose = proto.Field( + proto.ENUM, + number=3, + enum=CryptoKeyPurpose, + ) + create_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + next_rotation_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + rotation_period = proto.Field( + proto.MESSAGE, + number=8, + oneof='rotation_schedule', + message=duration_pb2.Duration, + ) + version_template = proto.Field( + proto.MESSAGE, + number=11, + message='CryptoKeyVersionTemplate', + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + import_only = proto.Field( + proto.BOOL, + number=13, + ) + destroy_scheduled_duration = proto.Field( + proto.MESSAGE, + number=14, + message=duration_pb2.Duration, + ) + + +class CryptoKeyVersionTemplate(proto.Message): + r"""A + [CryptoKeyVersionTemplate][google.cloud.kms.v1.CryptoKeyVersionTemplate] + specifies the properties to use when creating a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], either + manually with + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + or automatically as a result of auto-rotation. + + Attributes: + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] to + use when creating a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + based on this template. Immutable. Defaults to + [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + Required. + [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + to use when creating a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + based on this template. + + For backwards compatibility, GOOGLE_SYMMETRIC_ENCRYPTION is + implied if both this field is omitted and + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + is + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + """ + + protection_level = proto.Field( + proto.ENUM, + number=1, + enum='ProtectionLevel', + ) + algorithm = proto.Field( + proto.ENUM, + number=3, + enum='CryptoKeyVersion.CryptoKeyVersionAlgorithm', + ) + + +class KeyOperationAttestation(proto.Message): + r"""Contains an HSM-generated attestation about a key operation. For + more information, see [Verifying attestations] + (https://cloud.google.com/kms/docs/attest-key). + + Attributes: + format_ (google.cloud.kms_v1.types.KeyOperationAttestation.AttestationFormat): + Output only. The format of the attestation + data. + content (bytes): + Output only. The attestation data provided by + the HSM when the key operation was performed. + """ + class AttestationFormat(proto.Enum): + r"""Attestation formats provided by the HSM.""" + ATTESTATION_FORMAT_UNSPECIFIED = 0 + CAVIUM_V1_COMPRESSED = 3 + CAVIUM_V2_COMPRESSED = 4 + + format_ = proto.Field( + proto.ENUM, + number=4, + enum=AttestationFormat, + ) + content = proto.Field( + proto.BYTES, + number=5, + ) + + +class CryptoKeyVersion(proto.Message): + r"""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] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material represented + by a [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] can + never be viewed or exported. It can only be used to encrypt, + decrypt, or sign data when an authorized user or application invokes + Cloud KMS. + + Attributes: + name (str): + Output only. The resource name for this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in + the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*``. + state (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionState): + The current state of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + Output only. The + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + describing how crypto operations are performed with this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + Output only. The + [CryptoKeyVersionAlgorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + that this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + supports. + attestation (google.cloud.kms_v1.types.KeyOperationAttestation): + Output only. Statement that was generated and signed by the + HSM at key creation time. Use this statement to verify + attributes of the key as stored on the HSM, independently of + Google. Only provided for key versions with + [protection_level][google.cloud.kms.v1.CryptoKeyVersion.protection_level] + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] was + created. + generate_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + key material was generated. + destroy_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + key material is scheduled for destruction. Only present if + [state][google.cloud.kms.v1.CryptoKeyVersion.state] is + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED]. + destroy_event_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this CryptoKeyVersion's key material + was destroyed. Only present if + [state][google.cloud.kms.v1.CryptoKeyVersion.state] is + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. + import_job (str): + Output only. The name of the + [ImportJob][google.cloud.kms.v1.ImportJob] used in the most + recent import of this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Only present if the underlying key material was imported. + import_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + key material was most recently imported. + import_failure_reason (str): + Output only. The root cause of the most recent import + failure. Only present if + [state][google.cloud.kms.v1.CryptoKeyVersion.state] is + [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED]. + external_protection_level_options (google.cloud.kms_v1.types.ExternalProtectionLevelOptions): + ExternalProtectionLevelOptions stores a group of additional + fields for configuring a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + that are specific to the + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] + protection level. + reimport_eligible (bool): + Output only. Whether or not this key version is eligible for + reimport, by being specified as a target in + [ImportCryptoKeyVersionRequest.crypto_key_version][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.crypto_key_version]. + """ + class CryptoKeyVersionAlgorithm(proto.Enum): + r"""The algorithm of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], indicating + what parameters must be used for each cryptographic operation. + + The + [GOOGLE_SYMMETRIC_ENCRYPTION][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION] + algorithm is usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Algorithms beginning with "RSA_SIGN_" are usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]. + + The fields in the name after "RSA_SIGN_" correspond to the following + parameters: padding algorithm, modulus bit length, and digest + algorithm. + + For PSS, the salt length used is equal to the length of digest + algorithm. For example, + [RSA_SIGN_PSS_2048_SHA256][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PSS_2048_SHA256] + will use PSS with a salt length of 256 bits or 32 bytes. + + Algorithms beginning with "RSA_DECRYPT_" are usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + The fields in the name after "RSA_DECRYPT_" correspond to the + following parameters: padding algorithm, modulus bit length, and + digest algorithm. + + Algorithms beginning with "EC_SIGN_" are usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]. + + The fields in the name after "EC_SIGN_" correspond to the following + parameters: elliptic curve, digest algorithm. + + Algorithms beginning with "HMAC_" are usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [MAC][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.MAC]. + + The suffix following "HMAC_" corresponds to the hash algorithm being + used (eg. SHA256). + + For more information, see [Key purposes and algorithms] + (https://cloud.google.com/kms/docs/algorithms). + """ + CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED = 0 + GOOGLE_SYMMETRIC_ENCRYPTION = 1 + RSA_SIGN_PSS_2048_SHA256 = 2 + RSA_SIGN_PSS_3072_SHA256 = 3 + RSA_SIGN_PSS_4096_SHA256 = 4 + RSA_SIGN_PSS_4096_SHA512 = 15 + RSA_SIGN_PKCS1_2048_SHA256 = 5 + RSA_SIGN_PKCS1_3072_SHA256 = 6 + RSA_SIGN_PKCS1_4096_SHA256 = 7 + RSA_SIGN_PKCS1_4096_SHA512 = 16 + RSA_SIGN_RAW_PKCS1_2048 = 28 + RSA_SIGN_RAW_PKCS1_3072 = 29 + RSA_SIGN_RAW_PKCS1_4096 = 30 + RSA_DECRYPT_OAEP_2048_SHA256 = 8 + RSA_DECRYPT_OAEP_3072_SHA256 = 9 + RSA_DECRYPT_OAEP_4096_SHA256 = 10 + RSA_DECRYPT_OAEP_4096_SHA512 = 17 + RSA_DECRYPT_OAEP_2048_SHA1 = 37 + RSA_DECRYPT_OAEP_3072_SHA1 = 38 + RSA_DECRYPT_OAEP_4096_SHA1 = 39 + EC_SIGN_P256_SHA256 = 12 + EC_SIGN_P384_SHA384 = 13 + EC_SIGN_SECP256K1_SHA256 = 31 + HMAC_SHA256 = 32 + EXTERNAL_SYMMETRIC_ENCRYPTION = 18 + + class CryptoKeyVersionState(proto.Enum): + r"""The state of a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], indicating + if it can be used. + """ + CRYPTO_KEY_VERSION_STATE_UNSPECIFIED = 0 + PENDING_GENERATION = 5 + ENABLED = 1 + DISABLED = 2 + DESTROYED = 3 + DESTROY_SCHEDULED = 4 + PENDING_IMPORT = 6 + IMPORT_FAILED = 7 + + class CryptoKeyVersionView(proto.Enum): + r"""A view for + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]s. Controls + the level of detail returned for + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] in + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions] + and + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + """ + CRYPTO_KEY_VERSION_VIEW_UNSPECIFIED = 0 + FULL = 1 + + name = proto.Field( + proto.STRING, + number=1, + ) + state = proto.Field( + proto.ENUM, + number=3, + enum=CryptoKeyVersionState, + ) + protection_level = proto.Field( + proto.ENUM, + number=7, + enum='ProtectionLevel', + ) + algorithm = proto.Field( + proto.ENUM, + number=10, + enum=CryptoKeyVersionAlgorithm, + ) + attestation = proto.Field( + proto.MESSAGE, + number=8, + message='KeyOperationAttestation', + ) + create_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + generate_time = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + destroy_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + destroy_event_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + import_job = proto.Field( + proto.STRING, + number=14, + ) + import_time = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + import_failure_reason = proto.Field( + proto.STRING, + number=16, + ) + external_protection_level_options = proto.Field( + proto.MESSAGE, + number=17, + message='ExternalProtectionLevelOptions', + ) + reimport_eligible = proto.Field( + proto.BOOL, + number=18, + ) + + +class PublicKey(proto.Message): + r"""The public key for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained + via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Attributes: + pem (str): + The public key, encoded in PEM format. For more information, + see the `RFC 7468 `__ + sections for `General + Considerations `__ + and [Textual Encoding of Subject Public Key Info] + (https://tools.ietf.org/html/rfc7468#section-13). + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + The + [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + associated with this key. + pem_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem]. + An integrity check of + [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem] can be + performed by computing the CRC32C checksum of + [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem] and + comparing your results to this field. Discard the response + in case of non-matching checksum values, and perform a + limited number of retries. A persistent mismatch may + indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + + NOTE: This field is in Beta. + name (str): + The [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key. Provided here for verification. + + NOTE: This field is in Beta. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key. + """ + + pem = proto.Field( + proto.STRING, + number=1, + ) + algorithm = proto.Field( + proto.ENUM, + number=2, + enum='CryptoKeyVersion.CryptoKeyVersionAlgorithm', + ) + pem_crc32c = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + name = proto.Field( + proto.STRING, + number=4, + ) + protection_level = proto.Field( + proto.ENUM, + number=5, + enum='ProtectionLevel', + ) + + +class ImportJob(proto.Message): + r"""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. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is created, Cloud + KMS will generate a "wrapping key", which is a public/private key + pair. You use the wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the import process. + The nature of the wrapping key depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. When + the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] and + the [public_key][google.cloud.kms.v1.ImportJob.public_key] can be + fetched. The fetched public key can then be used to wrap your + pre-existing key material. + + Once the key material is wrapped, it can be imported into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in an + existing [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS uses the + private key portion of the wrapping key to unwrap the key material. + Only Cloud KMS has access to the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 days after + it is created. Once expired, Cloud KMS will no longer be able to + import or unwrap any key material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. + + For more information, see `Importing a + key `__. + + Attributes: + name (str): + Output only. The resource name for this + [ImportJob][google.cloud.kms.v1.ImportJob] in the format + ``projects/*/locations/*/keyRings/*/importJobs/*``. + import_method (google.cloud.kms_v1.types.ImportJob.ImportMethod): + Required. Immutable. The wrapping method to + be used for incoming key material. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + Required. Immutable. The protection level of the + [ImportJob][google.cloud.kms.v1.ImportJob]. This must match + the + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + of the + [version_template][google.cloud.kms.v1.CryptoKey.version_template] + on the [CryptoKey][google.cloud.kms.v1.CryptoKey] you + attempt to import into. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [ImportJob][google.cloud.kms.v1.ImportJob] was created. + generate_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this + [ImportJob][google.cloud.kms.v1.ImportJob]'s key material + was generated. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [ImportJob][google.cloud.kms.v1.ImportJob] is scheduled for + expiration and can no longer be used to import key material. + expire_event_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this + [ImportJob][google.cloud.kms.v1.ImportJob] expired. Only + present if [state][google.cloud.kms.v1.ImportJob.state] is + [EXPIRED][google.cloud.kms.v1.ImportJob.ImportJobState.EXPIRED]. + state (google.cloud.kms_v1.types.ImportJob.ImportJobState): + Output only. The current state of the + [ImportJob][google.cloud.kms.v1.ImportJob], indicating if it + can be used. + public_key (google.cloud.kms_v1.types.ImportJob.WrappingPublicKey): + Output only. The public key with which to wrap key material + prior to import. Only returned if + [state][google.cloud.kms.v1.ImportJob.state] is + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE]. + attestation (google.cloud.kms_v1.types.KeyOperationAttestation): + Output only. Statement that was generated and signed by the + key creator (for example, an HSM) at key creation time. Use + this statement to verify attributes of the key as stored on + the HSM, independently of Google. Only present if the chosen + [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] + is one with a protection level of + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. + """ + class ImportMethod(proto.Enum): + r"""[ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] describes + the key wrapping method chosen for this + [ImportJob][google.cloud.kms.v1.ImportJob]. + """ + IMPORT_METHOD_UNSPECIFIED = 0 + RSA_OAEP_3072_SHA1_AES_256 = 1 + RSA_OAEP_4096_SHA1_AES_256 = 2 + + class ImportJobState(proto.Enum): + r"""The state of the [ImportJob][google.cloud.kms.v1.ImportJob], + indicating if it can be used. + """ + IMPORT_JOB_STATE_UNSPECIFIED = 0 + PENDING_GENERATION = 1 + ACTIVE = 2 + EXPIRED = 3 + + class WrappingPublicKey(proto.Message): + r"""The public key component of the wrapping key. For details of the + type of key this public key corresponds to, see the + [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod]. + + Attributes: + pem (str): + The public key, encoded in PEM format. For more information, + see the `RFC 7468 `__ + sections for `General + Considerations `__ + and [Textual Encoding of Subject Public Key Info] + (https://tools.ietf.org/html/rfc7468#section-13). + """ + + pem = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + import_method = proto.Field( + proto.ENUM, + number=2, + enum=ImportMethod, + ) + protection_level = proto.Field( + proto.ENUM, + number=9, + enum='ProtectionLevel', + ) + create_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + generate_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + expire_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + expire_event_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + state = proto.Field( + proto.ENUM, + number=6, + enum=ImportJobState, + ) + public_key = proto.Field( + proto.MESSAGE, + number=7, + message=WrappingPublicKey, + ) + attestation = proto.Field( + proto.MESSAGE, + number=8, + message='KeyOperationAttestation', + ) + + +class ExternalProtectionLevelOptions(proto.Message): + r"""ExternalProtectionLevelOptions stores a group of additional fields + for configuring a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that are + specific to the + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] protection + level. + + Attributes: + external_key_uri (str): + The URI for an external resource that this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents. + """ + + external_key_uri = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/types/service.py b/owl-bot-staging/v1/google/cloud/kms_v1/types/service.py new file mode 100644 index 00000000..bc445cf8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/types/service.py @@ -0,0 +1,1974 @@ +# -*- 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.cloud.kms_v1.types import resources +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.kms.v1', + manifest={ + 'ListKeyRingsRequest', + 'ListCryptoKeysRequest', + 'ListCryptoKeyVersionsRequest', + 'ListImportJobsRequest', + 'ListKeyRingsResponse', + 'ListCryptoKeysResponse', + 'ListCryptoKeyVersionsResponse', + 'ListImportJobsResponse', + 'GetKeyRingRequest', + 'GetCryptoKeyRequest', + 'GetCryptoKeyVersionRequest', + 'GetPublicKeyRequest', + 'GetImportJobRequest', + 'CreateKeyRingRequest', + 'CreateCryptoKeyRequest', + 'CreateCryptoKeyVersionRequest', + 'ImportCryptoKeyVersionRequest', + 'CreateImportJobRequest', + 'UpdateCryptoKeyRequest', + 'UpdateCryptoKeyVersionRequest', + 'UpdateCryptoKeyPrimaryVersionRequest', + 'DestroyCryptoKeyVersionRequest', + 'RestoreCryptoKeyVersionRequest', + 'EncryptRequest', + 'DecryptRequest', + 'AsymmetricSignRequest', + 'AsymmetricDecryptRequest', + 'MacSignRequest', + 'MacVerifyRequest', + 'GenerateRandomBytesRequest', + 'EncryptResponse', + 'DecryptResponse', + 'AsymmetricSignResponse', + 'AsymmetricDecryptResponse', + 'MacSignResponse', + 'MacVerifyResponse', + 'GenerateRandomBytesResponse', + 'Digest', + 'LocationMetadata', + }, +) + + +class ListKeyRingsRequest(proto.Message): + r"""Request message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [KeyRings][google.cloud.kms.v1.KeyRing], in the format + ``projects/*/locations/*``. + page_size (int): + Optional. Optional limit on the number of + [KeyRings][google.cloud.kms.v1.KeyRing] to include in the + response. Further [KeyRings][google.cloud.kms.v1.KeyRing] + can subsequently be obtained by including the + [ListKeyRingsResponse.next_page_token][google.cloud.kms.v1.ListKeyRingsResponse.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 + [ListKeyRingsResponse.next_page_token][google.cloud.kms.v1.ListKeyRingsResponse.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 ListCryptoKeysRequest(proto.Message): + r"""Request message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Attributes: + parent (str): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + page_size (int): + Optional. Optional limit on the number of + [CryptoKeys][google.cloud.kms.v1.CryptoKey] to include in + the response. Further + [CryptoKeys][google.cloud.kms.v1.CryptoKey] can subsequently + be obtained by including the + [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.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 + [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token]. + version_view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): + The fields of the primary version to include + in the response. + 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, + ) + version_view = proto.Field( + proto.ENUM, + number=4, + enum=resources.CryptoKeyVersion.CryptoKeyVersionView, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + order_by = proto.Field( + proto.STRING, + number=6, + ) + + +class ListCryptoKeyVersionsRequest(proto.Message): + r"""Request message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + Attributes: + parent (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in the + format ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + page_size (int): + Optional. Optional limit on the number of + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] to + include in the response. Further + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can subsequently be obtained by including the + [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.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 + [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token]. + view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): + The fields to include in the response. + 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, + ) + view = proto.Field( + proto.ENUM, + number=4, + enum=resources.CryptoKeyVersion.CryptoKeyVersionView, + ) + filter = proto.Field( + proto.STRING, + number=5, + ) + order_by = proto.Field( + proto.STRING, + number=6, + ) + + +class ListImportJobsRequest(proto.Message): + r"""Request message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + Attributes: + parent (str): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + page_size (int): + Optional. Optional limit on the number of + [ImportJobs][google.cloud.kms.v1.ImportJob] to include in + the response. Further + [ImportJobs][google.cloud.kms.v1.ImportJob] can subsequently + be obtained by including the + [ListImportJobsResponse.next_page_token][google.cloud.kms.v1.ListImportJobsResponse.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 + [ListImportJobsResponse.next_page_token][google.cloud.kms.v1.ListImportJobsResponse.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 ListKeyRingsResponse(proto.Message): + r"""Response message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + Attributes: + key_rings (Sequence[google.cloud.kms_v1.types.KeyRing]): + The list of [KeyRings][google.cloud.kms.v1.KeyRing]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListKeyRingsRequest.page_token][google.cloud.kms.v1.ListKeyRingsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of [KeyRings][google.cloud.kms.v1.KeyRing] + that matched the query. + """ + + @property + def raw_page(self): + return self + + key_rings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.KeyRing, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCryptoKeysResponse(proto.Message): + r"""Response message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Attributes: + crypto_keys (Sequence[google.cloud.kms_v1.types.CryptoKey]): + The list of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListCryptoKeysRequest.page_token][google.cloud.kms.v1.ListCryptoKeysRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [CryptoKeys][google.cloud.kms.v1.CryptoKey] that matched the + query. + """ + + @property + def raw_page(self): + return self + + crypto_keys = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CryptoKey, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCryptoKeyVersionsResponse(proto.Message): + r"""Response message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + Attributes: + crypto_key_versions (Sequence[google.cloud.kms_v1.types.CryptoKeyVersion]): + The list of + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListCryptoKeyVersionsRequest.page_token][google.cloud.kms.v1.ListCryptoKeyVersionsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + that matched the query. + """ + + @property + def raw_page(self): + return self + + crypto_key_versions = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CryptoKeyVersion, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListImportJobsResponse(proto.Message): + r"""Response message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + Attributes: + import_jobs (Sequence[google.cloud.kms_v1.types.ImportJob]): + The list of [ImportJobs][google.cloud.kms.v1.ImportJob]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListImportJobsRequest.page_token][google.cloud.kms.v1.ListImportJobsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [ImportJobs][google.cloud.kms.v1.ImportJob] that matched the + query. + """ + + @property + def raw_page(self): + return self + + import_jobs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.ImportJob, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + + +class GetKeyRingRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] of + the [KeyRing][google.cloud.kms.v1.KeyRing] to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCryptoKeyRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] of + the [CryptoKey][google.cloud.kms.v1.CryptoKey] to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetPublicKeyRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetImportJobRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.ImportJob.name] of + the [ImportJob][google.cloud.kms.v1.ImportJob] to get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateKeyRingRequest(proto.Message): + r"""Request message for + [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [KeyRings][google.cloud.kms.v1.KeyRing], in the format + ``projects/*/locations/*``. + key_ring_id (str): + Required. It must be unique within a location and match the + regular expression ``[a-zA-Z0-9_-]{1,63}`` + key_ring (google.cloud.kms_v1.types.KeyRing): + Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with + initial field values. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + key_ring_id = proto.Field( + proto.STRING, + number=2, + ) + key_ring = proto.Field( + proto.MESSAGE, + number=3, + message=resources.KeyRing, + ) + + +class CreateCryptoKeyRequest(proto.Message): + r"""Request message for + [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] of + the KeyRing associated with the + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + crypto_key_id (str): + Required. It must be unique within a KeyRing and match the + regular expression ``[a-zA-Z0-9_-]{1,63}`` + crypto_key (google.cloud.kms_v1.types.CryptoKey): + Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with + initial field values. + skip_initial_version_creation (bool): + If set to true, the request will create a + [CryptoKey][google.cloud.kms.v1.CryptoKey] without any + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + You must manually call + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + or + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion] + before you can use this + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + crypto_key_id = proto.Field( + proto.STRING, + number=2, + ) + crypto_key = proto.Field( + proto.MESSAGE, + number=3, + message=resources.CryptoKey, + ) + skip_initial_version_creation = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] of + the [CryptoKey][google.cloud.kms.v1.CryptoKey] associated + with the + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): + Required. A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with initial field values. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + crypto_key_version = proto.Field( + proto.MESSAGE, + number=2, + message=resources.CryptoKeyVersion, + ) + + +class ImportCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] of + the [CryptoKey][google.cloud.kms.v1.CryptoKey] to be + imported into. + + The create permission is only required on this key when + creating a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + crypto_key_version (str): + Optional. The optional + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of an + existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + target for an import operation. If this field is not + present, a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + containing the supplied key material is created. + + If this field is present, the supplied key material is + imported into the existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. To + import into an existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], + the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must be a child of + [ImportCryptoKeyVersionRequest.parent][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.parent], + have been previously created via [ImportCryptoKeyVersion][], + and be in + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED] + or + [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED] + state. The key material and algorithm must match the + previous + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + exactly if the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] has + ever contained key material. + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + Required. The + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + of the key being imported. This does not need to match the + [version_template][google.cloud.kms.v1.CryptoKey.version_template] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] this + version imports into. + import_job (str): + Required. The [name][google.cloud.kms.v1.ImportJob.name] of + the [ImportJob][google.cloud.kms.v1.ImportJob] that was used + to wrap this key material. + rsa_aes_wrapped_key (bytes): + Wrapped key material produced with + [RSA_OAEP_3072_SHA1_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256] + or + [RSA_OAEP_4096_SHA1_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA1_AES_256]. + + This field contains the concatenation of two wrapped keys: + + .. raw:: html + +
    +
  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. +
  2. +
  3. The key to be imported, wrapped with the ephemeral AES-256 key + using AES-KWP (RFC 5649). +
  4. +
+ + If importing symmetric key material, it is expected that the + unwrapped key contains plain bytes. If importing asymmetric + key material, it is expected that the unwrapped key is in + PKCS#8-encoded DER format (the PrivateKeyInfo structure from + RFC 5208). + + 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``. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + crypto_key_version = proto.Field( + proto.STRING, + number=6, + ) + algorithm = proto.Field( + proto.ENUM, + number=2, + enum=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm, + ) + import_job = proto.Field( + proto.STRING, + number=4, + ) + rsa_aes_wrapped_key = proto.Field( + proto.BYTES, + number=5, + oneof='wrapped_key_material', + ) + + +class CreateImportJobRequest(proto.Message): + r"""Request message for + [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] of + the [KeyRing][google.cloud.kms.v1.KeyRing] associated with + the [ImportJobs][google.cloud.kms.v1.ImportJob]. + import_job_id (str): + Required. It must be unique within a KeyRing and match the + regular expression ``[a-zA-Z0-9_-]{1,63}`` + import_job (google.cloud.kms_v1.types.ImportJob): + Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with + initial field values. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + import_job_id = proto.Field( + proto.STRING, + number=2, + ) + import_job = proto.Field( + proto.MESSAGE, + number=3, + message=resources.ImportJob, + ) + + +class UpdateCryptoKeyRequest(proto.Message): + r"""Request message for + [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. + + Attributes: + crypto_key (google.cloud.kms_v1.types.CryptoKey): + Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] with + updated values. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + crypto_key = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CryptoKey, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. + + Attributes: + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): + Required. + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with updated values. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + crypto_key_version = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CryptoKeyVersion, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateCryptoKeyPrimaryVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. + crypto_key_version_id (str): + Required. The id of the child + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use as primary. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + crypto_key_version_id = proto.Field( + proto.STRING, + number=2, + ) + + +class DestroyCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + destroy. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class RestoreCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + restore. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class EncryptRequest(proto.Message): + r"""Request message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] or + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for encryption. + + If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is + specified, the server will use its [primary + version][google.cloud.kms.v1.CryptoKey.primary]. + plaintext (bytes): + Required. The data to encrypt. Must be no larger than 64KiB. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] + keys, the plaintext must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger than + 8KiB. + additional_authenticated_data (bytes): + Optional. Optional data that, if specified, must also be + provided during decryption through + [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] + keys, the AAD must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger than + 8KiB. + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]) + is equal to + [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]) + is equal to + [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + plaintext = proto.Field( + proto.BYTES, + number=2, + ) + additional_authenticated_data = proto.Field( + proto.BYTES, + number=3, + ) + plaintext_crc32c = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.Int64Value, + ) + additional_authenticated_data_crc32c = proto.Field( + proto.MESSAGE, + number=8, + message=wrappers_pb2.Int64Value, + ) + + +class DecryptRequest(proto.Message): + r"""Request message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for + decryption. The server will choose the appropriate version. + ciphertext (bytes): + Required. The encrypted data originally returned in + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + additional_authenticated_data (bytes): + Optional. Optional data that must match the data originally + supplied in + [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]) + is equal to + [DecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.DecryptRequest.ciphertext_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]) + is equal to + [DecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + ciphertext = proto.Field( + proto.BYTES, + number=2, + ) + additional_authenticated_data = proto.Field( + proto.BYTES, + number=3, + ) + ciphertext_crc32c = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int64Value, + ) + additional_authenticated_data_crc32c = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int64Value, + ) + + +class AsymmetricSignRequest(proto.Message): + r"""Request message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for signing. + digest (google.cloud.kms_v1.types.Digest): + Optional. The digest of the data to sign. The digest must be + produced with the same digest algorithm as specified by the + key version's + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]) + is equal to + [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + 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. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]) + is equal to + [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + digest = proto.Field( + proto.MESSAGE, + number=3, + message='Digest', + ) + digest_crc32c = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.Int64Value, + ) + data = proto.Field( + proto.BYTES, + number=6, + ) + data_crc32c = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.Int64Value, + ) + + +class AsymmetricDecryptRequest(proto.Message): + r"""Request message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for decryption. + ciphertext (bytes): + Required. The data encrypted with the named + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + public key using OAEP. + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]) + is equal to + [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + ciphertext = proto.Field( + proto.BYTES, + number=3, + ) + ciphertext_crc32c = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.Int64Value, + ) + + +class MacSignRequest(proto.Message): + r"""Request message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for signing. + data (bytes): + Required. The data to sign. The MAC tag is + computed over this data field based on the + specific algorithm. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data]) + is equal to + [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + data = proto.Field( + proto.BYTES, + number=2, + ) + data_crc32c = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + + +class MacVerifyRequest(proto.Message): + r"""Request message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for verification. + data (bytes): + Required. The data used previously as a + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] + to generate the MAC tag. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data]) + is equal to + [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + mac (bytes): + Required. The signature to verify. + mac_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([MacVerifyRequest.tag][]) is equal to + [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + data = proto.Field( + proto.BYTES, + number=2, + ) + data_crc32c = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + mac = proto.Field( + proto.BYTES, + number=4, + ) + mac_crc32c = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int64Value, + ) + + +class GenerateRandomBytesRequest(proto.Message): + r"""Request message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + Attributes: + location (str): + The project-specific location in which to + generate random bytes. For example, + "projects/my-project/locations/us-central1". + length_bytes (int): + The length in bytes of the amount of + randomness to retrieve. Minimum 8 bytes, + 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]. + """ + + location = proto.Field( + proto.STRING, + number=1, + ) + length_bytes = proto.Field( + proto.INT32, + number=2, + ) + protection_level = proto.Field( + proto.ENUM, + number=3, + enum=resources.ProtectionLevel, + ) + + +class EncryptResponse(proto.Message): + r"""Response message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Attributes: + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in encryption. Check this field to verify that the + intended resource was used for encryption. + ciphertext (bytes): + The encrypted data. + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + An integrity check of + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext] + can be performed by computing the CRC32C checksum of + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_plaintext_crc32c (bool): + Integrity verification field. A flag indicating whether + [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. A + false value of this field indicates either that + [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_additional_authenticated_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [AAD][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. + A false value of this field indicates either that + [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in encryption. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + ciphertext = proto.Field( + proto.BYTES, + number=2, + ) + ciphertext_crc32c = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.Int64Value, + ) + verified_plaintext_crc32c = proto.Field( + proto.BOOL, + number=5, + ) + verified_additional_authenticated_data_crc32c = proto.Field( + proto.BOOL, + number=6, + ) + protection_level = proto.Field( + proto.ENUM, + number=7, + enum=resources.ProtectionLevel, + ) + + +class DecryptResponse(proto.Message): + r"""Response message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + Attributes: + plaintext (bytes): + The decrypted data originally supplied in + [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext]. + An integrity check of + [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext] + can be performed by computing the CRC32C checksum of + [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: receiving this response message indicates + that + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + is able to successfully decrypt the + [ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. + Note: This field is defined as int64 for reasons of + compatibility across different languages. However, it is a + non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + used_primary (bool): + Whether the Decryption was performed using + the primary key version. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in decryption. + """ + + plaintext = proto.Field( + proto.BYTES, + number=1, + ) + plaintext_crc32c = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + used_primary = proto.Field( + proto.BOOL, + number=3, + ) + protection_level = proto.Field( + proto.ENUM, + number=4, + enum=resources.ProtectionLevel, + ) + + +class AsymmetricSignResponse(proto.Message): + r"""Response message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + Attributes: + signature (bytes): + The created signature. + signature_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature]. + An integrity check of + [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature] + can be performed by computing the CRC32C checksum of + [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_digest_crc32c (bool): + Integrity verification field. A flag indicating whether + [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. + A false value of this field indicates either that + [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for signing. Check this field to verify that the + intended resource was used for signing. + verified_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [data][google.cloud.kms.v1.AsymmetricSignRequest.data]. A + false value of this field indicates either that + [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for signing. + """ + + signature = proto.Field( + proto.BYTES, + number=1, + ) + signature_crc32c = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + verified_digest_crc32c = proto.Field( + proto.BOOL, + number=3, + ) + name = proto.Field( + proto.STRING, + number=4, + ) + verified_data_crc32c = proto.Field( + proto.BOOL, + number=5, + ) + protection_level = proto.Field( + proto.ENUM, + number=6, + enum=resources.ProtectionLevel, + ) + + +class AsymmetricDecryptResponse(proto.Message): + r"""Response message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + Attributes: + plaintext (bytes): + The decrypted data originally encrypted with + the matching public key. + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext]. + An integrity check of + [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext] + can be performed by computing the CRC32C checksum of + [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_ciphertext_crc32c (bool): + Integrity verification field. A flag indicating whether + [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. + A false value of this field indicates either that + [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in decryption. + """ + + plaintext = proto.Field( + proto.BYTES, + number=1, + ) + plaintext_crc32c = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + verified_ciphertext_crc32c = proto.Field( + proto.BOOL, + number=3, + ) + protection_level = proto.Field( + proto.ENUM, + number=4, + enum=resources.ProtectionLevel, + ) + + +class MacSignResponse(proto.Message): + r"""Response message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + Attributes: + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for signing. Check this field to verify that the + intended resource was used for signing. + mac (bytes): + The created signature. + mac_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac]. + An integrity check of + [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac] + can be performed by computing the CRC32C checksum of + [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [data][google.cloud.kms.v1.MacSignRequest.data]. A false + value of this field indicates either that + [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for signing. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + mac = proto.Field( + proto.BYTES, + number=2, + ) + mac_crc32c = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + verified_data_crc32c = proto.Field( + proto.BOOL, + number=4, + ) + protection_level = proto.Field( + proto.ENUM, + number=5, + enum=resources.ProtectionLevel, + ) + + +class MacVerifyResponse(proto.Message): + r"""Response message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + Attributes: + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for verification. Check this field to verify that the + intended resource was used for verification. + success (bool): + This field indicates whether or not the verification + operation for + [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac] + over + [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data] + was successful. + verified_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [data][google.cloud.kms.v1.MacVerifyRequest.data]. A false + value of this field indicates either that + [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_mac_crc32c (bool): + Integrity verification field. A flag indicating whether + [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [data][google.cloud.kms.v1.MacVerifyRequest.mac]. A false + value of this field indicates either that + [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_success_integrity (bool): + Integrity verification field. This value is used for the + integrity verification of [MacVerifyResponse.success]. If + the value of this field contradicts the value of + [MacVerifyResponse.success], discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for verification. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + success = proto.Field( + proto.BOOL, + number=2, + ) + verified_data_crc32c = proto.Field( + proto.BOOL, + number=3, + ) + verified_mac_crc32c = proto.Field( + proto.BOOL, + number=4, + ) + verified_success_integrity = proto.Field( + proto.BOOL, + number=5, + ) + protection_level = proto.Field( + proto.ENUM, + number=6, + enum=resources.ProtectionLevel, + ) + + +class GenerateRandomBytesResponse(proto.Message): + r"""Response message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + Attributes: + data (bytes): + The generated data. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data]. + An integrity check of + [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data] + can be performed by computing the CRC32C checksum of + [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + """ + + data = proto.Field( + proto.BYTES, + number=1, + ) + data_crc32c = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + + +class Digest(proto.Message): + r"""A [Digest][google.cloud.kms.v1.Digest] holds a cryptographic message + digest. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + 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``. + """ + + sha256 = proto.Field( + proto.BYTES, + number=1, + oneof='digest', + ) + sha384 = proto.Field( + proto.BYTES, + number=2, + oneof='digest', + ) + sha512 = proto.Field( + proto.BYTES, + number=3, + oneof='digest', + ) + + +class LocationMetadata(proto.Message): + r"""Cloud KMS metadata for the given + [google.cloud.location.Location][google.cloud.location.Location]. + + Attributes: + hsm_available (bool): + Indicates whether + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] can be + created in this location. + ekm_available (bool): + Indicates whether + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] can + be created in this location. + """ + + hsm_available = proto.Field( + proto.BOOL, + number=1, + ) + ekm_available = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 00000000..8fe3ebab --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9', '3.10']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/kms_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.9') +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python='3.9') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py new file mode 100644 index 00000000..1c0a208b --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py @@ -0,0 +1,204 @@ +#! /usr/bin/env python3 +# -*- 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class kmsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'asymmetric_decrypt': ('name', 'ciphertext', 'ciphertext_crc32c', ), + '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_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', ), + 'destroy_crypto_key_version': ('name', ), + 'encrypt': ('name', 'plaintext', 'additional_authenticated_data', 'plaintext_crc32c', 'additional_authenticated_data_crc32c', ), + 'generate_random_bytes': ('location', 'length_bytes', 'protection_level', ), + 'get_crypto_key': ('name', ), + 'get_crypto_key_version': ('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_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', ), + 'mac_verify': ('name', 'data', 'mac', 'data_crc32c', 'mac_crc32c', ), + 'restore_crypto_key_version': ('name', ), + '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', ), + 'get_iam_policy': ('resource', 'options', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=kmsCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the kms client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 00000000..f6eb8321 --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,55 @@ +# -*- 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 io +import os +import setuptools # type: ignore + +version = '0.1.0' + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, 'README.rst') +with io.open(readme_filename, encoding='utf-8') as readme_file: + readme = readme_file.read() + +setuptools.setup( + name='google-cloud-kms', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.28.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.19.7', + 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', + ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py new file mode 100644 index 00000000..b9e0378a --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -0,0 +1,8912 @@ +# -*- 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.key_management_service import KeyManagementServiceAsyncClient +from google.cloud.kms_v1.services.key_management_service import KeyManagementServiceClient +from google.cloud.kms_v1.services.key_management_service import pagers +from google.cloud.kms_v1.services.key_management_service import transports +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import 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 duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_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 KeyManagementServiceClient._get_default_mtls_endpoint(None) is None + assert KeyManagementServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert KeyManagementServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert KeyManagementServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert KeyManagementServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert KeyManagementServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + KeyManagementServiceClient, + KeyManagementServiceAsyncClient, +]) +def test_key_management_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.KeyManagementServiceGrpcTransport, "grpc"), + (transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_key_management_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", [ + KeyManagementServiceClient, + KeyManagementServiceAsyncClient, +]) +def test_key_management_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_key_management_service_client_get_transport_class(): + transport = KeyManagementServiceClient.get_transport_class() + available_transports = [ + transports.KeyManagementServiceGrpcTransport, + ] + assert transport in available_transports + + transport = KeyManagementServiceClient.get_transport_class("grpc") + assert transport == transports.KeyManagementServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@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_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(KeyManagementServiceClient, '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(KeyManagementServiceClient, '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", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", "true"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", "false"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(KeyManagementServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KeyManagementServiceClient)) +@mock.patch.object(KeyManagementServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KeyManagementServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_key_management_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", [ + 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", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_key_management_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", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_key_management_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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_key_management_service_client_client_options_from_dict(): + with mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = KeyManagementServiceClient( + 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("request_type", [ + service.ListKeyRingsRequest, + dict, +]) +def test_list_key_rings(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + 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_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListKeyRingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListKeyRingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyRingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +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. + client = KeyManagementServiceClient( + 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_key_rings), + '__call__') as call: + client.list_key_rings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListKeyRingsRequest() + + +@pytest.mark.asyncio +async def test_list_key_rings_async(transport: str = 'grpc_asyncio', request_type=service.ListKeyRingsRequest): + client = KeyManagementServiceAsyncClient( + 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_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListKeyRingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyRingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_key_rings_async_from_dict(): + await test_list_key_rings_async(request_type=dict) + + +def test_list_key_rings_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListKeyRingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + call.return_value = service.ListKeyRingsResponse() + client.list_key_rings(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_key_rings_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListKeyRingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse()) + await client.list_key_rings(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_key_rings_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListKeyRingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_key_rings( + 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_key_rings_flattened_error(): + client = KeyManagementServiceClient( + 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_key_rings( + service.ListKeyRingsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_key_rings_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListKeyRingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_key_rings( + 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_key_rings_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_key_rings( + service.ListKeyRingsRequest(), + parent='parent_value', + ) + + +def test_list_key_rings_pager(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_key_rings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_key_rings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.KeyRing) + for i in results) +def test_list_key_rings_pages(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_key_rings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + RuntimeError, + ) + pages = list(client.list_key_rings(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_key_rings_async_pager(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_key_rings(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, resources.KeyRing) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_key_rings_async_pages(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_key_rings(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", [ + service.ListCryptoKeysRequest, + dict, +]) +def test_list_crypto_keys(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + 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_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeysResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListCryptoKeysRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeysPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +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. + client = KeyManagementServiceClient( + 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_crypto_keys), + '__call__') as call: + client.list_crypto_keys() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListCryptoKeysRequest() + + +@pytest.mark.asyncio +async def test_list_crypto_keys_async(transport: str = 'grpc_asyncio', request_type=service.ListCryptoKeysRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListCryptoKeysRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeysAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_crypto_keys_async_from_dict(): + await test_list_crypto_keys_async(request_type=dict) + + +def test_list_crypto_keys_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListCryptoKeysRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + call.return_value = service.ListCryptoKeysResponse() + client.list_crypto_keys(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_crypto_keys_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListCryptoKeysRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse()) + await client.list_crypto_keys(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_crypto_keys_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeysResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_crypto_keys( + 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_crypto_keys_flattened_error(): + client = KeyManagementServiceClient( + 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_crypto_keys( + service.ListCryptoKeysRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_crypto_keys_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeysResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_crypto_keys( + 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_crypto_keys_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_keys( + service.ListCryptoKeysRequest(), + parent='parent_value', + ) + + +def test_list_crypto_keys_pager(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_crypto_keys), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crypto_keys(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKey) + for i in results) +def test_list_crypto_keys_pages(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_crypto_keys), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crypto_keys(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_crypto_keys_async_pager(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crypto_keys(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, resources.CryptoKey) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_crypto_keys_async_pages(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_crypto_keys(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", [ + service.ListCryptoKeyVersionsRequest, + dict, +]) +def test_list_crypto_key_versions(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + 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_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeyVersionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_crypto_key_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListCryptoKeyVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeyVersionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +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. + client = KeyManagementServiceClient( + 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_crypto_key_versions), + '__call__') as call: + client.list_crypto_key_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListCryptoKeyVersionsRequest() + + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_async(transport: str = 'grpc_asyncio', request_type=service.ListCryptoKeyVersionsRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_crypto_key_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListCryptoKeyVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeyVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_async_from_dict(): + await test_list_crypto_key_versions_async(request_type=dict) + + +def test_list_crypto_key_versions_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListCryptoKeyVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + call.return_value = service.ListCryptoKeyVersionsResponse() + client.list_crypto_key_versions(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_crypto_key_versions_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListCryptoKeyVersionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse()) + await client.list_crypto_key_versions(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_crypto_key_versions_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeyVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_crypto_key_versions( + 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_crypto_key_versions_flattened_error(): + client = KeyManagementServiceClient( + 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_crypto_key_versions( + service.ListCryptoKeyVersionsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeyVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_crypto_key_versions( + 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_crypto_key_versions_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_versions( + service.ListCryptoKeyVersionsRequest(), + parent='parent_value', + ) + + +def test_list_crypto_key_versions_pager(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_crypto_key_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crypto_key_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKeyVersion) + for i in results) +def test_list_crypto_key_versions_pages(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_crypto_key_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crypto_key_versions(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_crypto_key_versions_async_pager(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crypto_key_versions(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, resources.CryptoKeyVersion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_async_pages(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_crypto_key_versions(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", [ + service.ListImportJobsRequest, + dict, +]) +def test_list_import_jobs(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + 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_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListImportJobsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListImportJobsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImportJobsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +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. + client = KeyManagementServiceClient( + 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_import_jobs), + '__call__') as call: + client.list_import_jobs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListImportJobsRequest() + + +@pytest.mark.asyncio +async def test_list_import_jobs_async(transport: str = 'grpc_asyncio', request_type=service.ListImportJobsRequest): + client = KeyManagementServiceAsyncClient( + 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_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListImportJobsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImportJobsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_import_jobs_async_from_dict(): + await test_list_import_jobs_async(request_type=dict) + + +def test_list_import_jobs_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListImportJobsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + call.return_value = service.ListImportJobsResponse() + client.list_import_jobs(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_import_jobs_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListImportJobsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse()) + await client.list_import_jobs(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_import_jobs_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListImportJobsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_import_jobs( + 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_import_jobs_flattened_error(): + client = KeyManagementServiceClient( + 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_import_jobs( + service.ListImportJobsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_import_jobs_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListImportJobsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_import_jobs( + 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_import_jobs_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_import_jobs( + service.ListImportJobsRequest(), + parent='parent_value', + ) + + +def test_list_import_jobs_pager(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_import_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_import_jobs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, resources.ImportJob) + for i in results) +def test_list_import_jobs_pages(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_import_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + RuntimeError, + ) + pages = list(client.list_import_jobs(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_import_jobs_async_pager(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_import_jobs(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, resources.ImportJob) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_import_jobs_async_pages(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_import_jobs(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", [ + service.GetKeyRingRequest, + dict, +]) +def test_get_key_ring(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + 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_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing( + name='name_value', + ) + response = client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetKeyRingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +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. + client = KeyManagementServiceClient( + 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_key_ring), + '__call__') as call: + client.get_key_ring() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetKeyRingRequest() + + +@pytest.mark.asyncio +async def test_get_key_ring_async(transport: str = 'grpc_asyncio', request_type=service.GetKeyRingRequest): + client = KeyManagementServiceAsyncClient( + 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_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( + name='name_value', + )) + response = await client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetKeyRingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_key_ring_async_from_dict(): + await test_get_key_ring_async(request_type=dict) + + +def test_get_key_ring_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetKeyRingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + call.return_value = resources.KeyRing() + client.get_key_ring(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_key_ring_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetKeyRingRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) + await client.get_key_ring(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_key_ring_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_key_ring( + 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_key_ring_flattened_error(): + client = KeyManagementServiceClient( + 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_key_ring( + service.GetKeyRingRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_key_ring_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_key_ring( + 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_key_ring_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_key_ring( + service.GetKeyRingRequest(), + name='name_value', + ) + + +@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, + ) + + # 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + rotation_period=duration_pb2.Duration(seconds=751), + ) + response = client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetCryptoKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + + +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. + client = KeyManagementServiceClient( + 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_crypto_key), + '__call__') as call: + client.get_crypto_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetCryptoKeyRequest() + + +@pytest.mark.asyncio +async def test_get_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.GetCryptoKeyRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + )) + response = await client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetCryptoKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + + +@pytest.mark.asyncio +async def test_get_crypto_key_async_from_dict(): + await test_get_crypto_key_async(request_type=dict) + + +def test_get_crypto_key_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetCryptoKeyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.get_crypto_key(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_crypto_key_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetCryptoKeyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.get_crypto_key(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_crypto_key_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_crypto_key( + 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_crypto_key_flattened_error(): + client = KeyManagementServiceClient( + 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_crypto_key( + service.GetCryptoKeyRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_crypto_key_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_crypto_key( + 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_crypto_key_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_key( + service.GetCryptoKeyRequest(), + name='name_value', + ) + + +@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, + ) + + # 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + ) + response = client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +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. + client = KeyManagementServiceClient( + 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_crypto_key_version), + '__call__') as call: + client.get_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetCryptoKeyVersionRequest() + + +@pytest.mark.asyncio +async def test_get_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.GetCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + )) + response = await client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_get_crypto_key_version_async_from_dict(): + await test_get_crypto_key_version_async(request_type=dict) + + +def test_get_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetCryptoKeyVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.get_crypto_key_version(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_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetCryptoKeyVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.get_crypto_key_version(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_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_crypto_key_version( + 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_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + 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_crypto_key_version( + service.GetCryptoKeyVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_crypto_key_version( + 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_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_version( + service.GetCryptoKeyVersionRequest(), + name='name_value', + ) + + +@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, + ) + + # 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_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.PublicKey( + pem='pem_value', + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetPublicKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.PublicKey) + assert response.pem == 'pem_value' + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.name == 'name_value' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +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. + client = KeyManagementServiceClient( + 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_public_key), + '__call__') as call: + client.get_public_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetPublicKeyRequest() + + +@pytest.mark.asyncio +async def test_get_public_key_async(transport: str = 'grpc_asyncio', request_type=service.GetPublicKeyRequest): + client = KeyManagementServiceAsyncClient( + 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_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey( + pem='pem_value', + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetPublicKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.PublicKey) + assert response.pem == 'pem_value' + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.name == 'name_value' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_get_public_key_async_from_dict(): + await test_get_public_key_async(request_type=dict) + + +def test_get_public_key_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetPublicKeyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + call.return_value = resources.PublicKey() + client.get_public_key(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_public_key_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetPublicKeyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) + await client.get_public_key(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_public_key_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.PublicKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_public_key( + 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_public_key_flattened_error(): + client = KeyManagementServiceClient( + 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_public_key( + service.GetPublicKeyRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_public_key_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.PublicKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_public_key( + 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_public_key_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_public_key( + service.GetPublicKeyRequest(), + name='name_value', + ) + + +@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, + ) + + # 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_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + ) + response = client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetImportJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +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. + client = KeyManagementServiceClient( + 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_import_job), + '__call__') as call: + client.get_import_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetImportJobRequest() + + +@pytest.mark.asyncio +async def test_get_import_job_async(transport: str = 'grpc_asyncio', request_type=service.GetImportJobRequest): + client = KeyManagementServiceAsyncClient( + 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_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + )) + response = await client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetImportJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +@pytest.mark.asyncio +async def test_get_import_job_async_from_dict(): + await test_get_import_job_async(request_type=dict) + + +def test_get_import_job_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetImportJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + call.return_value = resources.ImportJob() + client.get_import_job(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_import_job_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetImportJobRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + await client.get_import_job(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_import_job_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_import_job( + 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_import_job_flattened_error(): + client = KeyManagementServiceClient( + 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_import_job( + service.GetImportJobRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_import_job_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_import_job( + 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_import_job_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_import_job( + service.GetImportJobRequest(), + name='name_value', + ) + + +@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, + ) + + # 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_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing( + name='name_value', + ) + response = client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateKeyRingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +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. + client = KeyManagementServiceClient( + 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_key_ring), + '__call__') as call: + client.create_key_ring() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateKeyRingRequest() + + +@pytest.mark.asyncio +async def test_create_key_ring_async(transport: str = 'grpc_asyncio', request_type=service.CreateKeyRingRequest): + client = KeyManagementServiceAsyncClient( + 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_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( + name='name_value', + )) + response = await client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateKeyRingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_key_ring_async_from_dict(): + await test_create_key_ring_async(request_type=dict) + + +def test_create_key_ring_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateKeyRingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + call.return_value = resources.KeyRing() + client.create_key_ring(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_key_ring_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateKeyRingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) + await client.create_key_ring(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_key_ring_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_key_ring( + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(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].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(): + client = KeyManagementServiceClient( + 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_key_ring( + service.CreateKeyRingRequest(), + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_key_ring_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_key_ring( + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(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].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 +async def test_create_key_ring_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_key_ring( + service.CreateKeyRingRequest(), + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(name='name_value'), + ) + + +@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, + ) + + # 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + rotation_period=duration_pb2.Duration(seconds=751), + ) + response = client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateCryptoKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + + +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. + client = KeyManagementServiceClient( + 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_crypto_key), + '__call__') as call: + client.create_crypto_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateCryptoKeyRequest() + + +@pytest.mark.asyncio +async def test_create_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.CreateCryptoKeyRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + )) + response = await client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateCryptoKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + + +@pytest.mark.asyncio +async def test_create_crypto_key_async_from_dict(): + await test_create_crypto_key_async(request_type=dict) + + +def test_create_crypto_key_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateCryptoKeyRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.create_crypto_key(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_crypto_key_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateCryptoKeyRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.create_crypto_key(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_crypto_key_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_crypto_key( + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(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].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(): + client = KeyManagementServiceClient( + 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_crypto_key( + service.CreateCryptoKeyRequest(), + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_crypto_key_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_crypto_key( + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(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].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 +async def test_create_crypto_key_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_key( + service.CreateCryptoKeyRequest(), + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(name='name_value'), + ) + + +@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, + ) + + # 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + ) + response = client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +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. + client = KeyManagementServiceClient( + 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_crypto_key_version), + '__call__') as call: + client.create_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateCryptoKeyVersionRequest() + + +@pytest.mark.asyncio +async def test_create_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.CreateCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + )) + response = await client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_create_crypto_key_version_async_from_dict(): + await test_create_crypto_key_version_async(request_type=dict) + + +def test_create_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateCryptoKeyVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.create_crypto_key_version(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_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateCryptoKeyVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.create_crypto_key_version(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_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_crypto_key_version( + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version + mock_val = resources.CryptoKeyVersion(name='name_value') + assert arg == mock_val + + +def test_create_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + 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_crypto_key_version( + service.CreateCryptoKeyVersionRequest(), + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_crypto_key_version( + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version + mock_val = resources.CryptoKeyVersion(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_version( + service.CreateCryptoKeyVersionRequest(), + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + ) + + +@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, + ) + + # 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.import_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + ) + response = client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.ImportCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +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. + client = KeyManagementServiceClient( + 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.import_crypto_key_version), + '__call__') as call: + client.import_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ImportCryptoKeyVersionRequest() + + +@pytest.mark.asyncio +async def test_import_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.ImportCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + 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.import_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + )) + response = await client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.ImportCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_import_crypto_key_version_async_from_dict(): + await test_import_crypto_key_version_async(request_type=dict) + + +def test_import_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ImportCryptoKeyVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.import_crypto_key_version(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_import_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ImportCryptoKeyVersionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.import_crypto_key_version(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'] + + +@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, + ) + + # 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_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + ) + response = client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateImportJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +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. + client = KeyManagementServiceClient( + 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_import_job), + '__call__') as call: + client.create_import_job() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateImportJobRequest() + + +@pytest.mark.asyncio +async def test_create_import_job_async(transport: str = 'grpc_asyncio', request_type=service.CreateImportJobRequest): + client = KeyManagementServiceAsyncClient( + 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_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + )) + response = await client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateImportJobRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +@pytest.mark.asyncio +async def test_create_import_job_async_from_dict(): + await test_create_import_job_async(request_type=dict) + + +def test_create_import_job_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateImportJobRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + call.return_value = resources.ImportJob() + client.create_import_job(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_import_job_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateImportJobRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + await client.create_import_job(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_import_job_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_import_job( + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(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].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(): + client = KeyManagementServiceClient( + 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_import_job( + service.CreateImportJobRequest(), + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_import_job_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_import_job( + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(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].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 +async def test_create_import_job_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_import_job( + service.CreateImportJobRequest(), + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(name='name_value'), + ) + + +@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, + ) + + # 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + rotation_period=duration_pb2.Duration(seconds=751), + ) + response = client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + + +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. + client = KeyManagementServiceClient( + 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_crypto_key), + '__call__') as call: + client.update_crypto_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyRequest() + + +@pytest.mark.asyncio +async def test_update_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + )) + response = await client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + + +@pytest.mark.asyncio +async def test_update_crypto_key_async_from_dict(): + await test_update_crypto_key_async(request_type=dict) + + +def test_update_crypto_key_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyRequest() + + request.crypto_key.name = 'crypto_key.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.update_crypto_key(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', + 'crypto_key.name=crypto_key.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_crypto_key_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyRequest() + + request.crypto_key.name = 'crypto_key.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.update_crypto_key(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', + 'crypto_key.name=crypto_key.name/value', + ) in kw['metadata'] + + +def test_update_crypto_key_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_crypto_key( + crypto_key=resources.CryptoKey(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].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(): + client = KeyManagementServiceClient( + 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_crypto_key( + service.UpdateCryptoKeyRequest(), + crypto_key=resources.CryptoKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_crypto_key_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_crypto_key( + crypto_key=resources.CryptoKey(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].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 +async def test_update_crypto_key_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_key( + service.UpdateCryptoKeyRequest(), + crypto_key=resources.CryptoKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@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, + ) + + # 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + ) + response = client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +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. + client = KeyManagementServiceClient( + 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_crypto_key_version), + '__call__') as call: + client.update_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyVersionRequest() + + +@pytest.mark.asyncio +async def test_update_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + )) + response = await client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_update_crypto_key_version_async_from_dict(): + await test_update_crypto_key_version_async(request_type=dict) + + +def test_update_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyVersionRequest() + + request.crypto_key_version.name = 'crypto_key_version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.update_crypto_key_version(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', + 'crypto_key_version.name=crypto_key_version.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyVersionRequest() + + request.crypto_key_version.name = 'crypto_key_version.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.update_crypto_key_version(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', + 'crypto_key_version.name=crypto_key_version.name/value', + ) in kw['metadata'] + + +def test_update_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_crypto_key_version( + crypto_key_version=resources.CryptoKeyVersion(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].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(): + client = KeyManagementServiceClient( + 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_crypto_key_version( + service.UpdateCryptoKeyVersionRequest(), + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_crypto_key_version( + crypto_key_version=resources.CryptoKeyVersion(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].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 +async def test_update_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_version( + service.UpdateCryptoKeyVersionRequest(), + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@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, + ) + + # 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_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + rotation_period=duration_pb2.Duration(seconds=751), + ) + response = client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + + +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. + client = KeyManagementServiceClient( + 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_crypto_key_primary_version), + '__call__') as call: + client.update_crypto_key_primary_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() + + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyPrimaryVersionRequest): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + )) + response = await client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_async_from_dict(): + await test_update_crypto_key_primary_version_async(request_type=dict) + + +def test_update_crypto_key_primary_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyPrimaryVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.update_crypto_key_primary_version(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_update_crypto_key_primary_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyPrimaryVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.update_crypto_key_primary_version(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_update_crypto_key_primary_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_crypto_key_primary_version( + name='name_value', + crypto_key_version_id='crypto_key_version_id_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 + 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(): + client = KeyManagementServiceClient( + 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_crypto_key_primary_version( + service.UpdateCryptoKeyPrimaryVersionRequest(), + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_crypto_key_primary_version( + name='name_value', + crypto_key_version_id='crypto_key_version_id_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 + arg = args[0].crypto_key_version_id + mock_val = 'crypto_key_version_id_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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_crypto_key_primary_version( + service.UpdateCryptoKeyPrimaryVersionRequest(), + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + + +@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, + ) + + # 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.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + ) + response = client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DestroyCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +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. + client = KeyManagementServiceClient( + 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.destroy_crypto_key_version), + '__call__') as call: + client.destroy_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DestroyCryptoKeyVersionRequest() + + +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.DestroyCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + 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.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + )) + response = await client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DestroyCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_async_from_dict(): + await test_destroy_crypto_key_version_async(request_type=dict) + + +def test_destroy_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DestroyCryptoKeyVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.destroy_crypto_key_version(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_destroy_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DestroyCryptoKeyVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.destroy_crypto_key_version(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_destroy_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.destroy_crypto_key_version( + 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_destroy_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + 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.destroy_crypto_key_version( + service.DestroyCryptoKeyVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.destroy_crypto_key_version( + 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_destroy_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.destroy_crypto_key_version( + service.DestroyCryptoKeyVersionRequest(), + name='name_value', + ) + + +@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, + ) + + # 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.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + ) + response = client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +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. + client = KeyManagementServiceClient( + 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.restore_crypto_key_version), + '__call__') as call: + client.restore_crypto_key_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreCryptoKeyVersionRequest() + + +@pytest.mark.asyncio +async def test_restore_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.RestoreCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + 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.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + reimport_eligible=True, + )) + response = await client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreCryptoKeyVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_restore_crypto_key_version_async_from_dict(): + await test_restore_crypto_key_version_async(request_type=dict) + + +def test_restore_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreCryptoKeyVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.restore_crypto_key_version(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_restore_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreCryptoKeyVersionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.restore_crypto_key_version(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_restore_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_crypto_key_version( + 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_restore_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + 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.restore_crypto_key_version( + service.RestoreCryptoKeyVersionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_restore_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_crypto_key_version( + 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_restore_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.restore_crypto_key_version( + service.RestoreCryptoKeyVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.EncryptRequest, + dict, +]) +def test_encrypt(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + 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.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.EncryptResponse( + name='name_value', + ciphertext=b'ciphertext_blob', + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.EncryptRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.EncryptResponse) + assert response.name == 'name_value' + assert response.ciphertext == b'ciphertext_blob' + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +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. + client = KeyManagementServiceClient( + 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.encrypt), + '__call__') as call: + client.encrypt() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.EncryptRequest() + + +@pytest.mark.asyncio +async def test_encrypt_async(transport: str = 'grpc_asyncio', request_type=service.EncryptRequest): + client = KeyManagementServiceAsyncClient( + 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.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse( + name='name_value', + ciphertext=b'ciphertext_blob', + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.EncryptRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.EncryptResponse) + assert response.name == 'name_value' + assert response.ciphertext == b'ciphertext_blob' + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_encrypt_async_from_dict(): + await test_encrypt_async(request_type=dict) + + +def test_encrypt_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EncryptRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + call.return_value = service.EncryptResponse() + client.encrypt(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_encrypt_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EncryptRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse()) + await client.encrypt(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_encrypt_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.EncryptResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.encrypt( + name='name_value', + plaintext=b'plaintext_blob', + ) + + # 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 + arg = args[0].plaintext + mock_val = b'plaintext_blob' + assert arg == mock_val + + +def test_encrypt_flattened_error(): + client = KeyManagementServiceClient( + 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.encrypt( + service.EncryptRequest(), + name='name_value', + plaintext=b'plaintext_blob', + ) + + +@pytest.mark.asyncio +async def test_encrypt_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.EncryptResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.encrypt( + name='name_value', + plaintext=b'plaintext_blob', + ) + + # 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 + arg = args[0].plaintext + mock_val = b'plaintext_blob' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_encrypt_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.encrypt( + service.EncryptRequest(), + name='name_value', + plaintext=b'plaintext_blob', + ) + + +@pytest.mark.parametrize("request_type", [ + service.DecryptRequest, + dict, +]) +def test_decrypt(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + 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.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecryptResponse( + plaintext=b'plaintext_blob', + used_primary=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DecryptRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.DecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.used_primary is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +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. + client = KeyManagementServiceClient( + 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.decrypt), + '__call__') as call: + client.decrypt() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DecryptRequest() + + +@pytest.mark.asyncio +async def test_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.DecryptRequest): + client = KeyManagementServiceAsyncClient( + 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.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse( + plaintext=b'plaintext_blob', + used_primary=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DecryptRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.DecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.used_primary is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_decrypt_async_from_dict(): + await test_decrypt_async(request_type=dict) + + +def test_decrypt_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DecryptRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + call.return_value = service.DecryptResponse() + client.decrypt(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_decrypt_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DecryptRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse()) + await client.decrypt(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_decrypt_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecryptResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.decrypt( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + # 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 + arg = args[0].ciphertext + mock_val = b'ciphertext_blob' + assert arg == mock_val + + +def test_decrypt_flattened_error(): + client = KeyManagementServiceClient( + 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.decrypt( + service.DecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + +@pytest.mark.asyncio +async def test_decrypt_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecryptResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.decrypt( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + # 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 + arg = args[0].ciphertext + mock_val = b'ciphertext_blob' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_decrypt_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.decrypt( + service.DecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + +@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, + ) + + # 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.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricSignResponse( + signature=b'signature_blob', + verified_digest_crc32c=True, + name='name_value', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.AsymmetricSignRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricSignResponse) + assert response.signature == b'signature_blob' + assert response.verified_digest_crc32c is True + assert response.name == 'name_value' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +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. + client = KeyManagementServiceClient( + 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.asymmetric_sign), + '__call__') as call: + client.asymmetric_sign() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.AsymmetricSignRequest() + + +@pytest.mark.asyncio +async def test_asymmetric_sign_async(transport: str = 'grpc_asyncio', request_type=service.AsymmetricSignRequest): + client = KeyManagementServiceAsyncClient( + 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.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse( + signature=b'signature_blob', + verified_digest_crc32c=True, + name='name_value', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.AsymmetricSignRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricSignResponse) + assert response.signature == b'signature_blob' + assert response.verified_digest_crc32c is True + assert response.name == 'name_value' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_asymmetric_sign_async_from_dict(): + await test_asymmetric_sign_async(request_type=dict) + + +def test_asymmetric_sign_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AsymmetricSignRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + call.return_value = service.AsymmetricSignResponse() + client.asymmetric_sign(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_asymmetric_sign_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AsymmetricSignRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse()) + await client.asymmetric_sign(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_asymmetric_sign_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricSignResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.asymmetric_sign( + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + + # 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 + arg = args[0].digest + mock_val = service.Digest(sha256=b'sha256_blob') + assert arg == mock_val + + +def test_asymmetric_sign_flattened_error(): + client = KeyManagementServiceClient( + 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.asymmetric_sign( + service.AsymmetricSignRequest(), + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + + +@pytest.mark.asyncio +async def test_asymmetric_sign_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricSignResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.asymmetric_sign( + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + + # 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 + arg = args[0].digest + mock_val = service.Digest(sha256=b'sha256_blob') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_asymmetric_sign_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.asymmetric_sign( + service.AsymmetricSignRequest(), + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + + +@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, + ) + + # 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.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricDecryptResponse( + plaintext=b'plaintext_blob', + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.AsymmetricDecryptRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricDecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.verified_ciphertext_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +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. + client = KeyManagementServiceClient( + 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.asymmetric_decrypt), + '__call__') as call: + client.asymmetric_decrypt() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.AsymmetricDecryptRequest() + + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.AsymmetricDecryptRequest): + client = KeyManagementServiceAsyncClient( + 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.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse( + plaintext=b'plaintext_blob', + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.AsymmetricDecryptRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricDecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.verified_ciphertext_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_async_from_dict(): + await test_asymmetric_decrypt_async(request_type=dict) + + +def test_asymmetric_decrypt_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AsymmetricDecryptRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + call.return_value = service.AsymmetricDecryptResponse() + client.asymmetric_decrypt(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_asymmetric_decrypt_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AsymmetricDecryptRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse()) + await client.asymmetric_decrypt(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_asymmetric_decrypt_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricDecryptResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.asymmetric_decrypt( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + # 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 + arg = args[0].ciphertext + mock_val = b'ciphertext_blob' + assert arg == mock_val + + +def test_asymmetric_decrypt_flattened_error(): + client = KeyManagementServiceClient( + 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.asymmetric_decrypt( + service.AsymmetricDecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricDecryptResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.asymmetric_decrypt( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + # 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 + arg = args[0].ciphertext + mock_val = b'ciphertext_blob' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.asymmetric_decrypt( + service.AsymmetricDecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + +@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, + ) + + # 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.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacSignResponse( + name='name_value', + mac=b'mac_blob', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.MacSignRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacSignResponse) + assert response.name == 'name_value' + assert response.mac == b'mac_blob' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +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. + client = KeyManagementServiceClient( + 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.mac_sign), + '__call__') as call: + client.mac_sign() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.MacSignRequest() + + +@pytest.mark.asyncio +async def test_mac_sign_async(transport: str = 'grpc_asyncio', request_type=service.MacSignRequest): + client = KeyManagementServiceAsyncClient( + 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.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse( + name='name_value', + mac=b'mac_blob', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.MacSignRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacSignResponse) + assert response.name == 'name_value' + assert response.mac == b'mac_blob' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_mac_sign_async_from_dict(): + await test_mac_sign_async(request_type=dict) + + +def test_mac_sign_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.MacSignRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + call.return_value = service.MacSignResponse() + client.mac_sign(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_mac_sign_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.MacSignRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse()) + await client.mac_sign(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_mac_sign_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacSignResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mac_sign( + name='name_value', + data=b'data_blob', + ) + + # 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 + arg = args[0].data + mock_val = b'data_blob' + assert arg == mock_val + + +def test_mac_sign_flattened_error(): + client = KeyManagementServiceClient( + 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.mac_sign( + service.MacSignRequest(), + name='name_value', + data=b'data_blob', + ) + + +@pytest.mark.asyncio +async def test_mac_sign_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacSignResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mac_sign( + name='name_value', + data=b'data_blob', + ) + + # 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 + arg = args[0].data + mock_val = b'data_blob' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_mac_sign_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.mac_sign( + service.MacSignRequest(), + name='name_value', + data=b'data_blob', + ) + + +@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, + ) + + # 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.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacVerifyResponse( + name='name_value', + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.MacVerifyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacVerifyResponse) + assert response.name == 'name_value' + assert response.success is True + assert response.verified_data_crc32c is True + assert response.verified_mac_crc32c is True + assert response.verified_success_integrity is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +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. + client = KeyManagementServiceClient( + 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.mac_verify), + '__call__') as call: + client.mac_verify() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.MacVerifyRequest() + + +@pytest.mark.asyncio +async def test_mac_verify_async(transport: str = 'grpc_asyncio', request_type=service.MacVerifyRequest): + client = KeyManagementServiceAsyncClient( + 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.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse( + name='name_value', + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.MacVerifyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacVerifyResponse) + assert response.name == 'name_value' + assert response.success is True + assert response.verified_data_crc32c is True + assert response.verified_mac_crc32c is True + assert response.verified_success_integrity is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_mac_verify_async_from_dict(): + await test_mac_verify_async(request_type=dict) + + +def test_mac_verify_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.MacVerifyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + call.return_value = service.MacVerifyResponse() + client.mac_verify(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_mac_verify_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.MacVerifyRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse()) + await client.mac_verify(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_mac_verify_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacVerifyResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mac_verify( + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + + # 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 + 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(): + client = KeyManagementServiceClient( + 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.mac_verify( + service.MacVerifyRequest(), + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + + +@pytest.mark.asyncio +async def test_mac_verify_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacVerifyResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mac_verify( + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + + # 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 + 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 +async def test_mac_verify_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.mac_verify( + service.MacVerifyRequest(), + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + + +@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, + ) + + # 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.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse( + data=b'data_blob', + ) + response = client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateRandomBytesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateRandomBytesResponse) + assert response.data == b'data_blob' + + +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. + client = KeyManagementServiceClient( + 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.generate_random_bytes), + '__call__') as call: + client.generate_random_bytes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateRandomBytesRequest() + + +@pytest.mark.asyncio +async def test_generate_random_bytes_async(transport: str = 'grpc_asyncio', request_type=service.GenerateRandomBytesRequest): + client = KeyManagementServiceAsyncClient( + 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.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse( + data=b'data_blob', + )) + response = await client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateRandomBytesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateRandomBytesResponse) + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_generate_random_bytes_async_from_dict(): + await test_generate_random_bytes_async(request_type=dict) + + +def test_generate_random_bytes_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateRandomBytesRequest() + + request.location = 'location/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + call.return_value = service.GenerateRandomBytesResponse() + client.generate_random_bytes(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', + 'location=location/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_random_bytes_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateRandomBytesRequest() + + request.location = 'location/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse()) + await client.generate_random_bytes(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', + 'location=location/value', + ) in kw['metadata'] + + +def test_generate_random_bytes_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_random_bytes( + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # 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].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(): + client = KeyManagementServiceClient( + 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.generate_random_bytes( + service.GenerateRandomBytesRequest(), + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + +@pytest.mark.asyncio +async def test_generate_random_bytes_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_random_bytes( + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # 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].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 +async def test_generate_random_bytes_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + 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.generate_random_bytes( + service.GenerateRandomBytesRequest(), + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + client_options={"credentials_file": "credentials.json"}, + 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(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = KeyManagementServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.KeyManagementServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, +]) +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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.KeyManagementServiceGrpcTransport, + ) + +def test_key_management_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.KeyManagementServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_key_management_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.KeyManagementServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_key_rings', + 'list_crypto_keys', + 'list_crypto_key_versions', + 'list_import_jobs', + 'get_key_ring', + 'get_crypto_key', + 'get_crypto_key_version', + 'get_public_key', + 'get_import_job', + 'create_key_ring', + 'create_crypto_key', + 'create_crypto_key_version', + 'import_crypto_key_version', + 'create_import_job', + 'update_crypto_key', + 'update_crypto_key_version', + 'update_crypto_key_primary_version', + 'destroy_crypto_key_version', + 'restore_crypto_key_version', + 'encrypt', + 'decrypt', + 'asymmetric_sign', + 'asymmetric_decrypt', + 'mac_sign', + 'mac_verify', + 'generate_random_bytes', + '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_key_management_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.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KeyManagementServiceTransport( + 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_key_management_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.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KeyManagementServiceTransport() + adc.assert_called_once() + + +def test_key_management_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) + KeyManagementServiceClient() + 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.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + ], +) +def test_key_management_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.KeyManagementServiceGrpcTransport, grpc_helpers), + (transports.KeyManagementServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_key_management_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.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) +def test_key_management_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_key_management_service_host_no_port(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), + ) + assert client.transport._host == 'cloudkms.googleapis.com:443' + + +def test_key_management_service_host_with_port(): + client = KeyManagementServiceClient( + 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_key_management_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KeyManagementServiceGrpcTransport( + 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_key_management_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KeyManagementServiceGrpcAsyncIOTransport( + 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.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) +def test_key_management_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.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) +def test_key_management_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_crypto_key_path(): + project = "squid" + location = "clam" + key_ring = "whelk" + crypto_key = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + actual = KeyManagementServiceClient.crypto_key_path(project, location, key_ring, crypto_key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "key_ring": "cuttlefish", + "crypto_key": "mussel", + } + path = KeyManagementServiceClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_crypto_key_path(path) + assert expected == actual + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + actual = KeyManagementServiceClient.crypto_key_version_path(project, location, key_ring, crypto_key, crypto_key_version) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = KeyManagementServiceClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_crypto_key_version_path(path) + assert expected == actual + +def test_import_job_path(): + project = "cuttlefish" + location = "mussel" + key_ring = "winkle" + import_job = "nautilus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format(project=project, location=location, key_ring=key_ring, import_job=import_job, ) + actual = KeyManagementServiceClient.import_job_path(project, location, key_ring, import_job) + assert expected == actual + + +def test_parse_import_job_path(): + expected = { + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "import_job": "clam", + } + path = KeyManagementServiceClient.import_job_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_import_job_path(path) + assert expected == actual + +def test_key_ring_path(): + project = "whelk" + location = "octopus" + key_ring = "oyster" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}".format(project=project, location=location, key_ring=key_ring, ) + actual = KeyManagementServiceClient.key_ring_path(project, location, key_ring) + assert expected == actual + + +def test_parse_key_ring_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "key_ring": "mussel", + } + path = KeyManagementServiceClient.key_ring_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_key_ring_path(path) + assert expected == actual + +def test_public_key_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + actual = KeyManagementServiceClient.public_key_path(project, location, key_ring, crypto_key, crypto_key_version) + assert expected == actual + + +def test_parse_public_key_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = KeyManagementServiceClient.public_key_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_public_key_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = KeyManagementServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = KeyManagementServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = KeyManagementServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = KeyManagementServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = KeyManagementServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = KeyManagementServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = KeyManagementServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = KeyManagementServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = KeyManagementServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = KeyManagementServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.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.KeyManagementServiceTransport, '_prep_wrapped_messages') as prep: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.KeyManagementServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = KeyManagementServiceClient.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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceAsyncClient( + 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 = KeyManagementServiceClient( + 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 = KeyManagementServiceClient( + 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", [ + (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 413728318ce4783db32f29083140ebf7e6b6aa76 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 24 Jan 2022 20:28:27 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../key_management_service/async_client.py | 39 +- .../services/key_management_service/client.py | 128 +- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - owl-bot-staging/v1/docs/conf.py | 376 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/docs/kms_v1/key_management_service.rst | 10 - owl-bot-staging/v1/docs/kms_v1/services.rst | 6 - owl-bot-staging/v1/docs/kms_v1/types.rst | 7 - .../v1/google/cloud/kms/__init__.py | 119 - owl-bot-staging/v1/google/cloud/kms/py.typed | 2 - .../v1/google/cloud/kms_v1/__init__.py | 120 - .../google/cloud/kms_v1/gapic_metadata.json | 283 - .../v1/google/cloud/kms_v1/py.typed | 2 - .../google/cloud/kms_v1/services/__init__.py | 15 - .../key_management_service/__init__.py | 22 - .../key_management_service/async_client.py | 3184 ------ .../services/key_management_service/client.py | 3254 ------ .../services/key_management_service/pagers.py | 503 - .../transports/__init__.py | 33 - .../key_management_service/transports/base.py | 696 -- .../key_management_service/transports/grpc.py | 1115 --- .../transports/grpc_asyncio.py | 1120 --- .../v1/google/cloud/kms_v1/types/__init__.py | 118 - .../v1/google/cloud/kms_v1/types/resources.py | 843 -- .../v1/google/cloud/kms_v1/types/service.py | 1974 ---- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../v1/scripts/fixup_kms_v1_keywords.py | 204 - owl-bot-staging/v1/setup.py | 55 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../v1/tests/unit/gapic/kms_v1/__init__.py | 16 - .../kms_v1/test_key_management_service.py | 8912 ----------------- .../kms_v1/test_key_management_service.py | 133 + 37 files changed, 256 insertions(+), 23291 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/kms_v1/key_management_service.rst delete mode 100644 owl-bot-staging/v1/docs/kms_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/kms_v1/types.rst delete mode 100644 owl-bot-staging/v1/google/cloud/kms/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py delete mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/types/service.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/kms_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py 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/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 6bc3e283..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/kms/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 97846726..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/kms *.py -recursive-include google/cloud/kms_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 9574e81c..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Kms API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Kms API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index e69a1dd2..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- 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. -# -# -# google-cloud-kms documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-kms" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-kms-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-kms.tex", - u"google-cloud-kms Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-kms", - u"Google Cloud Kms Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-kms", - u"google-cloud-kms Documentation", - author, - "google-cloud-kms", - "GAPIC library for Google Cloud Kms API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index ce6aa927..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - kms_v1/services - kms_v1/types diff --git a/owl-bot-staging/v1/docs/kms_v1/key_management_service.rst b/owl-bot-staging/v1/docs/kms_v1/key_management_service.rst deleted file mode 100644 index b34ce028..00000000 --- a/owl-bot-staging/v1/docs/kms_v1/key_management_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -KeyManagementService --------------------------------------- - -.. automodule:: google.cloud.kms_v1.services.key_management_service - :members: - :inherited-members: - -.. automodule:: google.cloud.kms_v1.services.key_management_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/kms_v1/services.rst b/owl-bot-staging/v1/docs/kms_v1/services.rst deleted file mode 100644 index 1edbf1d6..00000000 --- a/owl-bot-staging/v1/docs/kms_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Kms v1 API -==================================== -.. toctree:: - :maxdepth: 2 - - key_management_service diff --git a/owl-bot-staging/v1/docs/kms_v1/types.rst b/owl-bot-staging/v1/docs/kms_v1/types.rst deleted file mode 100644 index fe1026e9..00000000 --- a/owl-bot-staging/v1/docs/kms_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Kms v1 API -================================= - -.. automodule:: google.cloud.kms_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/kms/__init__.py b/owl-bot-staging/v1/google/cloud/kms/__init__.py deleted file mode 100644 index 77107dbb..00000000 --- a/owl-bot-staging/v1/google/cloud/kms/__init__.py +++ /dev/null @@ -1,119 +0,0 @@ -# -*- 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 google.cloud.kms_v1.services.key_management_service.client import KeyManagementServiceClient -from google.cloud.kms_v1.services.key_management_service.async_client import KeyManagementServiceAsyncClient - -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 -from google.cloud.kms_v1.types.resources import ExternalProtectionLevelOptions -from google.cloud.kms_v1.types.resources import ImportJob -from google.cloud.kms_v1.types.resources import KeyOperationAttestation -from google.cloud.kms_v1.types.resources import KeyRing -from google.cloud.kms_v1.types.resources import PublicKey -from google.cloud.kms_v1.types.resources import ProtectionLevel -from google.cloud.kms_v1.types.service import AsymmetricDecryptRequest -from google.cloud.kms_v1.types.service import AsymmetricDecryptResponse -from google.cloud.kms_v1.types.service import AsymmetricSignRequest -from google.cloud.kms_v1.types.service import AsymmetricSignResponse -from google.cloud.kms_v1.types.service import CreateCryptoKeyRequest -from google.cloud.kms_v1.types.service import CreateCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import CreateImportJobRequest -from google.cloud.kms_v1.types.service import CreateKeyRingRequest -from google.cloud.kms_v1.types.service import DecryptRequest -from google.cloud.kms_v1.types.service import DecryptResponse -from google.cloud.kms_v1.types.service import DestroyCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import Digest -from google.cloud.kms_v1.types.service import EncryptRequest -from google.cloud.kms_v1.types.service import EncryptResponse -from google.cloud.kms_v1.types.service import GenerateRandomBytesRequest -from google.cloud.kms_v1.types.service import GenerateRandomBytesResponse -from google.cloud.kms_v1.types.service import GetCryptoKeyRequest -from google.cloud.kms_v1.types.service import GetCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import GetImportJobRequest -from google.cloud.kms_v1.types.service import GetKeyRingRequest -from google.cloud.kms_v1.types.service import GetPublicKeyRequest -from google.cloud.kms_v1.types.service import ImportCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import ListCryptoKeysRequest -from google.cloud.kms_v1.types.service import ListCryptoKeysResponse -from google.cloud.kms_v1.types.service import ListCryptoKeyVersionsRequest -from google.cloud.kms_v1.types.service import ListCryptoKeyVersionsResponse -from google.cloud.kms_v1.types.service import ListImportJobsRequest -from google.cloud.kms_v1.types.service import ListImportJobsResponse -from google.cloud.kms_v1.types.service import ListKeyRingsRequest -from google.cloud.kms_v1.types.service import ListKeyRingsResponse -from google.cloud.kms_v1.types.service import LocationMetadata -from google.cloud.kms_v1.types.service import MacSignRequest -from google.cloud.kms_v1.types.service import MacSignResponse -from google.cloud.kms_v1.types.service import MacVerifyRequest -from google.cloud.kms_v1.types.service import MacVerifyResponse -from google.cloud.kms_v1.types.service import RestoreCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import UpdateCryptoKeyPrimaryVersionRequest -from google.cloud.kms_v1.types.service import UpdateCryptoKeyRequest -from google.cloud.kms_v1.types.service import UpdateCryptoKeyVersionRequest - -__all__ = ('KeyManagementServiceClient', - 'KeyManagementServiceAsyncClient', - 'CryptoKey', - 'CryptoKeyVersion', - 'CryptoKeyVersionTemplate', - 'ExternalProtectionLevelOptions', - 'ImportJob', - 'KeyOperationAttestation', - 'KeyRing', - 'PublicKey', - 'ProtectionLevel', - 'AsymmetricDecryptRequest', - 'AsymmetricDecryptResponse', - 'AsymmetricSignRequest', - 'AsymmetricSignResponse', - 'CreateCryptoKeyRequest', - 'CreateCryptoKeyVersionRequest', - 'CreateImportJobRequest', - 'CreateKeyRingRequest', - 'DecryptRequest', - 'DecryptResponse', - 'DestroyCryptoKeyVersionRequest', - 'Digest', - 'EncryptRequest', - 'EncryptResponse', - 'GenerateRandomBytesRequest', - 'GenerateRandomBytesResponse', - 'GetCryptoKeyRequest', - 'GetCryptoKeyVersionRequest', - 'GetImportJobRequest', - 'GetKeyRingRequest', - 'GetPublicKeyRequest', - 'ImportCryptoKeyVersionRequest', - 'ListCryptoKeysRequest', - 'ListCryptoKeysResponse', - 'ListCryptoKeyVersionsRequest', - 'ListCryptoKeyVersionsResponse', - 'ListImportJobsRequest', - 'ListImportJobsResponse', - 'ListKeyRingsRequest', - 'ListKeyRingsResponse', - 'LocationMetadata', - 'MacSignRequest', - 'MacSignResponse', - 'MacVerifyRequest', - 'MacVerifyResponse', - 'RestoreCryptoKeyVersionRequest', - 'UpdateCryptoKeyPrimaryVersionRequest', - 'UpdateCryptoKeyRequest', - 'UpdateCryptoKeyVersionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/kms/py.typed b/owl-bot-staging/v1/google/cloud/kms/py.typed deleted file mode 100644 index 3720b5f2..00000000 --- a/owl-bot-staging/v1/google/cloud/kms/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-kms package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/__init__.py deleted file mode 100644 index 23e95304..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/__init__.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- 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 .services.key_management_service import KeyManagementServiceClient -from .services.key_management_service import KeyManagementServiceAsyncClient - -from .types.resources import CryptoKey -from .types.resources import CryptoKeyVersion -from .types.resources import CryptoKeyVersionTemplate -from .types.resources import ExternalProtectionLevelOptions -from .types.resources import ImportJob -from .types.resources import KeyOperationAttestation -from .types.resources import KeyRing -from .types.resources import PublicKey -from .types.resources import ProtectionLevel -from .types.service import AsymmetricDecryptRequest -from .types.service import AsymmetricDecryptResponse -from .types.service import AsymmetricSignRequest -from .types.service import AsymmetricSignResponse -from .types.service import CreateCryptoKeyRequest -from .types.service import CreateCryptoKeyVersionRequest -from .types.service import CreateImportJobRequest -from .types.service import CreateKeyRingRequest -from .types.service import DecryptRequest -from .types.service import DecryptResponse -from .types.service import DestroyCryptoKeyVersionRequest -from .types.service import Digest -from .types.service import EncryptRequest -from .types.service import EncryptResponse -from .types.service import GenerateRandomBytesRequest -from .types.service import GenerateRandomBytesResponse -from .types.service import GetCryptoKeyRequest -from .types.service import GetCryptoKeyVersionRequest -from .types.service import GetImportJobRequest -from .types.service import GetKeyRingRequest -from .types.service import GetPublicKeyRequest -from .types.service import ImportCryptoKeyVersionRequest -from .types.service import ListCryptoKeysRequest -from .types.service import ListCryptoKeysResponse -from .types.service import ListCryptoKeyVersionsRequest -from .types.service import ListCryptoKeyVersionsResponse -from .types.service import ListImportJobsRequest -from .types.service import ListImportJobsResponse -from .types.service import ListKeyRingsRequest -from .types.service import ListKeyRingsResponse -from .types.service import LocationMetadata -from .types.service import MacSignRequest -from .types.service import MacSignResponse -from .types.service import MacVerifyRequest -from .types.service import MacVerifyResponse -from .types.service import RestoreCryptoKeyVersionRequest -from .types.service import UpdateCryptoKeyPrimaryVersionRequest -from .types.service import UpdateCryptoKeyRequest -from .types.service import UpdateCryptoKeyVersionRequest - -__all__ = ( - 'KeyManagementServiceAsyncClient', -'AsymmetricDecryptRequest', -'AsymmetricDecryptResponse', -'AsymmetricSignRequest', -'AsymmetricSignResponse', -'CreateCryptoKeyRequest', -'CreateCryptoKeyVersionRequest', -'CreateImportJobRequest', -'CreateKeyRingRequest', -'CryptoKey', -'CryptoKeyVersion', -'CryptoKeyVersionTemplate', -'DecryptRequest', -'DecryptResponse', -'DestroyCryptoKeyVersionRequest', -'Digest', -'EncryptRequest', -'EncryptResponse', -'ExternalProtectionLevelOptions', -'GenerateRandomBytesRequest', -'GenerateRandomBytesResponse', -'GetCryptoKeyRequest', -'GetCryptoKeyVersionRequest', -'GetImportJobRequest', -'GetKeyRingRequest', -'GetPublicKeyRequest', -'ImportCryptoKeyVersionRequest', -'ImportJob', -'KeyManagementServiceClient', -'KeyOperationAttestation', -'KeyRing', -'ListCryptoKeyVersionsRequest', -'ListCryptoKeyVersionsResponse', -'ListCryptoKeysRequest', -'ListCryptoKeysResponse', -'ListImportJobsRequest', -'ListImportJobsResponse', -'ListKeyRingsRequest', -'ListKeyRingsResponse', -'LocationMetadata', -'MacSignRequest', -'MacSignResponse', -'MacVerifyRequest', -'MacVerifyResponse', -'ProtectionLevel', -'PublicKey', -'RestoreCryptoKeyVersionRequest', -'UpdateCryptoKeyPrimaryVersionRequest', -'UpdateCryptoKeyRequest', -'UpdateCryptoKeyVersionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json deleted file mode 100644 index 582da425..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json +++ /dev/null @@ -1,283 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.kms_v1", - "protoPackage": "google.cloud.kms.v1", - "schema": "1.0", - "services": { - "KeyManagementService": { - "clients": { - "grpc": { - "libraryClient": "KeyManagementServiceClient", - "rpcs": { - "AsymmetricDecrypt": { - "methods": [ - "asymmetric_decrypt" - ] - }, - "AsymmetricSign": { - "methods": [ - "asymmetric_sign" - ] - }, - "CreateCryptoKey": { - "methods": [ - "create_crypto_key" - ] - }, - "CreateCryptoKeyVersion": { - "methods": [ - "create_crypto_key_version" - ] - }, - "CreateImportJob": { - "methods": [ - "create_import_job" - ] - }, - "CreateKeyRing": { - "methods": [ - "create_key_ring" - ] - }, - "Decrypt": { - "methods": [ - "decrypt" - ] - }, - "DestroyCryptoKeyVersion": { - "methods": [ - "destroy_crypto_key_version" - ] - }, - "Encrypt": { - "methods": [ - "encrypt" - ] - }, - "GenerateRandomBytes": { - "methods": [ - "generate_random_bytes" - ] - }, - "GetCryptoKey": { - "methods": [ - "get_crypto_key" - ] - }, - "GetCryptoKeyVersion": { - "methods": [ - "get_crypto_key_version" - ] - }, - "GetImportJob": { - "methods": [ - "get_import_job" - ] - }, - "GetKeyRing": { - "methods": [ - "get_key_ring" - ] - }, - "GetPublicKey": { - "methods": [ - "get_public_key" - ] - }, - "ImportCryptoKeyVersion": { - "methods": [ - "import_crypto_key_version" - ] - }, - "ListCryptoKeyVersions": { - "methods": [ - "list_crypto_key_versions" - ] - }, - "ListCryptoKeys": { - "methods": [ - "list_crypto_keys" - ] - }, - "ListImportJobs": { - "methods": [ - "list_import_jobs" - ] - }, - "ListKeyRings": { - "methods": [ - "list_key_rings" - ] - }, - "MacSign": { - "methods": [ - "mac_sign" - ] - }, - "MacVerify": { - "methods": [ - "mac_verify" - ] - }, - "RestoreCryptoKeyVersion": { - "methods": [ - "restore_crypto_key_version" - ] - }, - "UpdateCryptoKey": { - "methods": [ - "update_crypto_key" - ] - }, - "UpdateCryptoKeyPrimaryVersion": { - "methods": [ - "update_crypto_key_primary_version" - ] - }, - "UpdateCryptoKeyVersion": { - "methods": [ - "update_crypto_key_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "KeyManagementServiceAsyncClient", - "rpcs": { - "AsymmetricDecrypt": { - "methods": [ - "asymmetric_decrypt" - ] - }, - "AsymmetricSign": { - "methods": [ - "asymmetric_sign" - ] - }, - "CreateCryptoKey": { - "methods": [ - "create_crypto_key" - ] - }, - "CreateCryptoKeyVersion": { - "methods": [ - "create_crypto_key_version" - ] - }, - "CreateImportJob": { - "methods": [ - "create_import_job" - ] - }, - "CreateKeyRing": { - "methods": [ - "create_key_ring" - ] - }, - "Decrypt": { - "methods": [ - "decrypt" - ] - }, - "DestroyCryptoKeyVersion": { - "methods": [ - "destroy_crypto_key_version" - ] - }, - "Encrypt": { - "methods": [ - "encrypt" - ] - }, - "GenerateRandomBytes": { - "methods": [ - "generate_random_bytes" - ] - }, - "GetCryptoKey": { - "methods": [ - "get_crypto_key" - ] - }, - "GetCryptoKeyVersion": { - "methods": [ - "get_crypto_key_version" - ] - }, - "GetImportJob": { - "methods": [ - "get_import_job" - ] - }, - "GetKeyRing": { - "methods": [ - "get_key_ring" - ] - }, - "GetPublicKey": { - "methods": [ - "get_public_key" - ] - }, - "ImportCryptoKeyVersion": { - "methods": [ - "import_crypto_key_version" - ] - }, - "ListCryptoKeyVersions": { - "methods": [ - "list_crypto_key_versions" - ] - }, - "ListCryptoKeys": { - "methods": [ - "list_crypto_keys" - ] - }, - "ListImportJobs": { - "methods": [ - "list_import_jobs" - ] - }, - "ListKeyRings": { - "methods": [ - "list_key_rings" - ] - }, - "MacSign": { - "methods": [ - "mac_sign" - ] - }, - "MacVerify": { - "methods": [ - "mac_verify" - ] - }, - "RestoreCryptoKeyVersion": { - "methods": [ - "restore_crypto_key_version" - ] - }, - "UpdateCryptoKey": { - "methods": [ - "update_crypto_key" - ] - }, - "UpdateCryptoKeyPrimaryVersion": { - "methods": [ - "update_crypto_key_primary_version" - ] - }, - "UpdateCryptoKeyVersion": { - "methods": [ - "update_crypto_key_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/py.typed b/owl-bot-staging/v1/google/cloud/kms_v1/py.typed deleted file mode 100644 index 3720b5f2..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-kms package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- 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. -# diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/__init__.py deleted file mode 100644 index 5952e44c..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- 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 KeyManagementServiceClient -from .async_client import KeyManagementServiceAsyncClient - -__all__ = ( - 'KeyManagementServiceClient', - 'KeyManagementServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py deleted file mode 100644 index 500147a2..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py +++ /dev/null @@ -1,3184 +0,0 @@ -# -*- 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.key_management_service import pagers -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport -from .client import KeyManagementServiceClient - - -class KeyManagementServiceAsyncClient: - """Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - """ - - _client: KeyManagementServiceClient - - DEFAULT_ENDPOINT = KeyManagementServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT - - crypto_key_path = staticmethod(KeyManagementServiceClient.crypto_key_path) - parse_crypto_key_path = staticmethod(KeyManagementServiceClient.parse_crypto_key_path) - crypto_key_version_path = staticmethod(KeyManagementServiceClient.crypto_key_version_path) - parse_crypto_key_version_path = staticmethod(KeyManagementServiceClient.parse_crypto_key_version_path) - import_job_path = staticmethod(KeyManagementServiceClient.import_job_path) - parse_import_job_path = staticmethod(KeyManagementServiceClient.parse_import_job_path) - key_ring_path = staticmethod(KeyManagementServiceClient.key_ring_path) - parse_key_ring_path = staticmethod(KeyManagementServiceClient.parse_key_ring_path) - public_key_path = staticmethod(KeyManagementServiceClient.public_key_path) - parse_public_key_path = staticmethod(KeyManagementServiceClient.parse_public_key_path) - common_billing_account_path = staticmethod(KeyManagementServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(KeyManagementServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(KeyManagementServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(KeyManagementServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(KeyManagementServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(KeyManagementServiceClient.parse_common_organization_path) - common_project_path = staticmethod(KeyManagementServiceClient.common_project_path) - parse_common_project_path = staticmethod(KeyManagementServiceClient.parse_common_project_path) - common_location_path = staticmethod(KeyManagementServiceClient.common_location_path) - parse_common_location_path = staticmethod(KeyManagementServiceClient.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: - KeyManagementServiceAsyncClient: The constructed client. - """ - return KeyManagementServiceClient.from_service_account_info.__func__(KeyManagementServiceAsyncClient, 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: - KeyManagementServiceAsyncClient: The constructed client. - """ - return KeyManagementServiceClient.from_service_account_file.__func__(KeyManagementServiceAsyncClient, 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 KeyManagementServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> KeyManagementServiceTransport: - """Returns the transport used by the client instance. - - Returns: - KeyManagementServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(KeyManagementServiceClient).get_transport_class, type(KeyManagementServiceClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, KeyManagementServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the key management 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, ~.KeyManagementServiceTransport]): 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 = KeyManagementServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_key_rings(self, - request: Union[service.ListKeyRingsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListKeyRingsAsyncPager: - r"""Lists [KeyRings][google.cloud.kms.v1.KeyRing]. - - Args: - request (Union[google.cloud.kms_v1.types.ListKeyRingsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - parent (:class:`str`): - Required. The resource name of the location associated - with the [KeyRings][google.cloud.kms.v1.KeyRing], 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.key_management_service.pagers.ListKeyRingsAsyncPager: - Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.ListKeyRingsRequest(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_key_rings, - 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.ListKeyRingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_crypto_keys(self, - request: Union[service.ListCryptoKeysRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCryptoKeysAsyncPager: - r"""Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - Args: - request (Union[google.cloud.kms_v1.types.ListCryptoKeysRequest, dict]): - The request object. Request message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - parent (:class:`str`): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - - 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.key_management_service.pagers.ListCryptoKeysAsyncPager: - Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.ListCryptoKeysRequest(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_crypto_keys, - 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.ListCryptoKeysAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_crypto_key_versions(self, - request: Union[service.ListCryptoKeyVersionsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCryptoKeyVersionsAsyncPager: - r"""Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - Args: - request (Union[google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - parent (:class:`str`): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in - the format - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - - 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.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager: - Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.ListCryptoKeyVersionsRequest(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_crypto_key_versions, - 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.ListCryptoKeyVersionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_import_jobs(self, - request: Union[service.ListImportJobsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListImportJobsAsyncPager: - r"""Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. - - Args: - request (Union[google.cloud.kms_v1.types.ListImportJobsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - parent (:class:`str`): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - - 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.key_management_service.pagers.ListImportJobsAsyncPager: - Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.ListImportJobsRequest(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_import_jobs, - 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.ListImportJobsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_key_ring(self, - request: Union[service.GetKeyRingRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.KeyRing: - r"""Returns metadata for a given - [KeyRing][google.cloud.kms.v1.KeyRing]. - - Args: - request (Union[google.cloud.kms_v1.types.GetKeyRingRequest, dict]): - The request object. Request message for - [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. - name (:class:`str`): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the [KeyRing][google.cloud.kms.v1.KeyRing] 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.KeyRing: - 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. - # Sanity 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 = service.GetKeyRingRequest(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_key_ring, - 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 get_crypto_key(self, - request: Union[service.GetCryptoKeyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Returns metadata for a given - [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its - [primary][google.cloud.kms.v1.CryptoKey.primary] - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Args: - request (Union[google.cloud.kms_v1.types.GetCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. - name (:class:`str`): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] 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.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] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.GetCryptoKeyRequest(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_crypto_key, - 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 get_crypto_key_version(self, - request: Union[service.GetCryptoKeyVersionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Returns metadata for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Args: - request (Union[google.cloud.kms_v1.types.GetCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. - name (:class:`str`): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.GetCryptoKeyVersionRequest(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_crypto_key_version, - 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 get_public_key(self, - request: Union[service.GetPublicKeyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.PublicKey: - r"""Returns the public key for the given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] - or - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - Args: - request (Union[google.cloud.kms_v1.types.GetPublicKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - name (:class:`str`): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key 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.PublicKey: - The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.GetPublicKeyRequest(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_public_key, - 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 get_import_job(self, - request: Union[service.GetImportJobRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.ImportJob: - r"""Returns metadata for a given - [ImportJob][google.cloud.kms.v1.ImportJob]. - - Args: - request (Union[google.cloud.kms_v1.types.GetImportJobRequest, dict]): - The request object. Request message for - [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. - name (:class:`str`): - Required. The [name][google.cloud.kms.v1.ImportJob.name] - of the [ImportJob][google.cloud.kms.v1.ImportJob] 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.ImportJob: - 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. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", - which is a public/private key pair. You use the - wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the - import process. The nature of the wrapping key - depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be - set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be - used to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires - 3 days after it is created. Once expired, Cloud KMS - will no longer be able to import or unwrap any key - material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public - key. - - For more information, see [Importing a - key](\ https://cloud.google.com/kms/docs/importing-a-key). - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.GetImportJobRequest(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_import_job, - 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_key_ring(self, - request: Union[service.CreateKeyRingRequest, dict] = None, - *, - parent: str = None, - key_ring_id: str = None, - key_ring: resources.KeyRing = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.KeyRing: - r"""Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given - Project and Location. - - Args: - request (Union[google.cloud.kms_v1.types.CreateKeyRingRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. - parent (:class:`str`): - Required. The resource name of the location associated - with the [KeyRings][google.cloud.kms.v1.KeyRing], in the - format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_ring_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 ``key_ring_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_ring (:class:`google.cloud.kms_v1.types.KeyRing`): - Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with - initial field values. - - This corresponds to the ``key_ring`` 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.KeyRing: - 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. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.CreateKeyRingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if key_ring_id is not None: - request.key_ring_id = key_ring_id - if key_ring is not None: - request.key_ring = key_ring - - # 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_key_ring, - 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 create_crypto_key(self, - request: Union[service.CreateCryptoKeyRequest, dict] = None, - *, - parent: str = None, - crypto_key_id: str = None, - crypto_key: resources.CryptoKey = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and - [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] - are required. - - Args: - request (Union[google.cloud.kms_v1.types.CreateCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. - parent (:class:`str`): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the KeyRing associated with the - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_id (:class:`str`): - Required. It must be unique within a KeyRing and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``crypto_key_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): - Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] - with initial field values. - - This corresponds to the ``crypto_key`` 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.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] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.CreateCryptoKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if crypto_key_id is not None: - request.crypto_key_id = crypto_key_id - if crypto_key is not None: - request.crypto_key = crypto_key - - # 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_crypto_key, - 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 create_crypto_key_version(self, - request: Union[service.CreateCryptoKeyVersionRequest, dict] = None, - *, - parent: str = None, - crypto_key_version: resources.CryptoKeyVersion = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Create a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - The server will assign the next sequential id. If unset, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. - - Args: - request (Union[google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. - parent (:class:`str`): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] - associated with the - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): - Required. A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with initial field values. - - This corresponds to the ``crypto_key_version`` 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.CreateCryptoKeyVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if crypto_key_version is not None: - request.crypto_key_version = crypto_key_version - - # 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_crypto_key_version, - 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 import_crypto_key_version(self, - request: Union[service.ImportCryptoKeyVersionRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Import wrapped key material into a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - All requests must specify a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is - additionally specified in the request, key material will be - reimported into that version. Otherwise, a new version will be - created, and will be assigned the next sequential id within the - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Args: - request (Union[google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - request = service.ImportCryptoKeyVersionRequest(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.import_crypto_key_version, - 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 create_import_job(self, - request: Union[service.CreateImportJobRequest, dict] = None, - *, - parent: str = None, - import_job_id: str = None, - import_job: resources.ImportJob = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.ImportJob: - r"""Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] - is required. - - Args: - request (Union[google.cloud.kms_v1.types.CreateImportJobRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. - parent (:class:`str`): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the [KeyRing][google.cloud.kms.v1.KeyRing] associated - with the [ImportJobs][google.cloud.kms.v1.ImportJob]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - import_job_id (:class:`str`): - Required. It must be unique within a KeyRing and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``import_job_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - import_job (:class:`google.cloud.kms_v1.types.ImportJob`): - Required. An [ImportJob][google.cloud.kms.v1.ImportJob] - with initial field values. - - This corresponds to the ``import_job`` 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.ImportJob: - 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. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", - which is a public/private key pair. You use the - wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the - import process. The nature of the wrapping key - depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be - set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be - used to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires - 3 days after it is created. Once expired, Cloud KMS - will no longer be able to import or unwrap any key - material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public - key. - - For more information, see [Importing a - key](\ https://cloud.google.com/kms/docs/importing-a-key). - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.CreateImportJobRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if import_job_id is not None: - request.import_job_id = import_job_id - if import_job is not None: - request.import_job = import_job - - # 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_import_job, - 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_crypto_key(self, - request: Union[service.UpdateCryptoKeyRequest, dict] = None, - *, - crypto_key: resources.CryptoKey = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): - Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] - with updated values. - - This corresponds to the ``crypto_key`` 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.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] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.UpdateCryptoKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if crypto_key is not None: - request.crypto_key = crypto_key - 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_crypto_key, - 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(( - ("crypto_key.name", request.crypto_key.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_crypto_key_version(self, - request: Union[service.UpdateCryptoKeyVersionRequest, dict] = None, - *, - crypto_key_version: resources.CryptoKeyVersion = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Update a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - metadata. - - [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be - changed between - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - and - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - using this method. See - [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] - and - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to move between other states. - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): - Required. - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with updated values. - - This corresponds to the ``crypto_key_version`` 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.UpdateCryptoKeyVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if crypto_key_version is not None: - request.crypto_key_version = crypto_key_version - 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_crypto_key_version, - 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(( - ("crypto_key_version.name", request.crypto_key_version.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_crypto_key_primary_version(self, - request: Union[service.UpdateCryptoKeyPrimaryVersionRequest, dict] = None, - *, - name: str = None, - crypto_key_version_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Update the version of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Returns an error if called on a key whose purpose is not - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - name (:class:`str`): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_version_id (:class:`str`): - Required. The id of the child - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use as primary. - - This corresponds to the ``crypto_key_version_id`` 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.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] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.UpdateCryptoKeyPrimaryVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if crypto_key_version_id is not None: - request.crypto_key_version_id = crypto_key_version_id - - # 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_crypto_key_primary_version, - 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 destroy_crypto_key_version(self, - request: Union[service.DestroyCryptoKeyVersionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Schedule a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for - destruction. - - Upon calling this method, - [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] - will be set to - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be set to the time - [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] - in the future. At that time, the - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will - automatically change to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], - and the key material will be irrevocably destroyed. - - Before the - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - is reached, - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - may be called to reverse the process. - - Args: - request (Union[google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to destroy. - - 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.DestroyCryptoKeyVersionRequest(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.destroy_crypto_key_version, - 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 restore_crypto_key_version(self, - request: Union[service.RestoreCryptoKeyVersionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Restore a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state. - - Upon restoration of the CryptoKeyVersion, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be cleared. - - Args: - request (Union[google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to restore. - - 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 = service.RestoreCryptoKeyVersionRequest(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.restore_crypto_key_version, - 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 encrypt(self, - request: Union[service.EncryptRequest, dict] = None, - *, - name: str = None, - plaintext: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.EncryptResponse: - r"""Encrypts data, so that it can only be recovered by a call to - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Args: - request (Union[google.cloud.kms_v1.types.EncryptRequest, dict]): - The request object. Request message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - name (:class:`str`): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] or - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for encryption. - - If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is - specified, the server will use its [primary - version][google.cloud.kms.v1.CryptoKey.primary]. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - plaintext (:class:`bytes`): - Required. The data to encrypt. Must be no larger than - 64KiB. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] - keys, the plaintext must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger - than 8KiB. - - This corresponds to the ``plaintext`` 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.EncryptResponse: - Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.EncryptRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if plaintext is not None: - request.plaintext = plaintext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.encrypt, - 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 decrypt(self, - request: Union[service.DecryptRequest, dict] = None, - *, - name: str = None, - ciphertext: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.DecryptResponse: - r"""Decrypts data that was protected by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Args: - request (Union[google.cloud.kms_v1.types.DecryptRequest, dict]): - The request object. Request message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - name (:class:`str`): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for - decryption. The server will choose the appropriate - version. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ciphertext (:class:`bytes`): - Required. The encrypted data originally returned in - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. - - This corresponds to the ``ciphertext`` 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.DecryptResponse: - Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.DecryptRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if ciphertext is not None: - request.ciphertext = ciphertext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.decrypt, - 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 asymmetric_sign(self, - request: Union[service.AsymmetricSignRequest, dict] = None, - *, - name: str = None, - digest: service.Digest = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.AsymmetricSignResponse: - r"""Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_SIGN, producing a signature that can be verified with - the public key retrieved from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Args: - request (Union[google.cloud.kms_v1.types.AsymmetricSignRequest, dict]): - The request object. Request message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for signing. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - digest (:class:`google.cloud.kms_v1.types.Digest`): - Optional. The digest of the data to sign. The digest - must be produced with the same digest algorithm as - specified by the key version's - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. - - This corresponds to the ``digest`` 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.AsymmetricSignResponse: - Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.AsymmetricSignRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if digest is not None: - request.digest = digest - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.asymmetric_sign, - 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 asymmetric_decrypt(self, - request: Union[service.AsymmetricDecryptRequest, dict] = None, - *, - name: str = None, - ciphertext: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.AsymmetricDecryptResponse: - r"""Decrypts data that was encrypted with a public key retrieved - from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] - corresponding to a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_DECRYPT. - - Args: - request (Union[google.cloud.kms_v1.types.AsymmetricDecryptRequest, dict]): - The request object. Request message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for decryption. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ciphertext (:class:`bytes`): - Required. The data encrypted with the named - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - public key using OAEP. - - This corresponds to the ``ciphertext`` 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.AsymmetricDecryptResponse: - Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.AsymmetricDecryptRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if ciphertext is not None: - request.ciphertext = ciphertext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.asymmetric_decrypt, - 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 mac_sign(self, - request: Union[service.MacSignRequest, dict] = None, - *, - name: str = None, - data: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.MacSignResponse: - r"""Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - producing a tag that can be verified by another source with the - same key. - - Args: - request (Union[google.cloud.kms_v1.types.MacSignRequest, dict]): - The request object. Request message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for signing. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (:class:`bytes`): - Required. The data to sign. The MAC - tag is computed over this data field - based on the specific algorithm. - - This corresponds to the ``data`` 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.MacSignResponse: - Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.MacSignRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.mac_sign, - 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 mac_verify(self, - request: Union[service.MacVerifyRequest, dict] = None, - *, - name: str = None, - data: bytes = None, - mac: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.MacVerifyResponse: - r"""Verifies MAC tag using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - and returns a response that indicates whether or not the - verification was successful. - - Args: - request (Union[google.cloud.kms_v1.types.MacVerifyRequest, dict]): - The request object. Request message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for verification. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (:class:`bytes`): - Required. The data used previously as a - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] - to generate the MAC tag. - - This corresponds to the ``data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mac (:class:`bytes`): - Required. The signature to verify. - This corresponds to the ``mac`` 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.MacVerifyResponse: - Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.MacVerifyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - if mac is not None: - request.mac = mac - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.mac_verify, - 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 generate_random_bytes(self, - request: Union[service.GenerateRandomBytesRequest, dict] = None, - *, - location: str = None, - length_bytes: int = None, - protection_level: resources.ProtectionLevel = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.GenerateRandomBytesResponse: - r"""Generate random bytes using the Cloud KMS randomness - source in the provided location. - - Args: - request (Union[google.cloud.kms_v1.types.GenerateRandomBytesRequest, dict]): - The request object. Request message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - location (:class:`str`): - The project-specific location in - which to generate random bytes. For - example, "projects/my- - project/locations/us-central1". - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - length_bytes (:class:`int`): - The length in bytes of the amount of - randomness to retrieve. Minimum 8 - bytes, maximum 1024 bytes. - - This corresponds to the ``length_bytes`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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]. - - This corresponds to the ``protection_level`` 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.GenerateRandomBytesResponse: - Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = service.GenerateRandomBytesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if length_bytes is not None: - request.length_bytes = length_bytes - if protection_level is not None: - request.protection_level = protection_level - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.generate_random_bytes, - 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(( - ("location", request.location), - )), - ) - - # 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__ = ( - "KeyManagementServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py deleted file mode 100644 index 1d8ad469..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py +++ /dev/null @@ -1,3254 +0,0 @@ -# -*- 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.key_management_service import pagers -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import KeyManagementServiceGrpcTransport -from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport - - -class KeyManagementServiceClientMeta(type): - """Metaclass for the KeyManagementService 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[KeyManagementServiceTransport]] - _transport_registry["grpc"] = KeyManagementServiceGrpcTransport - _transport_registry["grpc_asyncio"] = KeyManagementServiceGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[KeyManagementServiceTransport]: - """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 KeyManagementServiceClient(metaclass=KeyManagementServiceClientMeta): - """Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - """ - - @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: - KeyManagementServiceClient: 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: - KeyManagementServiceClient: 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) -> KeyManagementServiceTransport: - """Returns the transport used by the client instance. - - Returns: - KeyManagementServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def crypto_key_version_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: - """Returns a fully-qualified crypto_key_version string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - - @staticmethod - def parse_crypto_key_version_path(path: str) -> Dict[str,str]: - """Parses a crypto_key_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def import_job_path(project: str,location: str,key_ring: str,import_job: str,) -> str: - """Returns a fully-qualified import_job string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format(project=project, location=location, key_ring=key_ring, import_job=import_job, ) - - @staticmethod - def parse_import_job_path(path: str) -> Dict[str,str]: - """Parses a import_job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/importJobs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def key_ring_path(project: str,location: str,key_ring: str,) -> str: - """Returns a fully-qualified key_ring string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}".format(project=project, location=location, key_ring=key_ring, ) - - @staticmethod - def parse_key_ring_path(path: str) -> Dict[str,str]: - """Parses a key_ring path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def public_key_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: - """Returns a fully-qualified public_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - - @staticmethod - def parse_public_key_path(path: str) -> Dict[str,str]: - """Parses a public_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)/publicKey$", 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, KeyManagementServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the key management 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, KeyManagementServiceTransport]): 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, KeyManagementServiceTransport): - # transport is a KeyManagementServiceTransport 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_key_rings(self, - request: Union[service.ListKeyRingsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListKeyRingsPager: - r"""Lists [KeyRings][google.cloud.kms.v1.KeyRing]. - - Args: - request (Union[google.cloud.kms_v1.types.ListKeyRingsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - parent (str): - Required. The resource name of the location associated - with the [KeyRings][google.cloud.kms.v1.KeyRing], 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.key_management_service.pagers.ListKeyRingsPager: - Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.ListKeyRingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.ListKeyRingsRequest): - request = service.ListKeyRingsRequest(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_key_rings] - - # 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.ListKeyRingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_crypto_keys(self, - request: Union[service.ListCryptoKeysRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCryptoKeysPager: - r"""Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - Args: - request (Union[google.cloud.kms_v1.types.ListCryptoKeysRequest, dict]): - The request object. Request message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - parent (str): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - - 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.key_management_service.pagers.ListCryptoKeysPager: - Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.ListCryptoKeysRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.ListCryptoKeysRequest): - request = service.ListCryptoKeysRequest(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_crypto_keys] - - # 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.ListCryptoKeysPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_crypto_key_versions(self, - request: Union[service.ListCryptoKeyVersionsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCryptoKeyVersionsPager: - r"""Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - Args: - request (Union[google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - parent (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in - the format - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - - 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.key_management_service.pagers.ListCryptoKeyVersionsPager: - Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.ListCryptoKeyVersionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.ListCryptoKeyVersionsRequest): - request = service.ListCryptoKeyVersionsRequest(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_crypto_key_versions] - - # 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.ListCryptoKeyVersionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_import_jobs(self, - request: Union[service.ListImportJobsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListImportJobsPager: - r"""Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. - - Args: - request (Union[google.cloud.kms_v1.types.ListImportJobsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - parent (str): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - - 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.key_management_service.pagers.ListImportJobsPager: - Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.ListImportJobsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.ListImportJobsRequest): - request = service.ListImportJobsRequest(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_import_jobs] - - # 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.ListImportJobsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_key_ring(self, - request: Union[service.GetKeyRingRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.KeyRing: - r"""Returns metadata for a given - [KeyRing][google.cloud.kms.v1.KeyRing]. - - Args: - request (Union[google.cloud.kms_v1.types.GetKeyRingRequest, dict]): - The request object. Request message for - [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. - name (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the [KeyRing][google.cloud.kms.v1.KeyRing] 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.KeyRing: - 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. - # Sanity 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 service.GetKeyRingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.GetKeyRingRequest): - request = service.GetKeyRingRequest(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_key_ring] - - # 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 get_crypto_key(self, - request: Union[service.GetCryptoKeyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Returns metadata for a given - [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its - [primary][google.cloud.kms.v1.CryptoKey.primary] - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Args: - request (Union[google.cloud.kms_v1.types.GetCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. - name (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] 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.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] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.GetCryptoKeyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.GetCryptoKeyRequest): - request = service.GetCryptoKeyRequest(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_crypto_key] - - # 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 get_crypto_key_version(self, - request: Union[service.GetCryptoKeyVersionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Returns metadata for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Args: - request (Union[google.cloud.kms_v1.types.GetCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. - name (str): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.GetCryptoKeyVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.GetCryptoKeyVersionRequest): - request = service.GetCryptoKeyVersionRequest(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_crypto_key_version] - - # 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 get_public_key(self, - request: Union[service.GetPublicKeyRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.PublicKey: - r"""Returns the public key for the given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] - or - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - Args: - request (Union[google.cloud.kms_v1.types.GetPublicKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - name (str): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key 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.PublicKey: - The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.GetPublicKeyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.GetPublicKeyRequest): - request = service.GetPublicKeyRequest(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_public_key] - - # 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 get_import_job(self, - request: Union[service.GetImportJobRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.ImportJob: - r"""Returns metadata for a given - [ImportJob][google.cloud.kms.v1.ImportJob]. - - Args: - request (Union[google.cloud.kms_v1.types.GetImportJobRequest, dict]): - The request object. Request message for - [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. - name (str): - Required. The [name][google.cloud.kms.v1.ImportJob.name] - of the [ImportJob][google.cloud.kms.v1.ImportJob] 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.ImportJob: - 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. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", - which is a public/private key pair. You use the - wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the - import process. The nature of the wrapping key - depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be - set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be - used to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires - 3 days after it is created. Once expired, Cloud KMS - will no longer be able to import or unwrap any key - material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public - key. - - For more information, see [Importing a - key](\ https://cloud.google.com/kms/docs/importing-a-key). - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.GetImportJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.GetImportJobRequest): - request = service.GetImportJobRequest(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_import_job] - - # 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_key_ring(self, - request: Union[service.CreateKeyRingRequest, dict] = None, - *, - parent: str = None, - key_ring_id: str = None, - key_ring: resources.KeyRing = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.KeyRing: - r"""Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given - Project and Location. - - Args: - request (Union[google.cloud.kms_v1.types.CreateKeyRingRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. - parent (str): - Required. The resource name of the location associated - with the [KeyRings][google.cloud.kms.v1.KeyRing], in the - format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_ring_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 ``key_ring_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_ring (google.cloud.kms_v1.types.KeyRing): - Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with - initial field values. - - This corresponds to the ``key_ring`` 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.KeyRing: - 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. - # Sanity 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: - 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 service.CreateKeyRingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.CreateKeyRingRequest): - request = service.CreateKeyRingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if key_ring_id is not None: - request.key_ring_id = key_ring_id - if key_ring is not None: - request.key_ring = key_ring - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_key_ring] - - # 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 create_crypto_key(self, - request: Union[service.CreateCryptoKeyRequest, dict] = None, - *, - parent: str = None, - crypto_key_id: str = None, - crypto_key: resources.CryptoKey = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and - [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] - are required. - - Args: - request (Union[google.cloud.kms_v1.types.CreateCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. - parent (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the KeyRing associated with the - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_id (str): - Required. It must be unique within a KeyRing and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``crypto_key_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key (google.cloud.kms_v1.types.CryptoKey): - Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] - with initial field values. - - This corresponds to the ``crypto_key`` 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.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] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.CreateCryptoKeyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.CreateCryptoKeyRequest): - request = service.CreateCryptoKeyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if crypto_key_id is not None: - request.crypto_key_id = crypto_key_id - if crypto_key is not None: - request.crypto_key = crypto_key - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_crypto_key] - - # 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 create_crypto_key_version(self, - request: Union[service.CreateCryptoKeyVersionRequest, dict] = None, - *, - parent: str = None, - crypto_key_version: resources.CryptoKeyVersion = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Create a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - The server will assign the next sequential id. If unset, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. - - Args: - request (Union[google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. - parent (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] - associated with the - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): - Required. A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with initial field values. - - This corresponds to the ``crypto_key_version`` 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.CreateCryptoKeyVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.CreateCryptoKeyVersionRequest): - request = service.CreateCryptoKeyVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if crypto_key_version is not None: - request.crypto_key_version = crypto_key_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_crypto_key_version] - - # 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 import_crypto_key_version(self, - request: Union[service.ImportCryptoKeyVersionRequest, dict] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Import wrapped key material into a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - All requests must specify a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is - additionally specified in the request, key material will be - reimported into that version. Otherwise, a new version will be - created, and will be assigned the next sequential id within the - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Args: - request (Union[google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a service.ImportCryptoKeyVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.ImportCryptoKeyVersionRequest): - request = service.ImportCryptoKeyVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_crypto_key_version] - - # 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 create_import_job(self, - request: Union[service.CreateImportJobRequest, dict] = None, - *, - parent: str = None, - import_job_id: str = None, - import_job: resources.ImportJob = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.ImportJob: - r"""Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] - is required. - - Args: - request (Union[google.cloud.kms_v1.types.CreateImportJobRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. - parent (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the [KeyRing][google.cloud.kms.v1.KeyRing] associated - with the [ImportJobs][google.cloud.kms.v1.ImportJob]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - import_job_id (str): - Required. It must be unique within a KeyRing and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``import_job_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - import_job (google.cloud.kms_v1.types.ImportJob): - Required. An [ImportJob][google.cloud.kms.v1.ImportJob] - with initial field values. - - This corresponds to the ``import_job`` 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.ImportJob: - 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. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", - which is a public/private key pair. You use the - wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the - import process. The nature of the wrapping key - depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be - set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be - used to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires - 3 days after it is created. Once expired, Cloud KMS - will no longer be able to import or unwrap any key - material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public - key. - - For more information, see [Importing a - key](\ https://cloud.google.com/kms/docs/importing-a-key). - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.CreateImportJobRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.CreateImportJobRequest): - request = service.CreateImportJobRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if import_job_id is not None: - request.import_job_id = import_job_id - if import_job is not None: - request.import_job = import_job - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_import_job] - - # 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_crypto_key(self, - request: Union[service.UpdateCryptoKeyRequest, dict] = None, - *, - crypto_key: resources.CryptoKey = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - crypto_key (google.cloud.kms_v1.types.CryptoKey): - Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] - with updated values. - - This corresponds to the ``crypto_key`` 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.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] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.UpdateCryptoKeyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.UpdateCryptoKeyRequest): - request = service.UpdateCryptoKeyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if crypto_key is not None: - request.crypto_key = crypto_key - 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_crypto_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("crypto_key.name", request.crypto_key.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_crypto_key_version(self, - request: Union[service.UpdateCryptoKeyVersionRequest, dict] = None, - *, - crypto_key_version: resources.CryptoKeyVersion = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Update a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - metadata. - - [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be - changed between - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - and - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - using this method. See - [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] - and - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to move between other states. - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): - Required. - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with updated values. - - This corresponds to the ``crypto_key_version`` 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.UpdateCryptoKeyVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.UpdateCryptoKeyVersionRequest): - request = service.UpdateCryptoKeyVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if crypto_key_version is not None: - request.crypto_key_version = crypto_key_version - 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_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("crypto_key_version.name", request.crypto_key_version.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_crypto_key_primary_version(self, - request: Union[service.UpdateCryptoKeyPrimaryVersionRequest, dict] = None, - *, - name: str = None, - crypto_key_version_id: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Update the version of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Returns an error if called on a key whose purpose is not - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_version_id (str): - Required. The id of the child - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use as primary. - - This corresponds to the ``crypto_key_version_id`` 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.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] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.UpdateCryptoKeyPrimaryVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.UpdateCryptoKeyPrimaryVersionRequest): - request = service.UpdateCryptoKeyPrimaryVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if crypto_key_version_id is not None: - request.crypto_key_version_id = crypto_key_version_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_crypto_key_primary_version] - - # 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 destroy_crypto_key_version(self, - request: Union[service.DestroyCryptoKeyVersionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Schedule a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for - destruction. - - Upon calling this method, - [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] - will be set to - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be set to the time - [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] - in the future. At that time, the - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will - automatically change to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], - and the key material will be irrevocably destroyed. - - Before the - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - is reached, - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - may be called to reverse the process. - - Args: - request (Union[google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to destroy. - - 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.DestroyCryptoKeyVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.DestroyCryptoKeyVersionRequest): - request = service.DestroyCryptoKeyVersionRequest(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.destroy_crypto_key_version] - - # 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 restore_crypto_key_version(self, - request: Union[service.RestoreCryptoKeyVersionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Restore a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state. - - Upon restoration of the CryptoKeyVersion, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be cleared. - - Args: - request (Union[google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to restore. - - 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.CryptoKeyVersion: - 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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # Sanity 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 service.RestoreCryptoKeyVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.RestoreCryptoKeyVersionRequest): - request = service.RestoreCryptoKeyVersionRequest(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.restore_crypto_key_version] - - # 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 encrypt(self, - request: Union[service.EncryptRequest, dict] = None, - *, - name: str = None, - plaintext: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.EncryptResponse: - r"""Encrypts data, so that it can only be recovered by a call to - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Args: - request (Union[google.cloud.kms_v1.types.EncryptRequest, dict]): - The request object. Request message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] or - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for encryption. - - If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is - specified, the server will use its [primary - version][google.cloud.kms.v1.CryptoKey.primary]. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - plaintext (bytes): - Required. The data to encrypt. Must be no larger than - 64KiB. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] - keys, the plaintext must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger - than 8KiB. - - This corresponds to the ``plaintext`` 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.EncryptResponse: - Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.EncryptRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.EncryptRequest): - request = service.EncryptRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if plaintext is not None: - request.plaintext = plaintext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.encrypt] - - # 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 decrypt(self, - request: Union[service.DecryptRequest, dict] = None, - *, - name: str = None, - ciphertext: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.DecryptResponse: - r"""Decrypts data that was protected by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Args: - request (Union[google.cloud.kms_v1.types.DecryptRequest, dict]): - The request object. Request message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for - decryption. The server will choose the appropriate - version. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ciphertext (bytes): - Required. The encrypted data originally returned in - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. - - This corresponds to the ``ciphertext`` 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.DecryptResponse: - Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.DecryptRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.DecryptRequest): - request = service.DecryptRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if ciphertext is not None: - request.ciphertext = ciphertext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.decrypt] - - # 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 asymmetric_sign(self, - request: Union[service.AsymmetricSignRequest, dict] = None, - *, - name: str = None, - digest: service.Digest = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.AsymmetricSignResponse: - r"""Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_SIGN, producing a signature that can be verified with - the public key retrieved from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Args: - request (Union[google.cloud.kms_v1.types.AsymmetricSignRequest, dict]): - The request object. Request message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for signing. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - digest (google.cloud.kms_v1.types.Digest): - Optional. The digest of the data to sign. The digest - must be produced with the same digest algorithm as - specified by the key version's - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. - - This corresponds to the ``digest`` 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.AsymmetricSignResponse: - Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.AsymmetricSignRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.AsymmetricSignRequest): - request = service.AsymmetricSignRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if digest is not None: - request.digest = digest - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.asymmetric_sign] - - # 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 asymmetric_decrypt(self, - request: Union[service.AsymmetricDecryptRequest, dict] = None, - *, - name: str = None, - ciphertext: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.AsymmetricDecryptResponse: - r"""Decrypts data that was encrypted with a public key retrieved - from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] - corresponding to a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_DECRYPT. - - Args: - request (Union[google.cloud.kms_v1.types.AsymmetricDecryptRequest, dict]): - The request object. Request message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for decryption. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ciphertext (bytes): - Required. The data encrypted with the named - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - public key using OAEP. - - This corresponds to the ``ciphertext`` 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.AsymmetricDecryptResponse: - Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.AsymmetricDecryptRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.AsymmetricDecryptRequest): - request = service.AsymmetricDecryptRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if ciphertext is not None: - request.ciphertext = ciphertext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.asymmetric_decrypt] - - # 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 mac_sign(self, - request: Union[service.MacSignRequest, dict] = None, - *, - name: str = None, - data: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.MacSignResponse: - r"""Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - producing a tag that can be verified by another source with the - same key. - - Args: - request (Union[google.cloud.kms_v1.types.MacSignRequest, dict]): - The request object. Request message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for signing. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (bytes): - Required. The data to sign. The MAC - tag is computed over this data field - based on the specific algorithm. - - This corresponds to the ``data`` 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.MacSignResponse: - Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.MacSignRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.MacSignRequest): - request = service.MacSignRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.mac_sign] - - # 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 mac_verify(self, - request: Union[service.MacVerifyRequest, dict] = None, - *, - name: str = None, - data: bytes = None, - mac: bytes = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.MacVerifyResponse: - r"""Verifies MAC tag using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - and returns a response that indicates whether or not the - verification was successful. - - Args: - request (Union[google.cloud.kms_v1.types.MacVerifyRequest, dict]): - The request object. Request message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for verification. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (bytes): - Required. The data used previously as a - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] - to generate the MAC tag. - - This corresponds to the ``data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mac (bytes): - Required. The signature to verify. - This corresponds to the ``mac`` 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.MacVerifyResponse: - Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.MacVerifyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.MacVerifyRequest): - request = service.MacVerifyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - if mac is not None: - request.mac = mac - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.mac_verify] - - # 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 generate_random_bytes(self, - request: Union[service.GenerateRandomBytesRequest, dict] = None, - *, - location: str = None, - length_bytes: int = None, - protection_level: resources.ProtectionLevel = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.GenerateRandomBytesResponse: - r"""Generate random bytes using the Cloud KMS randomness - source in the provided location. - - Args: - request (Union[google.cloud.kms_v1.types.GenerateRandomBytesRequest, dict]): - The request object. Request message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - location (str): - The project-specific location in - which to generate random bytes. For - example, "projects/my- - project/locations/us-central1". - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - length_bytes (int): - The length in bytes of the amount of - randomness to retrieve. Minimum 8 - bytes, maximum 1024 bytes. - - This corresponds to the ``length_bytes`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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]. - - This corresponds to the ``protection_level`` 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.GenerateRandomBytesResponse: - Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - """ - # Create or coerce a protobuf request object. - # Sanity 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: - 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 service.GenerateRandomBytesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, service.GenerateRandomBytesRequest): - request = service.GenerateRandomBytesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if length_bytes is not None: - request.length_bytes = length_bytes - if protection_level is not None: - request.protection_level = protection_level - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_random_bytes] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("location", request.location), - )), - ) - - # 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__ = ( - "KeyManagementServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/pagers.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/pagers.py deleted file mode 100644 index 0be3e030..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/pagers.py +++ /dev/null @@ -1,503 +0,0 @@ -# -*- 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 resources -from google.cloud.kms_v1.types import service - - -class ListKeyRingsPager: - """A pager for iterating through ``list_key_rings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``key_rings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListKeyRings`` requests and continue to iterate - through the ``key_rings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` - 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[..., service.ListKeyRingsResponse], - request: service.ListKeyRingsRequest, - response: service.ListKeyRingsResponse, - *, - 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.ListKeyRingsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListKeyRingsResponse): - 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 = service.ListKeyRingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListKeyRingsResponse]: - 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[resources.KeyRing]: - for page in self.pages: - yield from page.key_rings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListKeyRingsAsyncPager: - """A pager for iterating through ``list_key_rings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``key_rings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListKeyRings`` requests and continue to iterate - through the ``key_rings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` - 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[service.ListKeyRingsResponse]], - request: service.ListKeyRingsRequest, - response: service.ListKeyRingsResponse, - *, - 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.ListKeyRingsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListKeyRingsResponse): - 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 = service.ListKeyRingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListKeyRingsResponse]: - 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[resources.KeyRing]: - async def async_generator(): - async for page in self.pages: - for response in page.key_rings: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCryptoKeysPager: - """A pager for iterating through ``list_crypto_keys`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crypto_keys`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCryptoKeys`` requests and continue to iterate - through the ``crypto_keys`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` - 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[..., service.ListCryptoKeysResponse], - request: service.ListCryptoKeysRequest, - response: service.ListCryptoKeysResponse, - *, - 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.ListCryptoKeysRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListCryptoKeysResponse): - 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 = service.ListCryptoKeysRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListCryptoKeysResponse]: - 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[resources.CryptoKey]: - for page in self.pages: - yield from page.crypto_keys - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCryptoKeysAsyncPager: - """A pager for iterating through ``list_crypto_keys`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crypto_keys`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCryptoKeys`` requests and continue to iterate - through the ``crypto_keys`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` - 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[service.ListCryptoKeysResponse]], - request: service.ListCryptoKeysRequest, - response: service.ListCryptoKeysResponse, - *, - 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.ListCryptoKeysRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListCryptoKeysResponse): - 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 = service.ListCryptoKeysRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListCryptoKeysResponse]: - 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[resources.CryptoKey]: - async def async_generator(): - async for page in self.pages: - for response in page.crypto_keys: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCryptoKeyVersionsPager: - """A pager for iterating through ``list_crypto_key_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crypto_key_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCryptoKeyVersions`` requests and continue to iterate - through the ``crypto_key_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` - 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[..., service.ListCryptoKeyVersionsResponse], - request: service.ListCryptoKeyVersionsRequest, - response: service.ListCryptoKeyVersionsResponse, - *, - 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.ListCryptoKeyVersionsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): - 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 = service.ListCryptoKeyVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListCryptoKeyVersionsResponse]: - 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[resources.CryptoKeyVersion]: - for page in self.pages: - yield from page.crypto_key_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCryptoKeyVersionsAsyncPager: - """A pager for iterating through ``list_crypto_key_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crypto_key_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCryptoKeyVersions`` requests and continue to iterate - through the ``crypto_key_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` - 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[service.ListCryptoKeyVersionsResponse]], - request: service.ListCryptoKeyVersionsRequest, - response: service.ListCryptoKeyVersionsResponse, - *, - 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.ListCryptoKeyVersionsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): - 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 = service.ListCryptoKeyVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListCryptoKeyVersionsResponse]: - 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[resources.CryptoKeyVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.crypto_key_versions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListImportJobsPager: - """A pager for iterating through ``list_import_jobs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``import_jobs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListImportJobs`` requests and continue to iterate - through the ``import_jobs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` - 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[..., service.ListImportJobsResponse], - request: service.ListImportJobsRequest, - response: service.ListImportJobsResponse, - *, - 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.ListImportJobsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListImportJobsResponse): - 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 = service.ListImportJobsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListImportJobsResponse]: - 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[resources.ImportJob]: - for page in self.pages: - yield from page.import_jobs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListImportJobsAsyncPager: - """A pager for iterating through ``list_import_jobs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``import_jobs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListImportJobs`` requests and continue to iterate - through the ``import_jobs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` - 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[service.ListImportJobsResponse]], - request: service.ListImportJobsRequest, - response: service.ListImportJobsResponse, - *, - 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.ListImportJobsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListImportJobsResponse): - 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 = service.ListImportJobsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListImportJobsResponse]: - 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[resources.ImportJob]: - async def async_generator(): - async for page in self.pages: - for response in page.import_jobs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py deleted file mode 100644 index 291c245a..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- 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 KeyManagementServiceTransport -from .grpc import KeyManagementServiceGrpcTransport -from .grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[KeyManagementServiceTransport]] -_transport_registry['grpc'] = KeyManagementServiceGrpcTransport -_transport_registry['grpc_asyncio'] = KeyManagementServiceGrpcAsyncIOTransport - -__all__ = ( - 'KeyManagementServiceTransport', - 'KeyManagementServiceGrpcTransport', - 'KeyManagementServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py deleted file mode 100644 index 0b72c663..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py +++ /dev/null @@ -1,696 +0,0 @@ -# -*- 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 resources -from google.cloud.kms_v1.types import 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 KeyManagementServiceTransport(abc.ABC): - """Abstract transport class for KeyManagementService.""" - - 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_key_rings: gapic_v1.method.wrap_method( - self.list_key_rings, - 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.list_crypto_keys: gapic_v1.method.wrap_method( - self.list_crypto_keys, - 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.list_crypto_key_versions: gapic_v1.method.wrap_method( - self.list_crypto_key_versions, - 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.list_import_jobs: gapic_v1.method.wrap_method( - self.list_import_jobs, - 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_key_ring: gapic_v1.method.wrap_method( - self.get_key_ring, - 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_crypto_key: gapic_v1.method.wrap_method( - self.get_crypto_key, - 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_crypto_key_version: gapic_v1.method.wrap_method( - self.get_crypto_key_version, - 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_public_key: gapic_v1.method.wrap_method( - self.get_public_key, - 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_import_job: gapic_v1.method.wrap_method( - self.get_import_job, - 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_key_ring: gapic_v1.method.wrap_method( - self.create_key_ring, - 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_crypto_key: gapic_v1.method.wrap_method( - self.create_crypto_key, - 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_crypto_key_version: gapic_v1.method.wrap_method( - self.create_crypto_key_version, - default_timeout=60.0, - client_info=client_info, - ), - self.import_crypto_key_version: gapic_v1.method.wrap_method( - self.import_crypto_key_version, - default_timeout=60.0, - client_info=client_info, - ), - self.create_import_job: gapic_v1.method.wrap_method( - self.create_import_job, - 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_crypto_key: gapic_v1.method.wrap_method( - self.update_crypto_key, - 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_crypto_key_version: gapic_v1.method.wrap_method( - self.update_crypto_key_version, - 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_crypto_key_primary_version: gapic_v1.method.wrap_method( - self.update_crypto_key_primary_version, - 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.destroy_crypto_key_version: gapic_v1.method.wrap_method( - self.destroy_crypto_key_version, - 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.restore_crypto_key_version: gapic_v1.method.wrap_method( - self.restore_crypto_key_version, - 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.encrypt: gapic_v1.method.wrap_method( - self.encrypt, - 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.decrypt: gapic_v1.method.wrap_method( - self.decrypt, - 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.asymmetric_sign: gapic_v1.method.wrap_method( - self.asymmetric_sign, - 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.asymmetric_decrypt: gapic_v1.method.wrap_method( - self.asymmetric_decrypt, - 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.mac_sign: gapic_v1.method.wrap_method( - self.mac_sign, - 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.mac_verify: gapic_v1.method.wrap_method( - self.mac_verify, - 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.generate_random_bytes: gapic_v1.method.wrap_method( - self.generate_random_bytes, - 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_key_rings(self) -> Callable[ - [service.ListKeyRingsRequest], - Union[ - service.ListKeyRingsResponse, - Awaitable[service.ListKeyRingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_crypto_keys(self) -> Callable[ - [service.ListCryptoKeysRequest], - Union[ - service.ListCryptoKeysResponse, - Awaitable[service.ListCryptoKeysResponse] - ]]: - raise NotImplementedError() - - @property - def list_crypto_key_versions(self) -> Callable[ - [service.ListCryptoKeyVersionsRequest], - Union[ - service.ListCryptoKeyVersionsResponse, - Awaitable[service.ListCryptoKeyVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def list_import_jobs(self) -> Callable[ - [service.ListImportJobsRequest], - Union[ - service.ListImportJobsResponse, - Awaitable[service.ListImportJobsResponse] - ]]: - raise NotImplementedError() - - @property - def get_key_ring(self) -> Callable[ - [service.GetKeyRingRequest], - Union[ - resources.KeyRing, - Awaitable[resources.KeyRing] - ]]: - raise NotImplementedError() - - @property - def get_crypto_key(self) -> Callable[ - [service.GetCryptoKeyRequest], - Union[ - resources.CryptoKey, - Awaitable[resources.CryptoKey] - ]]: - raise NotImplementedError() - - @property - def get_crypto_key_version(self) -> Callable[ - [service.GetCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def get_public_key(self) -> Callable[ - [service.GetPublicKeyRequest], - Union[ - resources.PublicKey, - Awaitable[resources.PublicKey] - ]]: - raise NotImplementedError() - - @property - def get_import_job(self) -> Callable[ - [service.GetImportJobRequest], - Union[ - resources.ImportJob, - Awaitable[resources.ImportJob] - ]]: - raise NotImplementedError() - - @property - def create_key_ring(self) -> Callable[ - [service.CreateKeyRingRequest], - Union[ - resources.KeyRing, - Awaitable[resources.KeyRing] - ]]: - raise NotImplementedError() - - @property - def create_crypto_key(self) -> Callable[ - [service.CreateCryptoKeyRequest], - Union[ - resources.CryptoKey, - Awaitable[resources.CryptoKey] - ]]: - raise NotImplementedError() - - @property - def create_crypto_key_version(self) -> Callable[ - [service.CreateCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def import_crypto_key_version(self) -> Callable[ - [service.ImportCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def create_import_job(self) -> Callable[ - [service.CreateImportJobRequest], - Union[ - resources.ImportJob, - Awaitable[resources.ImportJob] - ]]: - raise NotImplementedError() - - @property - def update_crypto_key(self) -> Callable[ - [service.UpdateCryptoKeyRequest], - Union[ - resources.CryptoKey, - Awaitable[resources.CryptoKey] - ]]: - raise NotImplementedError() - - @property - def update_crypto_key_version(self) -> Callable[ - [service.UpdateCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def update_crypto_key_primary_version(self) -> Callable[ - [service.UpdateCryptoKeyPrimaryVersionRequest], - Union[ - resources.CryptoKey, - Awaitable[resources.CryptoKey] - ]]: - raise NotImplementedError() - - @property - def destroy_crypto_key_version(self) -> Callable[ - [service.DestroyCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def restore_crypto_key_version(self) -> Callable[ - [service.RestoreCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def encrypt(self) -> Callable[ - [service.EncryptRequest], - Union[ - service.EncryptResponse, - Awaitable[service.EncryptResponse] - ]]: - raise NotImplementedError() - - @property - def decrypt(self) -> Callable[ - [service.DecryptRequest], - Union[ - service.DecryptResponse, - Awaitable[service.DecryptResponse] - ]]: - raise NotImplementedError() - - @property - def asymmetric_sign(self) -> Callable[ - [service.AsymmetricSignRequest], - Union[ - service.AsymmetricSignResponse, - Awaitable[service.AsymmetricSignResponse] - ]]: - raise NotImplementedError() - - @property - def asymmetric_decrypt(self) -> Callable[ - [service.AsymmetricDecryptRequest], - Union[ - service.AsymmetricDecryptResponse, - Awaitable[service.AsymmetricDecryptResponse] - ]]: - raise NotImplementedError() - - @property - def mac_sign(self) -> Callable[ - [service.MacSignRequest], - Union[ - service.MacSignResponse, - Awaitable[service.MacSignResponse] - ]]: - raise NotImplementedError() - - @property - def mac_verify(self) -> Callable[ - [service.MacVerifyRequest], - Union[ - service.MacVerifyResponse, - Awaitable[service.MacVerifyResponse] - ]]: - raise NotImplementedError() - - @property - def generate_random_bytes(self) -> Callable[ - [service.GenerateRandomBytesRequest], - Union[ - service.GenerateRandomBytesResponse, - Awaitable[service.GenerateRandomBytesResponse] - ]]: - 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__ = ( - 'KeyManagementServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py deleted file mode 100644 index c360a411..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ /dev/null @@ -1,1115 +0,0 @@ -# -*- 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 resources -from google.cloud.kms_v1.types import service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO - - -class KeyManagementServiceGrpcTransport(KeyManagementServiceTransport): - """gRPC backend transport for KeyManagementService. - - Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - - 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, - credentials=self._credentials, - credentials_file=credentials_file, - 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_key_rings(self) -> Callable[ - [service.ListKeyRingsRequest], - service.ListKeyRingsResponse]: - r"""Return a callable for the list key rings method over gRPC. - - Lists [KeyRings][google.cloud.kms.v1.KeyRing]. - - Returns: - Callable[[~.ListKeyRingsRequest], - ~.ListKeyRingsResponse]: - 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_key_rings' not in self._stubs: - self._stubs['list_key_rings'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListKeyRings', - request_serializer=service.ListKeyRingsRequest.serialize, - response_deserializer=service.ListKeyRingsResponse.deserialize, - ) - return self._stubs['list_key_rings'] - - @property - def list_crypto_keys(self) -> Callable[ - [service.ListCryptoKeysRequest], - service.ListCryptoKeysResponse]: - r"""Return a callable for the list crypto keys method over gRPC. - - Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.ListCryptoKeysRequest], - ~.ListCryptoKeysResponse]: - 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_crypto_keys' not in self._stubs: - self._stubs['list_crypto_keys'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys', - request_serializer=service.ListCryptoKeysRequest.serialize, - response_deserializer=service.ListCryptoKeysResponse.deserialize, - ) - return self._stubs['list_crypto_keys'] - - @property - def list_crypto_key_versions(self) -> Callable[ - [service.ListCryptoKeyVersionsRequest], - service.ListCryptoKeyVersionsResponse]: - r"""Return a callable for the list crypto key versions method over gRPC. - - Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.ListCryptoKeyVersionsRequest], - ~.ListCryptoKeyVersionsResponse]: - 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_crypto_key_versions' not in self._stubs: - self._stubs['list_crypto_key_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions', - request_serializer=service.ListCryptoKeyVersionsRequest.serialize, - response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize, - ) - return self._stubs['list_crypto_key_versions'] - - @property - def list_import_jobs(self) -> Callable[ - [service.ListImportJobsRequest], - service.ListImportJobsResponse]: - r"""Return a callable for the list import jobs method over gRPC. - - Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. - - Returns: - Callable[[~.ListImportJobsRequest], - ~.ListImportJobsResponse]: - 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_import_jobs' not in self._stubs: - self._stubs['list_import_jobs'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListImportJobs', - request_serializer=service.ListImportJobsRequest.serialize, - response_deserializer=service.ListImportJobsResponse.deserialize, - ) - return self._stubs['list_import_jobs'] - - @property - def get_key_ring(self) -> Callable[ - [service.GetKeyRingRequest], - resources.KeyRing]: - r"""Return a callable for the get key ring method over gRPC. - - Returns metadata for a given - [KeyRing][google.cloud.kms.v1.KeyRing]. - - Returns: - Callable[[~.GetKeyRingRequest], - ~.KeyRing]: - 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_key_ring' not in self._stubs: - self._stubs['get_key_ring'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetKeyRing', - request_serializer=service.GetKeyRingRequest.serialize, - response_deserializer=resources.KeyRing.deserialize, - ) - return self._stubs['get_key_ring'] - - @property - def get_crypto_key(self) -> Callable[ - [service.GetCryptoKeyRequest], - resources.CryptoKey]: - r"""Return a callable for the get crypto key method over gRPC. - - Returns metadata for a given - [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its - [primary][google.cloud.kms.v1.CryptoKey.primary] - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.GetCryptoKeyRequest], - ~.CryptoKey]: - 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_crypto_key' not in self._stubs: - self._stubs['get_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetCryptoKey', - request_serializer=service.GetCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['get_crypto_key'] - - @property - def get_crypto_key_version(self) -> Callable[ - [service.GetCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the get crypto key version method over gRPC. - - Returns metadata for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.GetCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - 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_crypto_key_version' not in self._stubs: - self._stubs['get_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion', - request_serializer=service.GetCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['get_crypto_key_version'] - - @property - def get_public_key(self) -> Callable[ - [service.GetPublicKeyRequest], - resources.PublicKey]: - r"""Return a callable for the get public key method over gRPC. - - Returns the public key for the given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] - or - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - Returns: - Callable[[~.GetPublicKeyRequest], - ~.PublicKey]: - 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_public_key' not in self._stubs: - self._stubs['get_public_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetPublicKey', - request_serializer=service.GetPublicKeyRequest.serialize, - response_deserializer=resources.PublicKey.deserialize, - ) - return self._stubs['get_public_key'] - - @property - def get_import_job(self) -> Callable[ - [service.GetImportJobRequest], - resources.ImportJob]: - r"""Return a callable for the get import job method over gRPC. - - Returns metadata for a given - [ImportJob][google.cloud.kms.v1.ImportJob]. - - Returns: - Callable[[~.GetImportJobRequest], - ~.ImportJob]: - 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_import_job' not in self._stubs: - self._stubs['get_import_job'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetImportJob', - request_serializer=service.GetImportJobRequest.serialize, - response_deserializer=resources.ImportJob.deserialize, - ) - return self._stubs['get_import_job'] - - @property - def create_key_ring(self) -> Callable[ - [service.CreateKeyRingRequest], - resources.KeyRing]: - r"""Return a callable for the create key ring method over gRPC. - - Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given - Project and Location. - - Returns: - Callable[[~.CreateKeyRingRequest], - ~.KeyRing]: - 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_key_ring' not in self._stubs: - self._stubs['create_key_ring'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateKeyRing', - request_serializer=service.CreateKeyRingRequest.serialize, - response_deserializer=resources.KeyRing.deserialize, - ) - return self._stubs['create_key_ring'] - - @property - def create_crypto_key(self) -> Callable[ - [service.CreateCryptoKeyRequest], - resources.CryptoKey]: - r"""Return a callable for the create crypto key method over gRPC. - - Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and - [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] - are required. - - Returns: - Callable[[~.CreateCryptoKeyRequest], - ~.CryptoKey]: - 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_crypto_key' not in self._stubs: - self._stubs['create_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey', - request_serializer=service.CreateCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['create_crypto_key'] - - @property - def create_crypto_key_version(self) -> Callable[ - [service.CreateCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the create crypto key version method over gRPC. - - Create a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - The server will assign the next sequential id. If unset, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. - - Returns: - Callable[[~.CreateCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - 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_crypto_key_version' not in self._stubs: - self._stubs['create_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion', - request_serializer=service.CreateCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['create_crypto_key_version'] - - @property - def import_crypto_key_version(self) -> Callable[ - [service.ImportCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the import crypto key version method over gRPC. - - Import wrapped key material into a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - All requests must specify a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is - additionally specified in the request, key material will be - reimported into that version. Otherwise, a new version will be - created, and will be assigned the next sequential id within the - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.ImportCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - 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 'import_crypto_key_version' not in self._stubs: - self._stubs['import_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion', - request_serializer=service.ImportCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['import_crypto_key_version'] - - @property - def create_import_job(self) -> Callable[ - [service.CreateImportJobRequest], - resources.ImportJob]: - r"""Return a callable for the create import job method over gRPC. - - Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] - is required. - - Returns: - Callable[[~.CreateImportJobRequest], - ~.ImportJob]: - 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_import_job' not in self._stubs: - self._stubs['create_import_job'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateImportJob', - request_serializer=service.CreateImportJobRequest.serialize, - response_deserializer=resources.ImportJob.deserialize, - ) - return self._stubs['create_import_job'] - - @property - def update_crypto_key(self) -> Callable[ - [service.UpdateCryptoKeyRequest], - resources.CryptoKey]: - r"""Return a callable for the update crypto key method over gRPC. - - Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.UpdateCryptoKeyRequest], - ~.CryptoKey]: - 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_crypto_key' not in self._stubs: - self._stubs['update_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey', - request_serializer=service.UpdateCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['update_crypto_key'] - - @property - def update_crypto_key_version(self) -> Callable[ - [service.UpdateCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the update crypto key version method over gRPC. - - Update a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - metadata. - - [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be - changed between - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - and - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - using this method. See - [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] - and - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to move between other states. - - Returns: - Callable[[~.UpdateCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - 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_crypto_key_version' not in self._stubs: - self._stubs['update_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion', - request_serializer=service.UpdateCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['update_crypto_key_version'] - - @property - def update_crypto_key_primary_version(self) -> Callable[ - [service.UpdateCryptoKeyPrimaryVersionRequest], - resources.CryptoKey]: - r"""Return a callable for the update crypto key primary - version method over gRPC. - - Update the version of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Returns an error if called on a key whose purpose is not - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.UpdateCryptoKeyPrimaryVersionRequest], - ~.CryptoKey]: - 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_crypto_key_primary_version' not in self._stubs: - self._stubs['update_crypto_key_primary_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion', - request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['update_crypto_key_primary_version'] - - @property - def destroy_crypto_key_version(self) -> Callable[ - [service.DestroyCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the destroy crypto key version method over gRPC. - - Schedule a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for - destruction. - - Upon calling this method, - [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] - will be set to - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be set to the time - [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] - in the future. At that time, the - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will - automatically change to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], - and the key material will be irrevocably destroyed. - - Before the - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - is reached, - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - may be called to reverse the process. - - Returns: - Callable[[~.DestroyCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - 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 'destroy_crypto_key_version' not in self._stubs: - self._stubs['destroy_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion', - request_serializer=service.DestroyCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['destroy_crypto_key_version'] - - @property - def restore_crypto_key_version(self) -> Callable[ - [service.RestoreCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the restore crypto key version method over gRPC. - - Restore a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state. - - Upon restoration of the CryptoKeyVersion, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be cleared. - - Returns: - Callable[[~.RestoreCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - 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 'restore_crypto_key_version' not in self._stubs: - self._stubs['restore_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion', - request_serializer=service.RestoreCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['restore_crypto_key_version'] - - @property - def encrypt(self) -> Callable[ - [service.EncryptRequest], - service.EncryptResponse]: - r"""Return a callable for the encrypt method over gRPC. - - Encrypts data, so that it can only be recovered by a call to - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.EncryptRequest], - ~.EncryptResponse]: - 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 'encrypt' not in self._stubs: - self._stubs['encrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/Encrypt', - request_serializer=service.EncryptRequest.serialize, - response_deserializer=service.EncryptResponse.deserialize, - ) - return self._stubs['encrypt'] - - @property - def decrypt(self) -> Callable[ - [service.DecryptRequest], - service.DecryptResponse]: - r"""Return a callable for the decrypt method over gRPC. - - Decrypts data that was protected by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.DecryptRequest], - ~.DecryptResponse]: - 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 'decrypt' not in self._stubs: - self._stubs['decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/Decrypt', - request_serializer=service.DecryptRequest.serialize, - response_deserializer=service.DecryptResponse.deserialize, - ) - return self._stubs['decrypt'] - - @property - def asymmetric_sign(self) -> Callable[ - [service.AsymmetricSignRequest], - service.AsymmetricSignResponse]: - r"""Return a callable for the asymmetric sign method over gRPC. - - Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_SIGN, producing a signature that can be verified with - the public key retrieved from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Returns: - Callable[[~.AsymmetricSignRequest], - ~.AsymmetricSignResponse]: - 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 'asymmetric_sign' not in self._stubs: - self._stubs['asymmetric_sign'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/AsymmetricSign', - request_serializer=service.AsymmetricSignRequest.serialize, - response_deserializer=service.AsymmetricSignResponse.deserialize, - ) - return self._stubs['asymmetric_sign'] - - @property - def asymmetric_decrypt(self) -> Callable[ - [service.AsymmetricDecryptRequest], - service.AsymmetricDecryptResponse]: - r"""Return a callable for the asymmetric decrypt method over gRPC. - - Decrypts data that was encrypted with a public key retrieved - from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] - corresponding to a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_DECRYPT. - - Returns: - Callable[[~.AsymmetricDecryptRequest], - ~.AsymmetricDecryptResponse]: - 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 'asymmetric_decrypt' not in self._stubs: - self._stubs['asymmetric_decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt', - request_serializer=service.AsymmetricDecryptRequest.serialize, - response_deserializer=service.AsymmetricDecryptResponse.deserialize, - ) - return self._stubs['asymmetric_decrypt'] - - @property - def mac_sign(self) -> Callable[ - [service.MacSignRequest], - service.MacSignResponse]: - r"""Return a callable for the mac sign method over gRPC. - - Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - producing a tag that can be verified by another source with the - same key. - - Returns: - Callable[[~.MacSignRequest], - ~.MacSignResponse]: - 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 'mac_sign' not in self._stubs: - self._stubs['mac_sign'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/MacSign', - request_serializer=service.MacSignRequest.serialize, - response_deserializer=service.MacSignResponse.deserialize, - ) - return self._stubs['mac_sign'] - - @property - def mac_verify(self) -> Callable[ - [service.MacVerifyRequest], - service.MacVerifyResponse]: - r"""Return a callable for the mac verify method over gRPC. - - Verifies MAC tag using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - and returns a response that indicates whether or not the - verification was successful. - - Returns: - Callable[[~.MacVerifyRequest], - ~.MacVerifyResponse]: - 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 'mac_verify' not in self._stubs: - self._stubs['mac_verify'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/MacVerify', - request_serializer=service.MacVerifyRequest.serialize, - response_deserializer=service.MacVerifyResponse.deserialize, - ) - return self._stubs['mac_verify'] - - @property - def generate_random_bytes(self) -> Callable[ - [service.GenerateRandomBytesRequest], - service.GenerateRandomBytesResponse]: - r"""Return a callable for the generate random bytes method over gRPC. - - Generate random bytes using the Cloud KMS randomness - source in the provided location. - - Returns: - Callable[[~.GenerateRandomBytesRequest], - ~.GenerateRandomBytesResponse]: - 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 'generate_random_bytes' not in self._stubs: - self._stubs['generate_random_bytes'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes', - request_serializer=service.GenerateRandomBytesRequest.serialize, - response_deserializer=service.GenerateRandomBytesResponse.deserialize, - ) - return self._stubs['generate_random_bytes'] - - @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__ = ( - 'KeyManagementServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py deleted file mode 100644 index 169f387e..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,1120 +0,0 @@ -# -*- 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 resources -from google.cloud.kms_v1.types import service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import KeyManagementServiceGrpcTransport - - -class KeyManagementServiceGrpcAsyncIOTransport(KeyManagementServiceTransport): - """gRPC AsyncIO backend transport for KeyManagementService. - - Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - - 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, - credentials=self._credentials, - credentials_file=credentials_file, - 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_key_rings(self) -> Callable[ - [service.ListKeyRingsRequest], - Awaitable[service.ListKeyRingsResponse]]: - r"""Return a callable for the list key rings method over gRPC. - - Lists [KeyRings][google.cloud.kms.v1.KeyRing]. - - Returns: - Callable[[~.ListKeyRingsRequest], - Awaitable[~.ListKeyRingsResponse]]: - 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_key_rings' not in self._stubs: - self._stubs['list_key_rings'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListKeyRings', - request_serializer=service.ListKeyRingsRequest.serialize, - response_deserializer=service.ListKeyRingsResponse.deserialize, - ) - return self._stubs['list_key_rings'] - - @property - def list_crypto_keys(self) -> Callable[ - [service.ListCryptoKeysRequest], - Awaitable[service.ListCryptoKeysResponse]]: - r"""Return a callable for the list crypto keys method over gRPC. - - Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.ListCryptoKeysRequest], - Awaitable[~.ListCryptoKeysResponse]]: - 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_crypto_keys' not in self._stubs: - self._stubs['list_crypto_keys'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys', - request_serializer=service.ListCryptoKeysRequest.serialize, - response_deserializer=service.ListCryptoKeysResponse.deserialize, - ) - return self._stubs['list_crypto_keys'] - - @property - def list_crypto_key_versions(self) -> Callable[ - [service.ListCryptoKeyVersionsRequest], - Awaitable[service.ListCryptoKeyVersionsResponse]]: - r"""Return a callable for the list crypto key versions method over gRPC. - - Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.ListCryptoKeyVersionsRequest], - Awaitable[~.ListCryptoKeyVersionsResponse]]: - 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_crypto_key_versions' not in self._stubs: - self._stubs['list_crypto_key_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions', - request_serializer=service.ListCryptoKeyVersionsRequest.serialize, - response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize, - ) - return self._stubs['list_crypto_key_versions'] - - @property - def list_import_jobs(self) -> Callable[ - [service.ListImportJobsRequest], - Awaitable[service.ListImportJobsResponse]]: - r"""Return a callable for the list import jobs method over gRPC. - - Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. - - Returns: - Callable[[~.ListImportJobsRequest], - Awaitable[~.ListImportJobsResponse]]: - 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_import_jobs' not in self._stubs: - self._stubs['list_import_jobs'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListImportJobs', - request_serializer=service.ListImportJobsRequest.serialize, - response_deserializer=service.ListImportJobsResponse.deserialize, - ) - return self._stubs['list_import_jobs'] - - @property - def get_key_ring(self) -> Callable[ - [service.GetKeyRingRequest], - Awaitable[resources.KeyRing]]: - r"""Return a callable for the get key ring method over gRPC. - - Returns metadata for a given - [KeyRing][google.cloud.kms.v1.KeyRing]. - - Returns: - Callable[[~.GetKeyRingRequest], - Awaitable[~.KeyRing]]: - 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_key_ring' not in self._stubs: - self._stubs['get_key_ring'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetKeyRing', - request_serializer=service.GetKeyRingRequest.serialize, - response_deserializer=resources.KeyRing.deserialize, - ) - return self._stubs['get_key_ring'] - - @property - def get_crypto_key(self) -> Callable[ - [service.GetCryptoKeyRequest], - Awaitable[resources.CryptoKey]]: - r"""Return a callable for the get crypto key method over gRPC. - - Returns metadata for a given - [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its - [primary][google.cloud.kms.v1.CryptoKey.primary] - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.GetCryptoKeyRequest], - Awaitable[~.CryptoKey]]: - 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_crypto_key' not in self._stubs: - self._stubs['get_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetCryptoKey', - request_serializer=service.GetCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['get_crypto_key'] - - @property - def get_crypto_key_version(self) -> Callable[ - [service.GetCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the get crypto key version method over gRPC. - - Returns metadata for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.GetCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - 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_crypto_key_version' not in self._stubs: - self._stubs['get_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion', - request_serializer=service.GetCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['get_crypto_key_version'] - - @property - def get_public_key(self) -> Callable[ - [service.GetPublicKeyRequest], - Awaitable[resources.PublicKey]]: - r"""Return a callable for the get public key method over gRPC. - - Returns the public key for the given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] - or - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - Returns: - Callable[[~.GetPublicKeyRequest], - Awaitable[~.PublicKey]]: - 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_public_key' not in self._stubs: - self._stubs['get_public_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetPublicKey', - request_serializer=service.GetPublicKeyRequest.serialize, - response_deserializer=resources.PublicKey.deserialize, - ) - return self._stubs['get_public_key'] - - @property - def get_import_job(self) -> Callable[ - [service.GetImportJobRequest], - Awaitable[resources.ImportJob]]: - r"""Return a callable for the get import job method over gRPC. - - Returns metadata for a given - [ImportJob][google.cloud.kms.v1.ImportJob]. - - Returns: - Callable[[~.GetImportJobRequest], - Awaitable[~.ImportJob]]: - 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_import_job' not in self._stubs: - self._stubs['get_import_job'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetImportJob', - request_serializer=service.GetImportJobRequest.serialize, - response_deserializer=resources.ImportJob.deserialize, - ) - return self._stubs['get_import_job'] - - @property - def create_key_ring(self) -> Callable[ - [service.CreateKeyRingRequest], - Awaitable[resources.KeyRing]]: - r"""Return a callable for the create key ring method over gRPC. - - Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given - Project and Location. - - Returns: - Callable[[~.CreateKeyRingRequest], - Awaitable[~.KeyRing]]: - 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_key_ring' not in self._stubs: - self._stubs['create_key_ring'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateKeyRing', - request_serializer=service.CreateKeyRingRequest.serialize, - response_deserializer=resources.KeyRing.deserialize, - ) - return self._stubs['create_key_ring'] - - @property - def create_crypto_key(self) -> Callable[ - [service.CreateCryptoKeyRequest], - Awaitable[resources.CryptoKey]]: - r"""Return a callable for the create crypto key method over gRPC. - - Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and - [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] - are required. - - Returns: - Callable[[~.CreateCryptoKeyRequest], - Awaitable[~.CryptoKey]]: - 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_crypto_key' not in self._stubs: - self._stubs['create_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey', - request_serializer=service.CreateCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['create_crypto_key'] - - @property - def create_crypto_key_version(self) -> Callable[ - [service.CreateCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the create crypto key version method over gRPC. - - Create a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - The server will assign the next sequential id. If unset, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. - - Returns: - Callable[[~.CreateCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - 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_crypto_key_version' not in self._stubs: - self._stubs['create_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion', - request_serializer=service.CreateCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['create_crypto_key_version'] - - @property - def import_crypto_key_version(self) -> Callable[ - [service.ImportCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the import crypto key version method over gRPC. - - Import wrapped key material into a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - All requests must specify a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is - additionally specified in the request, key material will be - reimported into that version. Otherwise, a new version will be - created, and will be assigned the next sequential id within the - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.ImportCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - 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 'import_crypto_key_version' not in self._stubs: - self._stubs['import_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion', - request_serializer=service.ImportCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['import_crypto_key_version'] - - @property - def create_import_job(self) -> Callable[ - [service.CreateImportJobRequest], - Awaitable[resources.ImportJob]]: - r"""Return a callable for the create import job method over gRPC. - - Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] - is required. - - Returns: - Callable[[~.CreateImportJobRequest], - Awaitable[~.ImportJob]]: - 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_import_job' not in self._stubs: - self._stubs['create_import_job'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateImportJob', - request_serializer=service.CreateImportJobRequest.serialize, - response_deserializer=resources.ImportJob.deserialize, - ) - return self._stubs['create_import_job'] - - @property - def update_crypto_key(self) -> Callable[ - [service.UpdateCryptoKeyRequest], - Awaitable[resources.CryptoKey]]: - r"""Return a callable for the update crypto key method over gRPC. - - Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.UpdateCryptoKeyRequest], - Awaitable[~.CryptoKey]]: - 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_crypto_key' not in self._stubs: - self._stubs['update_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey', - request_serializer=service.UpdateCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['update_crypto_key'] - - @property - def update_crypto_key_version(self) -> Callable[ - [service.UpdateCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the update crypto key version method over gRPC. - - Update a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - metadata. - - [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be - changed between - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - and - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - using this method. See - [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] - and - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to move between other states. - - Returns: - Callable[[~.UpdateCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - 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_crypto_key_version' not in self._stubs: - self._stubs['update_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion', - request_serializer=service.UpdateCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['update_crypto_key_version'] - - @property - def update_crypto_key_primary_version(self) -> Callable[ - [service.UpdateCryptoKeyPrimaryVersionRequest], - Awaitable[resources.CryptoKey]]: - r"""Return a callable for the update crypto key primary - version method over gRPC. - - Update the version of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Returns an error if called on a key whose purpose is not - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.UpdateCryptoKeyPrimaryVersionRequest], - Awaitable[~.CryptoKey]]: - 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_crypto_key_primary_version' not in self._stubs: - self._stubs['update_crypto_key_primary_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion', - request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['update_crypto_key_primary_version'] - - @property - def destroy_crypto_key_version(self) -> Callable[ - [service.DestroyCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the destroy crypto key version method over gRPC. - - Schedule a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for - destruction. - - Upon calling this method, - [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] - will be set to - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be set to the time - [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] - in the future. At that time, the - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will - automatically change to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], - and the key material will be irrevocably destroyed. - - Before the - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - is reached, - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - may be called to reverse the process. - - Returns: - Callable[[~.DestroyCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - 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 'destroy_crypto_key_version' not in self._stubs: - self._stubs['destroy_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion', - request_serializer=service.DestroyCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['destroy_crypto_key_version'] - - @property - def restore_crypto_key_version(self) -> Callable[ - [service.RestoreCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the restore crypto key version method over gRPC. - - Restore a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state. - - Upon restoration of the CryptoKeyVersion, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be cleared. - - Returns: - Callable[[~.RestoreCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - 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 'restore_crypto_key_version' not in self._stubs: - self._stubs['restore_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion', - request_serializer=service.RestoreCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['restore_crypto_key_version'] - - @property - def encrypt(self) -> Callable[ - [service.EncryptRequest], - Awaitable[service.EncryptResponse]]: - r"""Return a callable for the encrypt method over gRPC. - - Encrypts data, so that it can only be recovered by a call to - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.EncryptRequest], - Awaitable[~.EncryptResponse]]: - 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 'encrypt' not in self._stubs: - self._stubs['encrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/Encrypt', - request_serializer=service.EncryptRequest.serialize, - response_deserializer=service.EncryptResponse.deserialize, - ) - return self._stubs['encrypt'] - - @property - def decrypt(self) -> Callable[ - [service.DecryptRequest], - Awaitable[service.DecryptResponse]]: - r"""Return a callable for the decrypt method over gRPC. - - Decrypts data that was protected by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.DecryptRequest], - Awaitable[~.DecryptResponse]]: - 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 'decrypt' not in self._stubs: - self._stubs['decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/Decrypt', - request_serializer=service.DecryptRequest.serialize, - response_deserializer=service.DecryptResponse.deserialize, - ) - return self._stubs['decrypt'] - - @property - def asymmetric_sign(self) -> Callable[ - [service.AsymmetricSignRequest], - Awaitable[service.AsymmetricSignResponse]]: - r"""Return a callable for the asymmetric sign method over gRPC. - - Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_SIGN, producing a signature that can be verified with - the public key retrieved from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Returns: - Callable[[~.AsymmetricSignRequest], - Awaitable[~.AsymmetricSignResponse]]: - 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 'asymmetric_sign' not in self._stubs: - self._stubs['asymmetric_sign'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/AsymmetricSign', - request_serializer=service.AsymmetricSignRequest.serialize, - response_deserializer=service.AsymmetricSignResponse.deserialize, - ) - return self._stubs['asymmetric_sign'] - - @property - def asymmetric_decrypt(self) -> Callable[ - [service.AsymmetricDecryptRequest], - Awaitable[service.AsymmetricDecryptResponse]]: - r"""Return a callable for the asymmetric decrypt method over gRPC. - - Decrypts data that was encrypted with a public key retrieved - from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] - corresponding to a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_DECRYPT. - - Returns: - Callable[[~.AsymmetricDecryptRequest], - Awaitable[~.AsymmetricDecryptResponse]]: - 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 'asymmetric_decrypt' not in self._stubs: - self._stubs['asymmetric_decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt', - request_serializer=service.AsymmetricDecryptRequest.serialize, - response_deserializer=service.AsymmetricDecryptResponse.deserialize, - ) - return self._stubs['asymmetric_decrypt'] - - @property - def mac_sign(self) -> Callable[ - [service.MacSignRequest], - Awaitable[service.MacSignResponse]]: - r"""Return a callable for the mac sign method over gRPC. - - Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - producing a tag that can be verified by another source with the - same key. - - Returns: - Callable[[~.MacSignRequest], - Awaitable[~.MacSignResponse]]: - 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 'mac_sign' not in self._stubs: - self._stubs['mac_sign'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/MacSign', - request_serializer=service.MacSignRequest.serialize, - response_deserializer=service.MacSignResponse.deserialize, - ) - return self._stubs['mac_sign'] - - @property - def mac_verify(self) -> Callable[ - [service.MacVerifyRequest], - Awaitable[service.MacVerifyResponse]]: - r"""Return a callable for the mac verify method over gRPC. - - Verifies MAC tag using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - and returns a response that indicates whether or not the - verification was successful. - - Returns: - Callable[[~.MacVerifyRequest], - Awaitable[~.MacVerifyResponse]]: - 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 'mac_verify' not in self._stubs: - self._stubs['mac_verify'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/MacVerify', - request_serializer=service.MacVerifyRequest.serialize, - response_deserializer=service.MacVerifyResponse.deserialize, - ) - return self._stubs['mac_verify'] - - @property - def generate_random_bytes(self) -> Callable[ - [service.GenerateRandomBytesRequest], - Awaitable[service.GenerateRandomBytesResponse]]: - r"""Return a callable for the generate random bytes method over gRPC. - - Generate random bytes using the Cloud KMS randomness - source in the provided location. - - Returns: - Callable[[~.GenerateRandomBytesRequest], - Awaitable[~.GenerateRandomBytesResponse]]: - 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 'generate_random_bytes' not in self._stubs: - self._stubs['generate_random_bytes'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes', - request_serializer=service.GenerateRandomBytesRequest.serialize, - response_deserializer=service.GenerateRandomBytesResponse.deserialize, - ) - return self._stubs['generate_random_bytes'] - - @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__ = ( - 'KeyManagementServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py deleted file mode 100644 index edc01123..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- 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 .resources import ( - CryptoKey, - CryptoKeyVersion, - CryptoKeyVersionTemplate, - ExternalProtectionLevelOptions, - ImportJob, - KeyOperationAttestation, - KeyRing, - PublicKey, - ProtectionLevel, -) -from .service import ( - AsymmetricDecryptRequest, - AsymmetricDecryptResponse, - AsymmetricSignRequest, - AsymmetricSignResponse, - CreateCryptoKeyRequest, - CreateCryptoKeyVersionRequest, - CreateImportJobRequest, - CreateKeyRingRequest, - DecryptRequest, - DecryptResponse, - DestroyCryptoKeyVersionRequest, - Digest, - EncryptRequest, - EncryptResponse, - GenerateRandomBytesRequest, - GenerateRandomBytesResponse, - GetCryptoKeyRequest, - GetCryptoKeyVersionRequest, - GetImportJobRequest, - GetKeyRingRequest, - GetPublicKeyRequest, - ImportCryptoKeyVersionRequest, - ListCryptoKeysRequest, - ListCryptoKeysResponse, - ListCryptoKeyVersionsRequest, - ListCryptoKeyVersionsResponse, - ListImportJobsRequest, - ListImportJobsResponse, - ListKeyRingsRequest, - ListKeyRingsResponse, - LocationMetadata, - MacSignRequest, - MacSignResponse, - MacVerifyRequest, - MacVerifyResponse, - RestoreCryptoKeyVersionRequest, - UpdateCryptoKeyPrimaryVersionRequest, - UpdateCryptoKeyRequest, - UpdateCryptoKeyVersionRequest, -) - -__all__ = ( - 'CryptoKey', - 'CryptoKeyVersion', - 'CryptoKeyVersionTemplate', - 'ExternalProtectionLevelOptions', - 'ImportJob', - 'KeyOperationAttestation', - 'KeyRing', - 'PublicKey', - 'ProtectionLevel', - 'AsymmetricDecryptRequest', - 'AsymmetricDecryptResponse', - 'AsymmetricSignRequest', - 'AsymmetricSignResponse', - 'CreateCryptoKeyRequest', - 'CreateCryptoKeyVersionRequest', - 'CreateImportJobRequest', - 'CreateKeyRingRequest', - 'DecryptRequest', - 'DecryptResponse', - 'DestroyCryptoKeyVersionRequest', - 'Digest', - 'EncryptRequest', - 'EncryptResponse', - 'GenerateRandomBytesRequest', - 'GenerateRandomBytesResponse', - 'GetCryptoKeyRequest', - 'GetCryptoKeyVersionRequest', - 'GetImportJobRequest', - 'GetKeyRingRequest', - 'GetPublicKeyRequest', - 'ImportCryptoKeyVersionRequest', - 'ListCryptoKeysRequest', - 'ListCryptoKeysResponse', - 'ListCryptoKeyVersionsRequest', - 'ListCryptoKeyVersionsResponse', - 'ListImportJobsRequest', - 'ListImportJobsResponse', - 'ListKeyRingsRequest', - 'ListKeyRingsResponse', - 'LocationMetadata', - 'MacSignRequest', - 'MacSignResponse', - 'MacVerifyRequest', - 'MacVerifyResponse', - 'RestoreCryptoKeyVersionRequest', - 'UpdateCryptoKeyPrimaryVersionRequest', - 'UpdateCryptoKeyRequest', - 'UpdateCryptoKeyVersionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py b/owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py deleted file mode 100644 index 5abdc1ca..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py +++ /dev/null @@ -1,843 +0,0 @@ -# -*- 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 duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.kms.v1', - manifest={ - 'ProtectionLevel', - 'KeyRing', - 'CryptoKey', - 'CryptoKeyVersionTemplate', - 'KeyOperationAttestation', - 'CryptoKeyVersion', - 'PublicKey', - 'ImportJob', - 'ExternalProtectionLevelOptions', - }, -) - - -class ProtectionLevel(proto.Enum): - r"""[ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] specifies how - cryptographic operations are performed. For more information, see - [Protection levels] - (https://cloud.google.com/kms/docs/algorithms#protection_levels). - """ - PROTECTION_LEVEL_UNSPECIFIED = 0 - SOFTWARE = 1 - HSM = 2 - EXTERNAL = 3 - - -class KeyRing(proto.Message): - r"""A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical - grouping of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - Attributes: - name (str): - Output only. The resource name for the - [KeyRing][google.cloud.kms.v1.KeyRing] in the format - ``projects/*/locations/*/keyRings/*``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [KeyRing][google.cloud.kms.v1.KeyRing] was created. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - create_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class CryptoKey(proto.Message): - r"""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 [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic operations. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The resource name for this - [CryptoKey][google.cloud.kms.v1.CryptoKey] in the format - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - primary (google.cloud.kms_v1.types.CryptoKeyVersion): - Output only. A copy of the "primary" - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - that will be used by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] - when this [CryptoKey][google.cloud.kms.v1.CryptoKey] is - given in - [EncryptRequest.name][google.cloud.kms.v1.EncryptRequest.name]. - - The [CryptoKey][google.cloud.kms.v1.CryptoKey]'s primary - version can be updated via - [UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - - Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] - may have a primary. For other keys, this field will be - omitted. - purpose (google.cloud.kms_v1.types.CryptoKey.CryptoKeyPurpose): - Immutable. The immutable purpose of this - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [CryptoKey][google.cloud.kms.v1.CryptoKey] was created. - next_rotation_time (google.protobuf.timestamp_pb2.Timestamp): - At - [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time], - the Key Management Service will automatically: - - 1. Create a new version of this - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - 2. Mark the new version as primary. - - Key rotations performed manually via - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - and - [UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion] - do not affect - [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time]. - - Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] - support automatic rotation. For other keys, this field must - be omitted. - rotation_period (google.protobuf.duration_pb2.Duration): - [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] - will be advanced by this period when the service - automatically rotates a key. Must be at least 24 hours and - at most 876,000 hours. - - If - [rotation_period][google.cloud.kms.v1.CryptoKey.rotation_period] - is set, - [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] - must also be set. - - Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] - [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 - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - instances. The properties of new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - instances created by either - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - or auto-rotation are controlled by this template. - labels (Sequence[google.cloud.kms_v1.types.CryptoKey.LabelsEntry]): - Labels with user-defined metadata. For more information, see - `Labeling - Keys `__. - import_only (bool): - Immutable. Whether this key may contain - imported versions only. - destroy_scheduled_duration (google.protobuf.duration_pb2.Duration): - Immutable. The period of time that versions of this key - spend in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state before transitioning to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. - If not specified at creation time, the default duration is - 24 hours. - """ - class CryptoKeyPurpose(proto.Enum): - r"""[CryptoKeyPurpose][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose] - describes the cryptographic capabilities of a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. A given key can only be - used for the operations allowed by its purpose. For more - information, see `Key - purposes `__. - """ - CRYPTO_KEY_PURPOSE_UNSPECIFIED = 0 - ENCRYPT_DECRYPT = 1 - ASYMMETRIC_SIGN = 5 - ASYMMETRIC_DECRYPT = 6 - MAC = 9 - - name = proto.Field( - proto.STRING, - number=1, - ) - primary = proto.Field( - proto.MESSAGE, - number=2, - message='CryptoKeyVersion', - ) - purpose = proto.Field( - proto.ENUM, - number=3, - enum=CryptoKeyPurpose, - ) - create_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - next_rotation_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - rotation_period = proto.Field( - proto.MESSAGE, - number=8, - oneof='rotation_schedule', - message=duration_pb2.Duration, - ) - version_template = proto.Field( - proto.MESSAGE, - number=11, - message='CryptoKeyVersionTemplate', - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - import_only = proto.Field( - proto.BOOL, - number=13, - ) - destroy_scheduled_duration = proto.Field( - proto.MESSAGE, - number=14, - message=duration_pb2.Duration, - ) - - -class CryptoKeyVersionTemplate(proto.Message): - r"""A - [CryptoKeyVersionTemplate][google.cloud.kms.v1.CryptoKeyVersionTemplate] - specifies the properties to use when creating a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], either - manually with - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - or automatically as a result of auto-rotation. - - Attributes: - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] to - use when creating a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - based on this template. Immutable. Defaults to - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. - algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): - Required. - [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] - to use when creating a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - based on this template. - - For backwards compatibility, GOOGLE_SYMMETRIC_ENCRYPTION is - implied if both this field is omitted and - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - is - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - """ - - protection_level = proto.Field( - proto.ENUM, - number=1, - enum='ProtectionLevel', - ) - algorithm = proto.Field( - proto.ENUM, - number=3, - enum='CryptoKeyVersion.CryptoKeyVersionAlgorithm', - ) - - -class KeyOperationAttestation(proto.Message): - r"""Contains an HSM-generated attestation about a key operation. For - more information, see [Verifying attestations] - (https://cloud.google.com/kms/docs/attest-key). - - Attributes: - format_ (google.cloud.kms_v1.types.KeyOperationAttestation.AttestationFormat): - Output only. The format of the attestation - data. - content (bytes): - Output only. The attestation data provided by - the HSM when the key operation was performed. - """ - class AttestationFormat(proto.Enum): - r"""Attestation formats provided by the HSM.""" - ATTESTATION_FORMAT_UNSPECIFIED = 0 - CAVIUM_V1_COMPRESSED = 3 - CAVIUM_V2_COMPRESSED = 4 - - format_ = proto.Field( - proto.ENUM, - number=4, - enum=AttestationFormat, - ) - content = proto.Field( - proto.BYTES, - number=5, - ) - - -class CryptoKeyVersion(proto.Message): - r"""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] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material represented - by a [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] can - never be viewed or exported. It can only be used to encrypt, - decrypt, or sign data when an authorized user or application invokes - Cloud KMS. - - Attributes: - name (str): - Output only. The resource name for this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in - the format - ``projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*``. - state (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionState): - The current state of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - Output only. The - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - describing how crypto operations are performed with this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): - Output only. The - [CryptoKeyVersionAlgorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] - that this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - supports. - attestation (google.cloud.kms_v1.types.KeyOperationAttestation): - Output only. Statement that was generated and signed by the - HSM at key creation time. Use this statement to verify - attributes of the key as stored on the HSM, independently of - Google. Only provided for key versions with - [protection_level][google.cloud.kms.v1.CryptoKeyVersion.protection_level] - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] was - created. - generate_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - key material was generated. - destroy_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - key material is scheduled for destruction. Only present if - [state][google.cloud.kms.v1.CryptoKeyVersion.state] is - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED]. - destroy_event_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this CryptoKeyVersion's key material - was destroyed. Only present if - [state][google.cloud.kms.v1.CryptoKeyVersion.state] is - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. - import_job (str): - Output only. The name of the - [ImportJob][google.cloud.kms.v1.ImportJob] used in the most - recent import of this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - Only present if the underlying key material was imported. - import_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - key material was most recently imported. - import_failure_reason (str): - Output only. The root cause of the most recent import - failure. Only present if - [state][google.cloud.kms.v1.CryptoKeyVersion.state] is - [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED]. - external_protection_level_options (google.cloud.kms_v1.types.ExternalProtectionLevelOptions): - ExternalProtectionLevelOptions stores a group of additional - fields for configuring a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - that are specific to the - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] - protection level. - reimport_eligible (bool): - Output only. Whether or not this key version is eligible for - reimport, by being specified as a target in - [ImportCryptoKeyVersionRequest.crypto_key_version][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.crypto_key_version]. - """ - class CryptoKeyVersionAlgorithm(proto.Enum): - r"""The algorithm of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], indicating - what parameters must be used for each cryptographic operation. - - The - [GOOGLE_SYMMETRIC_ENCRYPTION][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION] - algorithm is usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Algorithms beginning with "RSA_SIGN_" are usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]. - - The fields in the name after "RSA_SIGN_" correspond to the following - parameters: padding algorithm, modulus bit length, and digest - algorithm. - - For PSS, the salt length used is equal to the length of digest - algorithm. For example, - [RSA_SIGN_PSS_2048_SHA256][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PSS_2048_SHA256] - will use PSS with a salt length of 256 bits or 32 bytes. - - Algorithms beginning with "RSA_DECRYPT_" are usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - The fields in the name after "RSA_DECRYPT_" correspond to the - following parameters: padding algorithm, modulus bit length, and - digest algorithm. - - Algorithms beginning with "EC_SIGN_" are usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]. - - The fields in the name after "EC_SIGN_" correspond to the following - parameters: elliptic curve, digest algorithm. - - Algorithms beginning with "HMAC_" are usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [MAC][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.MAC]. - - The suffix following "HMAC_" corresponds to the hash algorithm being - used (eg. SHA256). - - For more information, see [Key purposes and algorithms] - (https://cloud.google.com/kms/docs/algorithms). - """ - CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED = 0 - GOOGLE_SYMMETRIC_ENCRYPTION = 1 - RSA_SIGN_PSS_2048_SHA256 = 2 - RSA_SIGN_PSS_3072_SHA256 = 3 - RSA_SIGN_PSS_4096_SHA256 = 4 - RSA_SIGN_PSS_4096_SHA512 = 15 - RSA_SIGN_PKCS1_2048_SHA256 = 5 - RSA_SIGN_PKCS1_3072_SHA256 = 6 - RSA_SIGN_PKCS1_4096_SHA256 = 7 - RSA_SIGN_PKCS1_4096_SHA512 = 16 - RSA_SIGN_RAW_PKCS1_2048 = 28 - RSA_SIGN_RAW_PKCS1_3072 = 29 - RSA_SIGN_RAW_PKCS1_4096 = 30 - RSA_DECRYPT_OAEP_2048_SHA256 = 8 - RSA_DECRYPT_OAEP_3072_SHA256 = 9 - RSA_DECRYPT_OAEP_4096_SHA256 = 10 - RSA_DECRYPT_OAEP_4096_SHA512 = 17 - RSA_DECRYPT_OAEP_2048_SHA1 = 37 - RSA_DECRYPT_OAEP_3072_SHA1 = 38 - RSA_DECRYPT_OAEP_4096_SHA1 = 39 - EC_SIGN_P256_SHA256 = 12 - EC_SIGN_P384_SHA384 = 13 - EC_SIGN_SECP256K1_SHA256 = 31 - HMAC_SHA256 = 32 - EXTERNAL_SYMMETRIC_ENCRYPTION = 18 - - class CryptoKeyVersionState(proto.Enum): - r"""The state of a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], indicating - if it can be used. - """ - CRYPTO_KEY_VERSION_STATE_UNSPECIFIED = 0 - PENDING_GENERATION = 5 - ENABLED = 1 - DISABLED = 2 - DESTROYED = 3 - DESTROY_SCHEDULED = 4 - PENDING_IMPORT = 6 - IMPORT_FAILED = 7 - - class CryptoKeyVersionView(proto.Enum): - r"""A view for - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]s. Controls - the level of detail returned for - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] in - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions] - and - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - """ - CRYPTO_KEY_VERSION_VIEW_UNSPECIFIED = 0 - FULL = 1 - - name = proto.Field( - proto.STRING, - number=1, - ) - state = proto.Field( - proto.ENUM, - number=3, - enum=CryptoKeyVersionState, - ) - protection_level = proto.Field( - proto.ENUM, - number=7, - enum='ProtectionLevel', - ) - algorithm = proto.Field( - proto.ENUM, - number=10, - enum=CryptoKeyVersionAlgorithm, - ) - attestation = proto.Field( - proto.MESSAGE, - number=8, - message='KeyOperationAttestation', - ) - create_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - generate_time = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - destroy_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - destroy_event_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - import_job = proto.Field( - proto.STRING, - number=14, - ) - import_time = proto.Field( - proto.MESSAGE, - number=15, - message=timestamp_pb2.Timestamp, - ) - import_failure_reason = proto.Field( - proto.STRING, - number=16, - ) - external_protection_level_options = proto.Field( - proto.MESSAGE, - number=17, - message='ExternalProtectionLevelOptions', - ) - reimport_eligible = proto.Field( - proto.BOOL, - number=18, - ) - - -class PublicKey(proto.Message): - r"""The public key for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained - via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Attributes: - pem (str): - The public key, encoded in PEM format. For more information, - see the `RFC 7468 `__ - sections for `General - Considerations `__ - and [Textual Encoding of Subject Public Key Info] - (https://tools.ietf.org/html/rfc7468#section-13). - algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): - The - [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] - associated with this key. - pem_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem]. - An integrity check of - [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem] can be - performed by computing the CRC32C checksum of - [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem] and - comparing your results to this field. Discard the response - in case of non-matching checksum values, and perform a - limited number of retries. A persistent mismatch may - indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - - NOTE: This field is in Beta. - name (str): - The [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key. Provided here for verification. - - NOTE: This field is in Beta. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key. - """ - - pem = proto.Field( - proto.STRING, - number=1, - ) - algorithm = proto.Field( - proto.ENUM, - number=2, - enum='CryptoKeyVersion.CryptoKeyVersionAlgorithm', - ) - pem_crc32c = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - name = proto.Field( - proto.STRING, - number=4, - ) - protection_level = proto.Field( - proto.ENUM, - number=5, - enum='ProtectionLevel', - ) - - -class ImportJob(proto.Message): - r"""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. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is created, Cloud - KMS will generate a "wrapping key", which is a public/private key - pair. You use the wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the import process. - The nature of the wrapping key depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. When - the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] and - the [public_key][google.cloud.kms.v1.ImportJob.public_key] can be - fetched. The fetched public key can then be used to wrap your - pre-existing key material. - - Once the key material is wrapped, it can be imported into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in an - existing [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS uses the - private key portion of the wrapping key to unwrap the key material. - Only Cloud KMS has access to the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 days after - it is created. Once expired, Cloud KMS will no longer be able to - import or unwrap any key material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. - - For more information, see `Importing a - key `__. - - Attributes: - name (str): - Output only. The resource name for this - [ImportJob][google.cloud.kms.v1.ImportJob] in the format - ``projects/*/locations/*/keyRings/*/importJobs/*``. - import_method (google.cloud.kms_v1.types.ImportJob.ImportMethod): - Required. Immutable. The wrapping method to - be used for incoming key material. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - Required. Immutable. The protection level of the - [ImportJob][google.cloud.kms.v1.ImportJob]. This must match - the - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] - of the - [version_template][google.cloud.kms.v1.CryptoKey.version_template] - on the [CryptoKey][google.cloud.kms.v1.CryptoKey] you - attempt to import into. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [ImportJob][google.cloud.kms.v1.ImportJob] was created. - generate_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this - [ImportJob][google.cloud.kms.v1.ImportJob]'s key material - was generated. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [ImportJob][google.cloud.kms.v1.ImportJob] is scheduled for - expiration and can no longer be used to import key material. - expire_event_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this - [ImportJob][google.cloud.kms.v1.ImportJob] expired. Only - present if [state][google.cloud.kms.v1.ImportJob.state] is - [EXPIRED][google.cloud.kms.v1.ImportJob.ImportJobState.EXPIRED]. - state (google.cloud.kms_v1.types.ImportJob.ImportJobState): - Output only. The current state of the - [ImportJob][google.cloud.kms.v1.ImportJob], indicating if it - can be used. - public_key (google.cloud.kms_v1.types.ImportJob.WrappingPublicKey): - Output only. The public key with which to wrap key material - prior to import. Only returned if - [state][google.cloud.kms.v1.ImportJob.state] is - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE]. - attestation (google.cloud.kms_v1.types.KeyOperationAttestation): - Output only. Statement that was generated and signed by the - key creator (for example, an HSM) at key creation time. Use - this statement to verify attributes of the key as stored on - the HSM, independently of Google. Only present if the chosen - [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] - is one with a protection level of - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. - """ - class ImportMethod(proto.Enum): - r"""[ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] describes - the key wrapping method chosen for this - [ImportJob][google.cloud.kms.v1.ImportJob]. - """ - IMPORT_METHOD_UNSPECIFIED = 0 - RSA_OAEP_3072_SHA1_AES_256 = 1 - RSA_OAEP_4096_SHA1_AES_256 = 2 - - class ImportJobState(proto.Enum): - r"""The state of the [ImportJob][google.cloud.kms.v1.ImportJob], - indicating if it can be used. - """ - IMPORT_JOB_STATE_UNSPECIFIED = 0 - PENDING_GENERATION = 1 - ACTIVE = 2 - EXPIRED = 3 - - class WrappingPublicKey(proto.Message): - r"""The public key component of the wrapping key. For details of the - type of key this public key corresponds to, see the - [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod]. - - Attributes: - pem (str): - The public key, encoded in PEM format. For more information, - see the `RFC 7468 `__ - sections for `General - Considerations `__ - and [Textual Encoding of Subject Public Key Info] - (https://tools.ietf.org/html/rfc7468#section-13). - """ - - pem = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - import_method = proto.Field( - proto.ENUM, - number=2, - enum=ImportMethod, - ) - protection_level = proto.Field( - proto.ENUM, - number=9, - enum='ProtectionLevel', - ) - create_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - generate_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - expire_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - expire_event_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - state = proto.Field( - proto.ENUM, - number=6, - enum=ImportJobState, - ) - public_key = proto.Field( - proto.MESSAGE, - number=7, - message=WrappingPublicKey, - ) - attestation = proto.Field( - proto.MESSAGE, - number=8, - message='KeyOperationAttestation', - ) - - -class ExternalProtectionLevelOptions(proto.Message): - r"""ExternalProtectionLevelOptions stores a group of additional fields - for configuring a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that are - specific to the - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] protection - level. - - Attributes: - external_key_uri (str): - The URI for an external resource that this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents. - """ - - external_key_uri = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/types/service.py b/owl-bot-staging/v1/google/cloud/kms_v1/types/service.py deleted file mode 100644 index bc445cf8..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/types/service.py +++ /dev/null @@ -1,1974 +0,0 @@ -# -*- 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.cloud.kms_v1.types import resources -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.kms.v1', - manifest={ - 'ListKeyRingsRequest', - 'ListCryptoKeysRequest', - 'ListCryptoKeyVersionsRequest', - 'ListImportJobsRequest', - 'ListKeyRingsResponse', - 'ListCryptoKeysResponse', - 'ListCryptoKeyVersionsResponse', - 'ListImportJobsResponse', - 'GetKeyRingRequest', - 'GetCryptoKeyRequest', - 'GetCryptoKeyVersionRequest', - 'GetPublicKeyRequest', - 'GetImportJobRequest', - 'CreateKeyRingRequest', - 'CreateCryptoKeyRequest', - 'CreateCryptoKeyVersionRequest', - 'ImportCryptoKeyVersionRequest', - 'CreateImportJobRequest', - 'UpdateCryptoKeyRequest', - 'UpdateCryptoKeyVersionRequest', - 'UpdateCryptoKeyPrimaryVersionRequest', - 'DestroyCryptoKeyVersionRequest', - 'RestoreCryptoKeyVersionRequest', - 'EncryptRequest', - 'DecryptRequest', - 'AsymmetricSignRequest', - 'AsymmetricDecryptRequest', - 'MacSignRequest', - 'MacVerifyRequest', - 'GenerateRandomBytesRequest', - 'EncryptResponse', - 'DecryptResponse', - 'AsymmetricSignResponse', - 'AsymmetricDecryptResponse', - 'MacSignResponse', - 'MacVerifyResponse', - 'GenerateRandomBytesResponse', - 'Digest', - 'LocationMetadata', - }, -) - - -class ListKeyRingsRequest(proto.Message): - r"""Request message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - Attributes: - parent (str): - Required. The resource name of the location associated with - the [KeyRings][google.cloud.kms.v1.KeyRing], in the format - ``projects/*/locations/*``. - page_size (int): - Optional. Optional limit on the number of - [KeyRings][google.cloud.kms.v1.KeyRing] to include in the - response. Further [KeyRings][google.cloud.kms.v1.KeyRing] - can subsequently be obtained by including the - [ListKeyRingsResponse.next_page_token][google.cloud.kms.v1.ListKeyRingsResponse.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 - [ListKeyRingsResponse.next_page_token][google.cloud.kms.v1.ListKeyRingsResponse.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 ListCryptoKeysRequest(proto.Message): - r"""Request message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Attributes: - parent (str): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - page_size (int): - Optional. Optional limit on the number of - [CryptoKeys][google.cloud.kms.v1.CryptoKey] to include in - the response. Further - [CryptoKeys][google.cloud.kms.v1.CryptoKey] can subsequently - be obtained by including the - [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.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 - [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token]. - version_view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): - The fields of the primary version to include - in the response. - 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, - ) - version_view = proto.Field( - proto.ENUM, - number=4, - enum=resources.CryptoKeyVersion.CryptoKeyVersionView, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - order_by = proto.Field( - proto.STRING, - number=6, - ) - - -class ListCryptoKeyVersionsRequest(proto.Message): - r"""Request message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - Attributes: - parent (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in the - format ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - page_size (int): - Optional. Optional limit on the number of - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] to - include in the response. Further - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can subsequently be obtained by including the - [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.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 - [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token]. - view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): - The fields to include in the response. - 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, - ) - view = proto.Field( - proto.ENUM, - number=4, - enum=resources.CryptoKeyVersion.CryptoKeyVersionView, - ) - filter = proto.Field( - proto.STRING, - number=5, - ) - order_by = proto.Field( - proto.STRING, - number=6, - ) - - -class ListImportJobsRequest(proto.Message): - r"""Request message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - Attributes: - parent (str): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - page_size (int): - Optional. Optional limit on the number of - [ImportJobs][google.cloud.kms.v1.ImportJob] to include in - the response. Further - [ImportJobs][google.cloud.kms.v1.ImportJob] can subsequently - be obtained by including the - [ListImportJobsResponse.next_page_token][google.cloud.kms.v1.ListImportJobsResponse.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 - [ListImportJobsResponse.next_page_token][google.cloud.kms.v1.ListImportJobsResponse.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 ListKeyRingsResponse(proto.Message): - r"""Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - Attributes: - key_rings (Sequence[google.cloud.kms_v1.types.KeyRing]): - The list of [KeyRings][google.cloud.kms.v1.KeyRing]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListKeyRingsRequest.page_token][google.cloud.kms.v1.ListKeyRingsRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of [KeyRings][google.cloud.kms.v1.KeyRing] - that matched the query. - """ - - @property - def raw_page(self): - return self - - key_rings = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.KeyRing, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCryptoKeysResponse(proto.Message): - r"""Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Attributes: - crypto_keys (Sequence[google.cloud.kms_v1.types.CryptoKey]): - The list of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListCryptoKeysRequest.page_token][google.cloud.kms.v1.ListCryptoKeysRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of - [CryptoKeys][google.cloud.kms.v1.CryptoKey] that matched the - query. - """ - - @property - def raw_page(self): - return self - - crypto_keys = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.CryptoKey, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCryptoKeyVersionsResponse(proto.Message): - r"""Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - Attributes: - crypto_key_versions (Sequence[google.cloud.kms_v1.types.CryptoKeyVersion]): - The list of - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListCryptoKeyVersionsRequest.page_token][google.cloud.kms.v1.ListCryptoKeyVersionsRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - that matched the query. - """ - - @property - def raw_page(self): - return self - - crypto_key_versions = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.CryptoKeyVersion, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListImportJobsResponse(proto.Message): - r"""Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - Attributes: - import_jobs (Sequence[google.cloud.kms_v1.types.ImportJob]): - The list of [ImportJobs][google.cloud.kms.v1.ImportJob]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListImportJobsRequest.page_token][google.cloud.kms.v1.ListImportJobsRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of - [ImportJobs][google.cloud.kms.v1.ImportJob] that matched the - query. - """ - - @property - def raw_page(self): - return self - - import_jobs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.ImportJob, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - total_size = proto.Field( - proto.INT32, - number=3, - ) - - -class GetKeyRingRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] of - the [KeyRing][google.cloud.kms.v1.KeyRing] to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetCryptoKeyRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] of - the [CryptoKey][google.cloud.kms.v1.CryptoKey] to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. - - Attributes: - name (str): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetPublicKeyRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Attributes: - name (str): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetImportJobRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.ImportJob.name] of - the [ImportJob][google.cloud.kms.v1.ImportJob] to get. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateKeyRingRequest(proto.Message): - r"""Request message for - [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. - - Attributes: - parent (str): - Required. The resource name of the location associated with - the [KeyRings][google.cloud.kms.v1.KeyRing], in the format - ``projects/*/locations/*``. - key_ring_id (str): - Required. It must be unique within a location and match the - regular expression ``[a-zA-Z0-9_-]{1,63}`` - key_ring (google.cloud.kms_v1.types.KeyRing): - Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with - initial field values. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - key_ring_id = proto.Field( - proto.STRING, - number=2, - ) - key_ring = proto.Field( - proto.MESSAGE, - number=3, - message=resources.KeyRing, - ) - - -class CreateCryptoKeyRequest(proto.Message): - r"""Request message for - [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. - - Attributes: - parent (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] of - the KeyRing associated with the - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - crypto_key_id (str): - Required. It must be unique within a KeyRing and match the - regular expression ``[a-zA-Z0-9_-]{1,63}`` - crypto_key (google.cloud.kms_v1.types.CryptoKey): - Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with - initial field values. - skip_initial_version_creation (bool): - If set to true, the request will create a - [CryptoKey][google.cloud.kms.v1.CryptoKey] without any - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - You must manually call - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - or - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion] - before you can use this - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - crypto_key_id = proto.Field( - proto.STRING, - number=2, - ) - crypto_key = proto.Field( - proto.MESSAGE, - number=3, - message=resources.CryptoKey, - ) - skip_initial_version_creation = proto.Field( - proto.BOOL, - number=5, - ) - - -class CreateCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. - - Attributes: - parent (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] of - the [CryptoKey][google.cloud.kms.v1.CryptoKey] associated - with the - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): - Required. A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with initial field values. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - crypto_key_version = proto.Field( - proto.MESSAGE, - number=2, - message=resources.CryptoKeyVersion, - ) - - -class ImportCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] of - the [CryptoKey][google.cloud.kms.v1.CryptoKey] to be - imported into. - - The create permission is only required on this key when - creating a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - crypto_key_version (str): - Optional. The optional - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of an - existing - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - target for an import operation. If this field is not - present, a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - containing the supplied key material is created. - - If this field is present, the supplied key material is - imported into the existing - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. To - import into an existing - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], - the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - must be a child of - [ImportCryptoKeyVersionRequest.parent][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.parent], - have been previously created via [ImportCryptoKeyVersion][], - and be in - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED] - or - [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED] - state. The key material and algorithm must match the - previous - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - exactly if the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] has - ever contained key material. - algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): - Required. The - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] - of the key being imported. This does not need to match the - [version_template][google.cloud.kms.v1.CryptoKey.version_template] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] this - version imports into. - import_job (str): - Required. The [name][google.cloud.kms.v1.ImportJob.name] of - the [ImportJob][google.cloud.kms.v1.ImportJob] that was used - to wrap this key material. - rsa_aes_wrapped_key (bytes): - Wrapped key material produced with - [RSA_OAEP_3072_SHA1_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256] - or - [RSA_OAEP_4096_SHA1_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA1_AES_256]. - - This field contains the concatenation of two wrapped keys: - - .. raw:: html - -
    -
  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. -
  2. -
  3. The key to be imported, wrapped with the ephemeral AES-256 key - using AES-KWP (RFC 5649). -
  4. -
- - If importing symmetric key material, it is expected that the - unwrapped key contains plain bytes. If importing asymmetric - key material, it is expected that the unwrapped key is in - PKCS#8-encoded DER format (the PrivateKeyInfo structure from - RFC 5208). - - 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``. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - crypto_key_version = proto.Field( - proto.STRING, - number=6, - ) - algorithm = proto.Field( - proto.ENUM, - number=2, - enum=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm, - ) - import_job = proto.Field( - proto.STRING, - number=4, - ) - rsa_aes_wrapped_key = proto.Field( - proto.BYTES, - number=5, - oneof='wrapped_key_material', - ) - - -class CreateImportJobRequest(proto.Message): - r"""Request message for - [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. - - Attributes: - parent (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] of - the [KeyRing][google.cloud.kms.v1.KeyRing] associated with - the [ImportJobs][google.cloud.kms.v1.ImportJob]. - import_job_id (str): - Required. It must be unique within a KeyRing and match the - regular expression ``[a-zA-Z0-9_-]{1,63}`` - import_job (google.cloud.kms_v1.types.ImportJob): - Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with - initial field values. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - import_job_id = proto.Field( - proto.STRING, - number=2, - ) - import_job = proto.Field( - proto.MESSAGE, - number=3, - message=resources.ImportJob, - ) - - -class UpdateCryptoKeyRequest(proto.Message): - r"""Request message for - [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - - Attributes: - crypto_key (google.cloud.kms_v1.types.CryptoKey): - Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] with - updated values. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - crypto_key = proto.Field( - proto.MESSAGE, - number=1, - message=resources.CryptoKey, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - - Attributes: - crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): - Required. - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with updated values. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - crypto_key_version = proto.Field( - proto.MESSAGE, - number=1, - message=resources.CryptoKeyVersion, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateCryptoKeyPrimaryVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. - crypto_key_version_id (str): - Required. The id of the child - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use as primary. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - crypto_key_version_id = proto.Field( - proto.STRING, - number=2, - ) - - -class DestroyCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - destroy. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class RestoreCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - restore. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class EncryptRequest(proto.Message): - r"""Request message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] or - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for encryption. - - If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is - specified, the server will use its [primary - version][google.cloud.kms.v1.CryptoKey.primary]. - plaintext (bytes): - Required. The data to encrypt. Must be no larger than 64KiB. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] - keys, the plaintext must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger than - 8KiB. - additional_authenticated_data (bytes): - Optional. Optional data that, if specified, must also be - provided during decryption through - [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] - keys, the AAD must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger than - 8KiB. - plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]) - is equal to - [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]) - is equal to - [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - plaintext = proto.Field( - proto.BYTES, - number=2, - ) - additional_authenticated_data = proto.Field( - proto.BYTES, - number=3, - ) - plaintext_crc32c = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.Int64Value, - ) - additional_authenticated_data_crc32c = proto.Field( - proto.MESSAGE, - number=8, - message=wrappers_pb2.Int64Value, - ) - - -class DecryptRequest(proto.Message): - r"""Request message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for - decryption. The server will choose the appropriate version. - ciphertext (bytes): - Required. The encrypted data originally returned in - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. - additional_authenticated_data (bytes): - Optional. Optional data that must match the data originally - supplied in - [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. - ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]) - is equal to - [DecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.DecryptRequest.ciphertext_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]) - is equal to - [DecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - ciphertext = proto.Field( - proto.BYTES, - number=2, - ) - additional_authenticated_data = proto.Field( - proto.BYTES, - number=3, - ) - ciphertext_crc32c = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int64Value, - ) - additional_authenticated_data_crc32c = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int64Value, - ) - - -class AsymmetricSignRequest(proto.Message): - r"""Request message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for signing. - digest (google.cloud.kms_v1.types.Digest): - Optional. The digest of the data to sign. The digest must be - produced with the same digest algorithm as specified by the - key version's - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. - digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]) - is equal to - [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - 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. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]) - is equal to - [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - digest = proto.Field( - proto.MESSAGE, - number=3, - message='Digest', - ) - digest_crc32c = proto.Field( - proto.MESSAGE, - number=4, - message=wrappers_pb2.Int64Value, - ) - data = proto.Field( - proto.BYTES, - number=6, - ) - data_crc32c = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.Int64Value, - ) - - -class AsymmetricDecryptRequest(proto.Message): - r"""Request message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for decryption. - ciphertext (bytes): - Required. The data encrypted with the named - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - public key using OAEP. - ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]) - is equal to - [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - ciphertext = proto.Field( - proto.BYTES, - number=3, - ) - ciphertext_crc32c = proto.Field( - proto.MESSAGE, - number=4, - message=wrappers_pb2.Int64Value, - ) - - -class MacSignRequest(proto.Message): - r"""Request message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for signing. - data (bytes): - Required. The data to sign. The MAC tag is - computed over this data field based on the - specific algorithm. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data]) - is equal to - [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - data = proto.Field( - proto.BYTES, - number=2, - ) - data_crc32c = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - - -class MacVerifyRequest(proto.Message): - r"""Request message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for verification. - data (bytes): - Required. The data used previously as a - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] - to generate the MAC tag. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data]) - is equal to - [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - mac (bytes): - Required. The signature to verify. - mac_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([MacVerifyRequest.tag][]) is equal to - [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - data = proto.Field( - proto.BYTES, - number=2, - ) - data_crc32c = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - mac = proto.Field( - proto.BYTES, - number=4, - ) - mac_crc32c = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int64Value, - ) - - -class GenerateRandomBytesRequest(proto.Message): - r"""Request message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - Attributes: - location (str): - The project-specific location in which to - generate random bytes. For example, - "projects/my-project/locations/us-central1". - length_bytes (int): - The length in bytes of the amount of - randomness to retrieve. Minimum 8 bytes, - 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]. - """ - - location = proto.Field( - proto.STRING, - number=1, - ) - length_bytes = proto.Field( - proto.INT32, - number=2, - ) - protection_level = proto.Field( - proto.ENUM, - number=3, - enum=resources.ProtectionLevel, - ) - - -class EncryptResponse(proto.Message): - r"""Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Attributes: - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in encryption. Check this field to verify that the - intended resource was used for encryption. - ciphertext (bytes): - The encrypted data. - ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. - An integrity check of - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext] - can be performed by computing the CRC32C checksum of - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_plaintext_crc32c (bool): - Integrity verification field. A flag indicating whether - [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. A - false value of this field indicates either that - [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_additional_authenticated_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [AAD][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. - A false value of this field indicates either that - [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in encryption. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - ciphertext = proto.Field( - proto.BYTES, - number=2, - ) - ciphertext_crc32c = proto.Field( - proto.MESSAGE, - number=4, - message=wrappers_pb2.Int64Value, - ) - verified_plaintext_crc32c = proto.Field( - proto.BOOL, - number=5, - ) - verified_additional_authenticated_data_crc32c = proto.Field( - proto.BOOL, - number=6, - ) - protection_level = proto.Field( - proto.ENUM, - number=7, - enum=resources.ProtectionLevel, - ) - - -class DecryptResponse(proto.Message): - r"""Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - Attributes: - plaintext (bytes): - The decrypted data originally supplied in - [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. - plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext]. - An integrity check of - [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext] - can be performed by computing the CRC32C checksum of - [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: receiving this response message indicates - that - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - is able to successfully decrypt the - [ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. - Note: This field is defined as int64 for reasons of - compatibility across different languages. However, it is a - non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - used_primary (bool): - Whether the Decryption was performed using - the primary key version. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in decryption. - """ - - plaintext = proto.Field( - proto.BYTES, - number=1, - ) - plaintext_crc32c = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int64Value, - ) - used_primary = proto.Field( - proto.BOOL, - number=3, - ) - protection_level = proto.Field( - proto.ENUM, - number=4, - enum=resources.ProtectionLevel, - ) - - -class AsymmetricSignResponse(proto.Message): - r"""Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - Attributes: - signature (bytes): - The created signature. - signature_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature]. - An integrity check of - [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature] - can be performed by computing the CRC32C checksum of - [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_digest_crc32c (bool): - Integrity verification field. A flag indicating whether - [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. - A false value of this field indicates either that - [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for signing. Check this field to verify that the - intended resource was used for signing. - verified_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [data][google.cloud.kms.v1.AsymmetricSignRequest.data]. A - false value of this field indicates either that - [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for signing. - """ - - signature = proto.Field( - proto.BYTES, - number=1, - ) - signature_crc32c = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int64Value, - ) - verified_digest_crc32c = proto.Field( - proto.BOOL, - number=3, - ) - name = proto.Field( - proto.STRING, - number=4, - ) - verified_data_crc32c = proto.Field( - proto.BOOL, - number=5, - ) - protection_level = proto.Field( - proto.ENUM, - number=6, - enum=resources.ProtectionLevel, - ) - - -class AsymmetricDecryptResponse(proto.Message): - r"""Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - Attributes: - plaintext (bytes): - The decrypted data originally encrypted with - the matching public key. - plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext]. - An integrity check of - [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext] - can be performed by computing the CRC32C checksum of - [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_ciphertext_crc32c (bool): - Integrity verification field. A flag indicating whether - [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. - A false value of this field indicates either that - [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in decryption. - """ - - plaintext = proto.Field( - proto.BYTES, - number=1, - ) - plaintext_crc32c = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int64Value, - ) - verified_ciphertext_crc32c = proto.Field( - proto.BOOL, - number=3, - ) - protection_level = proto.Field( - proto.ENUM, - number=4, - enum=resources.ProtectionLevel, - ) - - -class MacSignResponse(proto.Message): - r"""Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - Attributes: - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for signing. Check this field to verify that the - intended resource was used for signing. - mac (bytes): - The created signature. - mac_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac]. - An integrity check of - [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac] - can be performed by computing the CRC32C checksum of - [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [data][google.cloud.kms.v1.MacSignRequest.data]. A false - value of this field indicates either that - [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for signing. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - mac = proto.Field( - proto.BYTES, - number=2, - ) - mac_crc32c = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - verified_data_crc32c = proto.Field( - proto.BOOL, - number=4, - ) - protection_level = proto.Field( - proto.ENUM, - number=5, - enum=resources.ProtectionLevel, - ) - - -class MacVerifyResponse(proto.Message): - r"""Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - Attributes: - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for verification. Check this field to verify that the - intended resource was used for verification. - success (bool): - This field indicates whether or not the verification - operation for - [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac] - over - [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data] - was successful. - verified_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [data][google.cloud.kms.v1.MacVerifyRequest.data]. A false - value of this field indicates either that - [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_mac_crc32c (bool): - Integrity verification field. A flag indicating whether - [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [data][google.cloud.kms.v1.MacVerifyRequest.mac]. A false - value of this field indicates either that - [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_success_integrity (bool): - Integrity verification field. This value is used for the - integrity verification of [MacVerifyResponse.success]. If - the value of this field contradicts the value of - [MacVerifyResponse.success], discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for verification. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - success = proto.Field( - proto.BOOL, - number=2, - ) - verified_data_crc32c = proto.Field( - proto.BOOL, - number=3, - ) - verified_mac_crc32c = proto.Field( - proto.BOOL, - number=4, - ) - verified_success_integrity = proto.Field( - proto.BOOL, - number=5, - ) - protection_level = proto.Field( - proto.ENUM, - number=6, - enum=resources.ProtectionLevel, - ) - - -class GenerateRandomBytesResponse(proto.Message): - r"""Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - Attributes: - data (bytes): - The generated data. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data]. - An integrity check of - [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data] - can be performed by computing the CRC32C checksum of - [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - """ - - data = proto.Field( - proto.BYTES, - number=1, - ) - data_crc32c = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - - -class Digest(proto.Message): - r"""A [Digest][google.cloud.kms.v1.Digest] holds a cryptographic message - digest. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - 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``. - """ - - sha256 = proto.Field( - proto.BYTES, - number=1, - oneof='digest', - ) - sha384 = proto.Field( - proto.BYTES, - number=2, - oneof='digest', - ) - sha512 = proto.Field( - proto.BYTES, - number=3, - oneof='digest', - ) - - -class LocationMetadata(proto.Message): - r"""Cloud KMS metadata for the given - [google.cloud.location.Location][google.cloud.location.Location]. - - Attributes: - hsm_available (bool): - Indicates whether - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] can be - created in this location. - ekm_available (bool): - Indicates whether - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] can - be created in this location. - """ - - hsm_available = proto.Field( - proto.BOOL, - number=1, - ) - ekm_available = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 8fe3ebab..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- 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 pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9', '3.10']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/kms_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.9') -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python='3.9') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py deleted file mode 100644 index 1c0a208b..00000000 --- a/owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py +++ /dev/null @@ -1,204 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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 argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class kmsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'asymmetric_decrypt': ('name', 'ciphertext', 'ciphertext_crc32c', ), - '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_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', ), - 'destroy_crypto_key_version': ('name', ), - 'encrypt': ('name', 'plaintext', 'additional_authenticated_data', 'plaintext_crc32c', 'additional_authenticated_data_crc32c', ), - 'generate_random_bytes': ('location', 'length_bytes', 'protection_level', ), - 'get_crypto_key': ('name', ), - 'get_crypto_key_version': ('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_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', ), - 'mac_verify': ('name', 'data', 'mac', 'data_crc32c', 'mac_crc32c', ), - 'restore_crypto_key_version': ('name', ), - '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', ), - 'get_iam_policy': ('resource', 'options', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=kmsCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the kms client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index f6eb8321..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- 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 io -import os -import setuptools # type: ignore - -version = '0.1.0' - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, 'README.rst') -with io.open(readme_filename, encoding='utf-8') as readme_file: - readme = readme_file.read() - -setuptools.setup( - name='google-cloud-kms', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.28.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.19.7', - 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', - ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py deleted file mode 100644 index b9e0378a..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py +++ /dev/null @@ -1,8912 +0,0 @@ -# -*- 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.key_management_service import KeyManagementServiceAsyncClient -from google.cloud.kms_v1.services.key_management_service import KeyManagementServiceClient -from google.cloud.kms_v1.services.key_management_service import pagers -from google.cloud.kms_v1.services.key_management_service import transports -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import 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 duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_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 KeyManagementServiceClient._get_default_mtls_endpoint(None) is None - assert KeyManagementServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert KeyManagementServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert KeyManagementServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert KeyManagementServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert KeyManagementServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - KeyManagementServiceClient, - KeyManagementServiceAsyncClient, -]) -def test_key_management_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.KeyManagementServiceGrpcTransport, "grpc"), - (transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_key_management_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", [ - KeyManagementServiceClient, - KeyManagementServiceAsyncClient, -]) -def test_key_management_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_key_management_service_client_get_transport_class(): - transport = KeyManagementServiceClient.get_transport_class() - available_transports = [ - transports.KeyManagementServiceGrpcTransport, - ] - assert transport in available_transports - - transport = KeyManagementServiceClient.get_transport_class("grpc") - assert transport == transports.KeyManagementServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@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_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(KeyManagementServiceClient, '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(KeyManagementServiceClient, '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", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", "true"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", "false"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(KeyManagementServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KeyManagementServiceClient)) -@mock.patch.object(KeyManagementServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KeyManagementServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_key_management_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", [ - 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", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_key_management_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", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_key_management_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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_key_management_service_client_client_options_from_dict(): - with mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = KeyManagementServiceClient( - 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("request_type", [ - service.ListKeyRingsRequest, - dict, -]) -def test_list_key_rings(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - 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_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListKeyRingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListKeyRingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeyRingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -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. - client = KeyManagementServiceClient( - 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_key_rings), - '__call__') as call: - client.list_key_rings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListKeyRingsRequest() - - -@pytest.mark.asyncio -async def test_list_key_rings_async(transport: str = 'grpc_asyncio', request_type=service.ListKeyRingsRequest): - client = KeyManagementServiceAsyncClient( - 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_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListKeyRingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeyRingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_key_rings_async_from_dict(): - await test_list_key_rings_async(request_type=dict) - - -def test_list_key_rings_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListKeyRingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - call.return_value = service.ListKeyRingsResponse() - client.list_key_rings(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_key_rings_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListKeyRingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse()) - await client.list_key_rings(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_key_rings_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListKeyRingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_key_rings( - 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_key_rings_flattened_error(): - client = KeyManagementServiceClient( - 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_key_rings( - service.ListKeyRingsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_key_rings_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListKeyRingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_key_rings( - 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_key_rings_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_key_rings( - service.ListKeyRingsRequest(), - parent='parent_value', - ) - - -def test_list_key_rings_pager(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_key_rings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_key_rings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, resources.KeyRing) - for i in results) -def test_list_key_rings_pages(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_key_rings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - RuntimeError, - ) - pages = list(client.list_key_rings(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_key_rings_async_pager(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_key_rings(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, resources.KeyRing) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_key_rings_async_pages(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_key_rings(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", [ - service.ListCryptoKeysRequest, - dict, -]) -def test_list_crypto_keys(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - 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_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeysResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCryptoKeysRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeysPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -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. - client = KeyManagementServiceClient( - 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_crypto_keys), - '__call__') as call: - client.list_crypto_keys() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCryptoKeysRequest() - - -@pytest.mark.asyncio -async def test_list_crypto_keys_async(transport: str = 'grpc_asyncio', request_type=service.ListCryptoKeysRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCryptoKeysRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeysAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_crypto_keys_async_from_dict(): - await test_list_crypto_keys_async(request_type=dict) - - -def test_list_crypto_keys_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListCryptoKeysRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - call.return_value = service.ListCryptoKeysResponse() - client.list_crypto_keys(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_crypto_keys_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListCryptoKeysRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse()) - await client.list_crypto_keys(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_crypto_keys_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeysResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_crypto_keys( - 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_crypto_keys_flattened_error(): - client = KeyManagementServiceClient( - 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_crypto_keys( - service.ListCryptoKeysRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_crypto_keys_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeysResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_crypto_keys( - 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_crypto_keys_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_keys( - service.ListCryptoKeysRequest(), - parent='parent_value', - ) - - -def test_list_crypto_keys_pager(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_crypto_keys), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crypto_keys(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, resources.CryptoKey) - for i in results) -def test_list_crypto_keys_pages(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_crypto_keys), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crypto_keys(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_crypto_keys_async_pager(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crypto_keys(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, resources.CryptoKey) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_crypto_keys_async_pages(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_crypto_keys(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", [ - service.ListCryptoKeyVersionsRequest, - dict, -]) -def test_list_crypto_key_versions(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - 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_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeyVersionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_crypto_key_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCryptoKeyVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeyVersionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -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. - client = KeyManagementServiceClient( - 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_crypto_key_versions), - '__call__') as call: - client.list_crypto_key_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCryptoKeyVersionsRequest() - - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_async(transport: str = 'grpc_asyncio', request_type=service.ListCryptoKeyVersionsRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_crypto_key_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCryptoKeyVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeyVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_async_from_dict(): - await test_list_crypto_key_versions_async(request_type=dict) - - -def test_list_crypto_key_versions_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListCryptoKeyVersionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - call.return_value = service.ListCryptoKeyVersionsResponse() - client.list_crypto_key_versions(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_crypto_key_versions_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListCryptoKeyVersionsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse()) - await client.list_crypto_key_versions(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_crypto_key_versions_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeyVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_crypto_key_versions( - 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_crypto_key_versions_flattened_error(): - client = KeyManagementServiceClient( - 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_crypto_key_versions( - service.ListCryptoKeyVersionsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeyVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_crypto_key_versions( - 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_crypto_key_versions_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_versions( - service.ListCryptoKeyVersionsRequest(), - parent='parent_value', - ) - - -def test_list_crypto_key_versions_pager(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_crypto_key_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crypto_key_versions(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, resources.CryptoKeyVersion) - for i in results) -def test_list_crypto_key_versions_pages(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_crypto_key_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crypto_key_versions(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_crypto_key_versions_async_pager(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crypto_key_versions(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, resources.CryptoKeyVersion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_async_pages(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_crypto_key_versions(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", [ - service.ListImportJobsRequest, - dict, -]) -def test_list_import_jobs(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - 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_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListImportJobsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListImportJobsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImportJobsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -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. - client = KeyManagementServiceClient( - 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_import_jobs), - '__call__') as call: - client.list_import_jobs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListImportJobsRequest() - - -@pytest.mark.asyncio -async def test_list_import_jobs_async(transport: str = 'grpc_asyncio', request_type=service.ListImportJobsRequest): - client = KeyManagementServiceAsyncClient( - 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_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListImportJobsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImportJobsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_import_jobs_async_from_dict(): - await test_list_import_jobs_async(request_type=dict) - - -def test_list_import_jobs_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListImportJobsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - call.return_value = service.ListImportJobsResponse() - client.list_import_jobs(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_import_jobs_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListImportJobsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse()) - await client.list_import_jobs(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_import_jobs_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListImportJobsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_import_jobs( - 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_import_jobs_flattened_error(): - client = KeyManagementServiceClient( - 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_import_jobs( - service.ListImportJobsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_import_jobs_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListImportJobsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_import_jobs( - 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_import_jobs_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_import_jobs( - service.ListImportJobsRequest(), - parent='parent_value', - ) - - -def test_list_import_jobs_pager(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_import_jobs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_import_jobs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, resources.ImportJob) - for i in results) -def test_list_import_jobs_pages(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_import_jobs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - RuntimeError, - ) - pages = list(client.list_import_jobs(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_import_jobs_async_pager(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_import_jobs(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, resources.ImportJob) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_import_jobs_async_pages(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_import_jobs(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", [ - service.GetKeyRingRequest, - dict, -]) -def test_get_key_ring(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - 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_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing( - name='name_value', - ) - response = client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetKeyRingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -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. - client = KeyManagementServiceClient( - 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_key_ring), - '__call__') as call: - client.get_key_ring() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetKeyRingRequest() - - -@pytest.mark.asyncio -async def test_get_key_ring_async(transport: str = 'grpc_asyncio', request_type=service.GetKeyRingRequest): - client = KeyManagementServiceAsyncClient( - 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_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( - name='name_value', - )) - response = await client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetKeyRingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_key_ring_async_from_dict(): - await test_get_key_ring_async(request_type=dict) - - -def test_get_key_ring_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetKeyRingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - call.return_value = resources.KeyRing() - client.get_key_ring(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_key_ring_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetKeyRingRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) - await client.get_key_ring(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_key_ring_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_key_ring( - 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_key_ring_flattened_error(): - client = KeyManagementServiceClient( - 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_key_ring( - service.GetKeyRingRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_key_ring_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_key_ring( - 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_key_ring_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_key_ring( - service.GetKeyRingRequest(), - name='name_value', - ) - - -@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, - ) - - # 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - rotation_period=duration_pb2.Duration(seconds=751), - ) - response = client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCryptoKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - - -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. - client = KeyManagementServiceClient( - 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_crypto_key), - '__call__') as call: - client.get_crypto_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCryptoKeyRequest() - - -@pytest.mark.asyncio -async def test_get_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.GetCryptoKeyRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - )) - response = await client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCryptoKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - - -@pytest.mark.asyncio -async def test_get_crypto_key_async_from_dict(): - await test_get_crypto_key_async(request_type=dict) - - -def test_get_crypto_key_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetCryptoKeyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.get_crypto_key(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_crypto_key_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetCryptoKeyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.get_crypto_key(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_crypto_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_crypto_key( - 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_crypto_key_flattened_error(): - client = KeyManagementServiceClient( - 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_crypto_key( - service.GetCryptoKeyRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_crypto_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_crypto_key( - 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_crypto_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_key( - service.GetCryptoKeyRequest(), - name='name_value', - ) - - -@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, - ) - - # 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - ) - response = client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -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. - client = KeyManagementServiceClient( - 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_crypto_key_version), - '__call__') as call: - client.get_crypto_key_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCryptoKeyVersionRequest() - - -@pytest.mark.asyncio -async def test_get_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.GetCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - )) - response = await client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_get_crypto_key_version_async_from_dict(): - await test_get_crypto_key_version_async(request_type=dict) - - -def test_get_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetCryptoKeyVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.get_crypto_key_version(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_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetCryptoKeyVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.get_crypto_key_version(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_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_crypto_key_version( - 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_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - 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_crypto_key_version( - service.GetCryptoKeyVersionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_crypto_key_version( - 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_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_version( - service.GetCryptoKeyVersionRequest(), - name='name_value', - ) - - -@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, - ) - - # 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_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.PublicKey( - pem='pem_value', - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetPublicKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.PublicKey) - assert response.pem == 'pem_value' - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.name == 'name_value' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -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. - client = KeyManagementServiceClient( - 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_public_key), - '__call__') as call: - client.get_public_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetPublicKeyRequest() - - -@pytest.mark.asyncio -async def test_get_public_key_async(transport: str = 'grpc_asyncio', request_type=service.GetPublicKeyRequest): - client = KeyManagementServiceAsyncClient( - 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_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey( - pem='pem_value', - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetPublicKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.PublicKey) - assert response.pem == 'pem_value' - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.name == 'name_value' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_get_public_key_async_from_dict(): - await test_get_public_key_async(request_type=dict) - - -def test_get_public_key_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetPublicKeyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - call.return_value = resources.PublicKey() - client.get_public_key(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_public_key_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetPublicKeyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) - await client.get_public_key(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_public_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.PublicKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_public_key( - 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_public_key_flattened_error(): - client = KeyManagementServiceClient( - 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_public_key( - service.GetPublicKeyRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_public_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.PublicKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_public_key( - 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_public_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_public_key( - service.GetPublicKeyRequest(), - name='name_value', - ) - - -@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, - ) - - # 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_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - ) - response = client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetImportJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -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. - client = KeyManagementServiceClient( - 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_import_job), - '__call__') as call: - client.get_import_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetImportJobRequest() - - -@pytest.mark.asyncio -async def test_get_import_job_async(transport: str = 'grpc_asyncio', request_type=service.GetImportJobRequest): - client = KeyManagementServiceAsyncClient( - 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_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - )) - response = await client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetImportJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -@pytest.mark.asyncio -async def test_get_import_job_async_from_dict(): - await test_get_import_job_async(request_type=dict) - - -def test_get_import_job_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetImportJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - call.return_value = resources.ImportJob() - client.get_import_job(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_import_job_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetImportJobRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - await client.get_import_job(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_import_job_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_import_job( - 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_import_job_flattened_error(): - client = KeyManagementServiceClient( - 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_import_job( - service.GetImportJobRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_import_job_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_import_job( - 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_import_job_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_import_job( - service.GetImportJobRequest(), - name='name_value', - ) - - -@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, - ) - - # 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_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing( - name='name_value', - ) - response = client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateKeyRingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -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. - client = KeyManagementServiceClient( - 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_key_ring), - '__call__') as call: - client.create_key_ring() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateKeyRingRequest() - - -@pytest.mark.asyncio -async def test_create_key_ring_async(transport: str = 'grpc_asyncio', request_type=service.CreateKeyRingRequest): - client = KeyManagementServiceAsyncClient( - 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_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( - name='name_value', - )) - response = await client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateKeyRingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_key_ring_async_from_dict(): - await test_create_key_ring_async(request_type=dict) - - -def test_create_key_ring_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateKeyRingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - call.return_value = resources.KeyRing() - client.create_key_ring(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_key_ring_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateKeyRingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) - await client.create_key_ring(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_key_ring_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_key_ring( - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(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].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(): - client = KeyManagementServiceClient( - 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_key_ring( - service.CreateKeyRingRequest(), - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_key_ring_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_key_ring( - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(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].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 -async def test_create_key_ring_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_key_ring( - service.CreateKeyRingRequest(), - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(name='name_value'), - ) - - -@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, - ) - - # 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - rotation_period=duration_pb2.Duration(seconds=751), - ) - response = client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCryptoKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - - -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. - client = KeyManagementServiceClient( - 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_crypto_key), - '__call__') as call: - client.create_crypto_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCryptoKeyRequest() - - -@pytest.mark.asyncio -async def test_create_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.CreateCryptoKeyRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - )) - response = await client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCryptoKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - - -@pytest.mark.asyncio -async def test_create_crypto_key_async_from_dict(): - await test_create_crypto_key_async(request_type=dict) - - -def test_create_crypto_key_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateCryptoKeyRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.create_crypto_key(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_crypto_key_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateCryptoKeyRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.create_crypto_key(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_crypto_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_crypto_key( - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(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].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(): - client = KeyManagementServiceClient( - 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_crypto_key( - service.CreateCryptoKeyRequest(), - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_crypto_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_crypto_key( - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(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].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 -async def test_create_crypto_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_key( - service.CreateCryptoKeyRequest(), - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(name='name_value'), - ) - - -@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, - ) - - # 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - ) - response = client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -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. - client = KeyManagementServiceClient( - 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_crypto_key_version), - '__call__') as call: - client.create_crypto_key_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCryptoKeyVersionRequest() - - -@pytest.mark.asyncio -async def test_create_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.CreateCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - )) - response = await client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_create_crypto_key_version_async_from_dict(): - await test_create_crypto_key_version_async(request_type=dict) - - -def test_create_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateCryptoKeyVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.create_crypto_key_version(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_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateCryptoKeyVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.create_crypto_key_version(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_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_crypto_key_version( - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version - mock_val = resources.CryptoKeyVersion(name='name_value') - assert arg == mock_val - - -def test_create_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - 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_crypto_key_version( - service.CreateCryptoKeyVersionRequest(), - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_crypto_key_version( - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version - mock_val = resources.CryptoKeyVersion(name='name_value') - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_create_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_version( - service.CreateCryptoKeyVersionRequest(), - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - ) - - -@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, - ) - - # 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.import_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - ) - response = client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.ImportCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -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. - client = KeyManagementServiceClient( - 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.import_crypto_key_version), - '__call__') as call: - client.import_crypto_key_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ImportCryptoKeyVersionRequest() - - -@pytest.mark.asyncio -async def test_import_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.ImportCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - 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.import_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - )) - response = await client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.ImportCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_import_crypto_key_version_async_from_dict(): - await test_import_crypto_key_version_async(request_type=dict) - - -def test_import_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ImportCryptoKeyVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.import_crypto_key_version(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_import_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ImportCryptoKeyVersionRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.import_crypto_key_version(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'] - - -@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, - ) - - # 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_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - ) - response = client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateImportJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -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. - client = KeyManagementServiceClient( - 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_import_job), - '__call__') as call: - client.create_import_job() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateImportJobRequest() - - -@pytest.mark.asyncio -async def test_create_import_job_async(transport: str = 'grpc_asyncio', request_type=service.CreateImportJobRequest): - client = KeyManagementServiceAsyncClient( - 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_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - )) - response = await client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateImportJobRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -@pytest.mark.asyncio -async def test_create_import_job_async_from_dict(): - await test_create_import_job_async(request_type=dict) - - -def test_create_import_job_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateImportJobRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - call.return_value = resources.ImportJob() - client.create_import_job(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_import_job_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateImportJobRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - await client.create_import_job(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_import_job_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_import_job( - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(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].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(): - client = KeyManagementServiceClient( - 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_import_job( - service.CreateImportJobRequest(), - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_import_job_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_import_job( - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(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].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 -async def test_create_import_job_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_import_job( - service.CreateImportJobRequest(), - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(name='name_value'), - ) - - -@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, - ) - - # 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - rotation_period=duration_pb2.Duration(seconds=751), - ) - response = client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - - -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. - client = KeyManagementServiceClient( - 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_crypto_key), - '__call__') as call: - client.update_crypto_key() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyRequest() - - -@pytest.mark.asyncio -async def test_update_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - )) - response = await client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - - -@pytest.mark.asyncio -async def test_update_crypto_key_async_from_dict(): - await test_update_crypto_key_async(request_type=dict) - - -def test_update_crypto_key_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyRequest() - - request.crypto_key.name = 'crypto_key.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.update_crypto_key(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', - 'crypto_key.name=crypto_key.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_crypto_key_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyRequest() - - request.crypto_key.name = 'crypto_key.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.update_crypto_key(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', - 'crypto_key.name=crypto_key.name/value', - ) in kw['metadata'] - - -def test_update_crypto_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_crypto_key( - crypto_key=resources.CryptoKey(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].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(): - client = KeyManagementServiceClient( - 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_crypto_key( - service.UpdateCryptoKeyRequest(), - crypto_key=resources.CryptoKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_crypto_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_crypto_key( - crypto_key=resources.CryptoKey(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].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 -async def test_update_crypto_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_key( - service.UpdateCryptoKeyRequest(), - crypto_key=resources.CryptoKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@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, - ) - - # 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - ) - response = client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -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. - client = KeyManagementServiceClient( - 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_crypto_key_version), - '__call__') as call: - client.update_crypto_key_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyVersionRequest() - - -@pytest.mark.asyncio -async def test_update_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - )) - response = await client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_update_crypto_key_version_async_from_dict(): - await test_update_crypto_key_version_async(request_type=dict) - - -def test_update_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyVersionRequest() - - request.crypto_key_version.name = 'crypto_key_version.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.update_crypto_key_version(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', - 'crypto_key_version.name=crypto_key_version.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyVersionRequest() - - request.crypto_key_version.name = 'crypto_key_version.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.update_crypto_key_version(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', - 'crypto_key_version.name=crypto_key_version.name/value', - ) in kw['metadata'] - - -def test_update_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_crypto_key_version( - crypto_key_version=resources.CryptoKeyVersion(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].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(): - client = KeyManagementServiceClient( - 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_crypto_key_version( - service.UpdateCryptoKeyVersionRequest(), - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_crypto_key_version( - crypto_key_version=resources.CryptoKeyVersion(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].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 -async def test_update_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_version( - service.UpdateCryptoKeyVersionRequest(), - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@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, - ) - - # 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_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - rotation_period=duration_pb2.Duration(seconds=751), - ) - response = client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - - -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. - client = KeyManagementServiceClient( - 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_crypto_key_primary_version), - '__call__') as call: - client.update_crypto_key_primary_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() - - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyPrimaryVersionRequest): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - )) - response = await client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_async_from_dict(): - await test_update_crypto_key_primary_version_async(request_type=dict) - - -def test_update_crypto_key_primary_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyPrimaryVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.update_crypto_key_primary_version(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_update_crypto_key_primary_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyPrimaryVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.update_crypto_key_primary_version(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_update_crypto_key_primary_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_crypto_key_primary_version( - name='name_value', - crypto_key_version_id='crypto_key_version_id_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 - 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(): - client = KeyManagementServiceClient( - 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_crypto_key_primary_version( - service.UpdateCryptoKeyPrimaryVersionRequest(), - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_crypto_key_primary_version( - name='name_value', - crypto_key_version_id='crypto_key_version_id_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 - arg = args[0].crypto_key_version_id - mock_val = 'crypto_key_version_id_value' - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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_crypto_key_primary_version( - service.UpdateCryptoKeyPrimaryVersionRequest(), - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - - -@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, - ) - - # 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.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - ) - response = client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.DestroyCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -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. - client = KeyManagementServiceClient( - 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.destroy_crypto_key_version), - '__call__') as call: - client.destroy_crypto_key_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DestroyCryptoKeyVersionRequest() - - -@pytest.mark.asyncio -async def test_destroy_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.DestroyCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - 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.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - )) - response = await client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.DestroyCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_destroy_crypto_key_version_async_from_dict(): - await test_destroy_crypto_key_version_async(request_type=dict) - - -def test_destroy_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DestroyCryptoKeyVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.destroy_crypto_key_version(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_destroy_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DestroyCryptoKeyVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.destroy_crypto_key_version(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_destroy_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.destroy_crypto_key_version( - 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_destroy_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - 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.destroy_crypto_key_version( - service.DestroyCryptoKeyVersionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_destroy_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.destroy_crypto_key_version( - 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_destroy_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.destroy_crypto_key_version( - service.DestroyCryptoKeyVersionRequest(), - name='name_value', - ) - - -@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, - ) - - # 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.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - ) - response = client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.RestoreCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -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. - client = KeyManagementServiceClient( - 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.restore_crypto_key_version), - '__call__') as call: - client.restore_crypto_key_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RestoreCryptoKeyVersionRequest() - - -@pytest.mark.asyncio -async def test_restore_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.RestoreCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - 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.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - reimport_eligible=True, - )) - response = await client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.RestoreCryptoKeyVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_restore_crypto_key_version_async_from_dict(): - await test_restore_crypto_key_version_async(request_type=dict) - - -def test_restore_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.RestoreCryptoKeyVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.restore_crypto_key_version(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_restore_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.RestoreCryptoKeyVersionRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.restore_crypto_key_version(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_restore_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.restore_crypto_key_version( - 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_restore_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - 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.restore_crypto_key_version( - service.RestoreCryptoKeyVersionRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_restore_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.restore_crypto_key_version( - 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_restore_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.restore_crypto_key_version( - service.RestoreCryptoKeyVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.EncryptRequest, - dict, -]) -def test_encrypt(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - 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.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse( - name='name_value', - ciphertext=b'ciphertext_blob', - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.EncryptRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.EncryptResponse) - assert response.name == 'name_value' - assert response.ciphertext == b'ciphertext_blob' - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -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. - client = KeyManagementServiceClient( - 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.encrypt), - '__call__') as call: - client.encrypt() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.EncryptRequest() - - -@pytest.mark.asyncio -async def test_encrypt_async(transport: str = 'grpc_asyncio', request_type=service.EncryptRequest): - client = KeyManagementServiceAsyncClient( - 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.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse( - name='name_value', - ciphertext=b'ciphertext_blob', - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.EncryptRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.EncryptResponse) - assert response.name == 'name_value' - assert response.ciphertext == b'ciphertext_blob' - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_encrypt_async_from_dict(): - await test_encrypt_async(request_type=dict) - - -def test_encrypt_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.EncryptRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - call.return_value = service.EncryptResponse() - client.encrypt(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_encrypt_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.EncryptRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse()) - await client.encrypt(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_encrypt_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.encrypt( - name='name_value', - plaintext=b'plaintext_blob', - ) - - # 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 - arg = args[0].plaintext - mock_val = b'plaintext_blob' - assert arg == mock_val - - -def test_encrypt_flattened_error(): - client = KeyManagementServiceClient( - 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.encrypt( - service.EncryptRequest(), - name='name_value', - plaintext=b'plaintext_blob', - ) - - -@pytest.mark.asyncio -async def test_encrypt_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.encrypt( - name='name_value', - plaintext=b'plaintext_blob', - ) - - # 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 - arg = args[0].plaintext - mock_val = b'plaintext_blob' - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_encrypt_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.encrypt( - service.EncryptRequest(), - name='name_value', - plaintext=b'plaintext_blob', - ) - - -@pytest.mark.parametrize("request_type", [ - service.DecryptRequest, - dict, -]) -def test_decrypt(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - 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.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse( - plaintext=b'plaintext_blob', - used_primary=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.DecryptRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.DecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.used_primary is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -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. - client = KeyManagementServiceClient( - 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.decrypt), - '__call__') as call: - client.decrypt() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DecryptRequest() - - -@pytest.mark.asyncio -async def test_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.DecryptRequest): - client = KeyManagementServiceAsyncClient( - 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.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse( - plaintext=b'plaintext_blob', - used_primary=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.DecryptRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.DecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.used_primary is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_decrypt_async_from_dict(): - await test_decrypt_async(request_type=dict) - - -def test_decrypt_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DecryptRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - call.return_value = service.DecryptResponse() - client.decrypt(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_decrypt_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DecryptRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse()) - await client.decrypt(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_decrypt_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.decrypt( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - # 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 - arg = args[0].ciphertext - mock_val = b'ciphertext_blob' - assert arg == mock_val - - -def test_decrypt_flattened_error(): - client = KeyManagementServiceClient( - 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.decrypt( - service.DecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - -@pytest.mark.asyncio -async def test_decrypt_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.decrypt( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - # 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 - arg = args[0].ciphertext - mock_val = b'ciphertext_blob' - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_decrypt_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.decrypt( - service.DecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - -@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, - ) - - # 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.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse( - signature=b'signature_blob', - verified_digest_crc32c=True, - name='name_value', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.AsymmetricSignRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricSignResponse) - assert response.signature == b'signature_blob' - assert response.verified_digest_crc32c is True - assert response.name == 'name_value' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -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. - client = KeyManagementServiceClient( - 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.asymmetric_sign), - '__call__') as call: - client.asymmetric_sign() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.AsymmetricSignRequest() - - -@pytest.mark.asyncio -async def test_asymmetric_sign_async(transport: str = 'grpc_asyncio', request_type=service.AsymmetricSignRequest): - client = KeyManagementServiceAsyncClient( - 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.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse( - signature=b'signature_blob', - verified_digest_crc32c=True, - name='name_value', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.AsymmetricSignRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricSignResponse) - assert response.signature == b'signature_blob' - assert response.verified_digest_crc32c is True - assert response.name == 'name_value' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_asymmetric_sign_async_from_dict(): - await test_asymmetric_sign_async(request_type=dict) - - -def test_asymmetric_sign_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.AsymmetricSignRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - call.return_value = service.AsymmetricSignResponse() - client.asymmetric_sign(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_asymmetric_sign_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.AsymmetricSignRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse()) - await client.asymmetric_sign(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_asymmetric_sign_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.asymmetric_sign( - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - - # 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 - arg = args[0].digest - mock_val = service.Digest(sha256=b'sha256_blob') - assert arg == mock_val - - -def test_asymmetric_sign_flattened_error(): - client = KeyManagementServiceClient( - 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.asymmetric_sign( - service.AsymmetricSignRequest(), - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - - -@pytest.mark.asyncio -async def test_asymmetric_sign_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.asymmetric_sign( - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - - # 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 - arg = args[0].digest - mock_val = service.Digest(sha256=b'sha256_blob') - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_asymmetric_sign_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.asymmetric_sign( - service.AsymmetricSignRequest(), - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - - -@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, - ) - - # 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.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse( - plaintext=b'plaintext_blob', - verified_ciphertext_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.AsymmetricDecryptRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricDecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.verified_ciphertext_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -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. - client = KeyManagementServiceClient( - 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.asymmetric_decrypt), - '__call__') as call: - client.asymmetric_decrypt() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.AsymmetricDecryptRequest() - - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.AsymmetricDecryptRequest): - client = KeyManagementServiceAsyncClient( - 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.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse( - plaintext=b'plaintext_blob', - verified_ciphertext_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.AsymmetricDecryptRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricDecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.verified_ciphertext_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_async_from_dict(): - await test_asymmetric_decrypt_async(request_type=dict) - - -def test_asymmetric_decrypt_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.AsymmetricDecryptRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - call.return_value = service.AsymmetricDecryptResponse() - client.asymmetric_decrypt(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_asymmetric_decrypt_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.AsymmetricDecryptRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse()) - await client.asymmetric_decrypt(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_asymmetric_decrypt_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.asymmetric_decrypt( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - # 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 - arg = args[0].ciphertext - mock_val = b'ciphertext_blob' - assert arg == mock_val - - -def test_asymmetric_decrypt_flattened_error(): - client = KeyManagementServiceClient( - 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.asymmetric_decrypt( - service.AsymmetricDecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.asymmetric_decrypt( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - # 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 - arg = args[0].ciphertext - mock_val = b'ciphertext_blob' - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.asymmetric_decrypt( - service.AsymmetricDecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - -@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, - ) - - # 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.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse( - name='name_value', - mac=b'mac_blob', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.MacSignRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacSignResponse) - assert response.name == 'name_value' - assert response.mac == b'mac_blob' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -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. - client = KeyManagementServiceClient( - 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.mac_sign), - '__call__') as call: - client.mac_sign() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.MacSignRequest() - - -@pytest.mark.asyncio -async def test_mac_sign_async(transport: str = 'grpc_asyncio', request_type=service.MacSignRequest): - client = KeyManagementServiceAsyncClient( - 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.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse( - name='name_value', - mac=b'mac_blob', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.MacSignRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacSignResponse) - assert response.name == 'name_value' - assert response.mac == b'mac_blob' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_mac_sign_async_from_dict(): - await test_mac_sign_async(request_type=dict) - - -def test_mac_sign_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.MacSignRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - call.return_value = service.MacSignResponse() - client.mac_sign(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_mac_sign_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.MacSignRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse()) - await client.mac_sign(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_mac_sign_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.mac_sign( - name='name_value', - data=b'data_blob', - ) - - # 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 - arg = args[0].data - mock_val = b'data_blob' - assert arg == mock_val - - -def test_mac_sign_flattened_error(): - client = KeyManagementServiceClient( - 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.mac_sign( - service.MacSignRequest(), - name='name_value', - data=b'data_blob', - ) - - -@pytest.mark.asyncio -async def test_mac_sign_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.mac_sign( - name='name_value', - data=b'data_blob', - ) - - # 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 - arg = args[0].data - mock_val = b'data_blob' - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_mac_sign_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.mac_sign( - service.MacSignRequest(), - name='name_value', - data=b'data_blob', - ) - - -@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, - ) - - # 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.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse( - name='name_value', - success=True, - verified_data_crc32c=True, - verified_mac_crc32c=True, - verified_success_integrity=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.MacVerifyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacVerifyResponse) - assert response.name == 'name_value' - assert response.success is True - assert response.verified_data_crc32c is True - assert response.verified_mac_crc32c is True - assert response.verified_success_integrity is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -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. - client = KeyManagementServiceClient( - 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.mac_verify), - '__call__') as call: - client.mac_verify() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.MacVerifyRequest() - - -@pytest.mark.asyncio -async def test_mac_verify_async(transport: str = 'grpc_asyncio', request_type=service.MacVerifyRequest): - client = KeyManagementServiceAsyncClient( - 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.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse( - name='name_value', - success=True, - verified_data_crc32c=True, - verified_mac_crc32c=True, - verified_success_integrity=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.MacVerifyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacVerifyResponse) - assert response.name == 'name_value' - assert response.success is True - assert response.verified_data_crc32c is True - assert response.verified_mac_crc32c is True - assert response.verified_success_integrity is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_mac_verify_async_from_dict(): - await test_mac_verify_async(request_type=dict) - - -def test_mac_verify_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.MacVerifyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - call.return_value = service.MacVerifyResponse() - client.mac_verify(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_mac_verify_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.MacVerifyRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse()) - await client.mac_verify(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_mac_verify_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.mac_verify( - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - - # 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 - 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(): - client = KeyManagementServiceClient( - 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.mac_verify( - service.MacVerifyRequest(), - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - - -@pytest.mark.asyncio -async def test_mac_verify_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.mac_verify( - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - - # 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 - 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 -async def test_mac_verify_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.mac_verify( - service.MacVerifyRequest(), - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - - -@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, - ) - - # 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.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse( - data=b'data_blob', - ) - response = client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.GenerateRandomBytesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateRandomBytesResponse) - assert response.data == b'data_blob' - - -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. - client = KeyManagementServiceClient( - 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.generate_random_bytes), - '__call__') as call: - client.generate_random_bytes() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GenerateRandomBytesRequest() - - -@pytest.mark.asyncio -async def test_generate_random_bytes_async(transport: str = 'grpc_asyncio', request_type=service.GenerateRandomBytesRequest): - client = KeyManagementServiceAsyncClient( - 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.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse( - data=b'data_blob', - )) - response = await client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.GenerateRandomBytesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateRandomBytesResponse) - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_generate_random_bytes_async_from_dict(): - await test_generate_random_bytes_async(request_type=dict) - - -def test_generate_random_bytes_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GenerateRandomBytesRequest() - - request.location = 'location/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - call.return_value = service.GenerateRandomBytesResponse() - client.generate_random_bytes(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', - 'location=location/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_random_bytes_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GenerateRandomBytesRequest() - - request.location = 'location/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse()) - await client.generate_random_bytes(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', - 'location=location/value', - ) in kw['metadata'] - - -def test_generate_random_bytes_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_random_bytes( - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # 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].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(): - client = KeyManagementServiceClient( - 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.generate_random_bytes( - service.GenerateRandomBytesRequest(), - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - -@pytest.mark.asyncio -async def test_generate_random_bytes_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_random_bytes( - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # 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].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 -async def test_generate_random_bytes_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - 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.generate_random_bytes( - service.GenerateRandomBytesRequest(), - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - client_options={"credentials_file": "credentials.json"}, - 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(), - ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = KeyManagementServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.KeyManagementServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, -]) -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 = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.KeyManagementServiceGrpcTransport, - ) - -def test_key_management_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.KeyManagementServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_key_management_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.KeyManagementServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_key_rings', - 'list_crypto_keys', - 'list_crypto_key_versions', - 'list_import_jobs', - 'get_key_ring', - 'get_crypto_key', - 'get_crypto_key_version', - 'get_public_key', - 'get_import_job', - 'create_key_ring', - 'create_crypto_key', - 'create_crypto_key_version', - 'import_crypto_key_version', - 'create_import_job', - 'update_crypto_key', - 'update_crypto_key_version', - 'update_crypto_key_primary_version', - 'destroy_crypto_key_version', - 'restore_crypto_key_version', - 'encrypt', - 'decrypt', - 'asymmetric_sign', - 'asymmetric_decrypt', - 'mac_sign', - 'mac_verify', - 'generate_random_bytes', - '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_key_management_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.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KeyManagementServiceTransport( - 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_key_management_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.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KeyManagementServiceTransport() - adc.assert_called_once() - - -def test_key_management_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) - KeyManagementServiceClient() - 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.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, - ], -) -def test_key_management_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.KeyManagementServiceGrpcTransport, grpc_helpers), - (transports.KeyManagementServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_key_management_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.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) -def test_key_management_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_key_management_service_host_no_port(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), - ) - assert client.transport._host == 'cloudkms.googleapis.com:443' - - -def test_key_management_service_host_with_port(): - client = KeyManagementServiceClient( - 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_key_management_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.KeyManagementServiceGrpcTransport( - 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_key_management_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.KeyManagementServiceGrpcAsyncIOTransport( - 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.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) -def test_key_management_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.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) -def test_key_management_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_crypto_key_path(): - project = "squid" - location = "clam" - key_ring = "whelk" - crypto_key = "octopus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - actual = KeyManagementServiceClient.crypto_key_path(project, location, key_ring, crypto_key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "key_ring": "cuttlefish", - "crypto_key": "mussel", - } - path = KeyManagementServiceClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_crypto_key_path(path) - assert expected == actual - -def test_crypto_key_version_path(): - project = "winkle" - location = "nautilus" - key_ring = "scallop" - crypto_key = "abalone" - crypto_key_version = "squid" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - actual = KeyManagementServiceClient.crypto_key_version_path(project, location, key_ring, crypto_key, crypto_key_version) - assert expected == actual - - -def test_parse_crypto_key_version_path(): - expected = { - "project": "clam", - "location": "whelk", - "key_ring": "octopus", - "crypto_key": "oyster", - "crypto_key_version": "nudibranch", - } - path = KeyManagementServiceClient.crypto_key_version_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_crypto_key_version_path(path) - assert expected == actual - -def test_import_job_path(): - project = "cuttlefish" - location = "mussel" - key_ring = "winkle" - import_job = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format(project=project, location=location, key_ring=key_ring, import_job=import_job, ) - actual = KeyManagementServiceClient.import_job_path(project, location, key_ring, import_job) - assert expected == actual - - -def test_parse_import_job_path(): - expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "import_job": "clam", - } - path = KeyManagementServiceClient.import_job_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_import_job_path(path) - assert expected == actual - -def test_key_ring_path(): - project = "whelk" - location = "octopus" - key_ring = "oyster" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}".format(project=project, location=location, key_ring=key_ring, ) - actual = KeyManagementServiceClient.key_ring_path(project, location, key_ring) - assert expected == actual - - -def test_parse_key_ring_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "key_ring": "mussel", - } - path = KeyManagementServiceClient.key_ring_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_key_ring_path(path) - assert expected == actual - -def test_public_key_path(): - project = "winkle" - location = "nautilus" - key_ring = "scallop" - crypto_key = "abalone" - crypto_key_version = "squid" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - actual = KeyManagementServiceClient.public_key_path(project, location, key_ring, crypto_key, crypto_key_version) - assert expected == actual - - -def test_parse_public_key_path(): - expected = { - "project": "clam", - "location": "whelk", - "key_ring": "octopus", - "crypto_key": "oyster", - "crypto_key_version": "nudibranch", - } - path = KeyManagementServiceClient.public_key_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_public_key_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = KeyManagementServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = KeyManagementServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = KeyManagementServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = KeyManagementServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = KeyManagementServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = KeyManagementServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = KeyManagementServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = KeyManagementServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = KeyManagementServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = KeyManagementServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.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.KeyManagementServiceTransport, '_prep_wrapped_messages') as prep: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.KeyManagementServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = KeyManagementServiceClient.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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceAsyncClient( - 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 = KeyManagementServiceClient( - 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 = KeyManagementServiceClient( - 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", [ - (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, - ) 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, + )