From c61bd74884debb3e9b149ce42c65b10c0545572b Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 3 Feb 2022 01:50:22 +0000 Subject: [PATCH 1/2] feat: add a new EkmService API PiperOrigin-RevId: 425982419 Source-Link: https://github.com/googleapis/googleapis/commit/8dff5691cc4d4a0c61af8cdef85b6460ae560f0d Source-Link: https://github.com/googleapis/googleapis-gen/commit/b1538df1643922606d00ec0365c1e0a51bfbcabf Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjE1MzhkZjE2NDM5MjI2MDZkMDBlYzAzNjVjMWUwYTUxYmZiY2FiZiJ9 --- 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/ekm_service.rst | 10 + .../v1/docs/kms_v1/key_management_service.rst | 10 + owl-bot-staging/v1/docs/kms_v1/services.rst | 7 + owl-bot-staging/v1/docs/kms_v1/types.rst | 7 + .../v1/google/cloud/kms/__init__.py | 137 + owl-bot-staging/v1/google/cloud/kms/py.typed | 2 + .../v1/google/cloud/kms_v1/__init__.py | 138 + .../google/cloud/kms_v1/gapic_metadata.json | 337 + .../v1/google/cloud/kms_v1/py.typed | 2 + .../google/cloud/kms_v1/services/__init__.py | 15 + .../kms_v1/services/ekm_service/__init__.py | 22 + .../services/ekm_service/async_client.py | 898 ++ .../kms_v1/services/ekm_service/client.py | 1080 ++ .../kms_v1/services/ekm_service/pagers.py | 139 + .../ekm_service/transports/__init__.py | 33 + .../services/ekm_service/transports/base.py | 247 + .../services/ekm_service/transports/grpc.py | 424 + .../ekm_service/transports/grpc_asyncio.py | 429 + .../key_management_service/__init__.py | 22 + .../key_management_service/async_client.py | 3197 ++++++ .../services/key_management_service/client.py | 3267 ++++++ .../services/key_management_service/pagers.py | 503 + .../transports/__init__.py | 33 + .../key_management_service/transports/base.py | 696 ++ .../key_management_service/transports/grpc.py | 1118 ++ .../transports/grpc_asyncio.py | 1123 ++ .../v1/google/cloud/kms_v1/types/__init__.py | 134 + .../google/cloud/kms_v1/types/ekm_service.py | 377 + .../v1/google/cloud/kms_v1/types/resources.py | 916 ++ .../v1/google/cloud/kms_v1/types/service.py | 1979 ++++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../v1/scripts/fixup_kms_v1_keywords.py | 208 + 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 + .../unit/gapic/kms_v1/test_ekm_service.py | 2765 +++++ .../kms_v1/test_key_management_service.py | 8985 +++++++++++++++++ 45 files changed, 29965 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/ekm_service.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/ekm_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.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/ekm_service.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_ekm_service.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..12cf25d1 --- /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 = "4.0.1" + +# 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 root toctree document. +root_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 = [ + ( + root_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 = [ + ( + root_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 = [ + ( + root_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/ekm_service.rst b/owl-bot-staging/v1/docs/kms_v1/ekm_service.rst new file mode 100644 index 00000000..82f6e2a4 --- /dev/null +++ b/owl-bot-staging/v1/docs/kms_v1/ekm_service.rst @@ -0,0 +1,10 @@ +EkmService +---------------------------- + +.. automodule:: google.cloud.kms_v1.services.ekm_service + :members: + :inherited-members: + +.. automodule:: google.cloud.kms_v1.services.ekm_service.pagers + :members: + :inherited-members: diff --git a/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..141ddfe4 --- /dev/null +++ b/owl-bot-staging/v1/docs/kms_v1/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Kms v1 API +==================================== +.. toctree:: + :maxdepth: 2 + + ekm_service + 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..e4f07546 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms/__init__.py @@ -0,0 +1,137 @@ +# -*- 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.ekm_service.client import EkmServiceClient +from google.cloud.kms_v1.services.ekm_service.async_client import EkmServiceAsyncClient +from google.cloud.kms_v1.services.key_management_service.client import KeyManagementServiceClient +from google.cloud.kms_v1.services.key_management_service.async_client import KeyManagementServiceAsyncClient + +from google.cloud.kms_v1.types.ekm_service import Certificate +from google.cloud.kms_v1.types.ekm_service import CreateEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import EkmConnection +from google.cloud.kms_v1.types.ekm_service import GetEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsRequest +from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsResponse +from google.cloud.kms_v1.types.ekm_service import UpdateEkmConnectionRequest +from google.cloud.kms_v1.types.resources import CryptoKey +from google.cloud.kms_v1.types.resources import CryptoKeyVersion +from google.cloud.kms_v1.types.resources import CryptoKeyVersionTemplate +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__ = ('EkmServiceClient', + 'EkmServiceAsyncClient', + 'KeyManagementServiceClient', + 'KeyManagementServiceAsyncClient', + 'Certificate', + 'CreateEkmConnectionRequest', + 'EkmConnection', + 'GetEkmConnectionRequest', + 'ListEkmConnectionsRequest', + 'ListEkmConnectionsResponse', + 'UpdateEkmConnectionRequest', + '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..74317d3a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/__init__.py @@ -0,0 +1,138 @@ +# -*- 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.ekm_service import EkmServiceClient +from .services.ekm_service import EkmServiceAsyncClient +from .services.key_management_service import KeyManagementServiceClient +from .services.key_management_service import KeyManagementServiceAsyncClient + +from .types.ekm_service import Certificate +from .types.ekm_service import CreateEkmConnectionRequest +from .types.ekm_service import EkmConnection +from .types.ekm_service import GetEkmConnectionRequest +from .types.ekm_service import ListEkmConnectionsRequest +from .types.ekm_service import ListEkmConnectionsResponse +from .types.ekm_service import UpdateEkmConnectionRequest +from .types.resources import CryptoKey +from .types.resources import CryptoKeyVersion +from .types.resources import CryptoKeyVersionTemplate +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__ = ( + 'EkmServiceAsyncClient', + 'KeyManagementServiceAsyncClient', +'AsymmetricDecryptRequest', +'AsymmetricDecryptResponse', +'AsymmetricSignRequest', +'AsymmetricSignResponse', +'Certificate', +'CreateCryptoKeyRequest', +'CreateCryptoKeyVersionRequest', +'CreateEkmConnectionRequest', +'CreateImportJobRequest', +'CreateKeyRingRequest', +'CryptoKey', +'CryptoKeyVersion', +'CryptoKeyVersionTemplate', +'DecryptRequest', +'DecryptResponse', +'DestroyCryptoKeyVersionRequest', +'Digest', +'EkmConnection', +'EkmServiceClient', +'EncryptRequest', +'EncryptResponse', +'ExternalProtectionLevelOptions', +'GenerateRandomBytesRequest', +'GenerateRandomBytesResponse', +'GetCryptoKeyRequest', +'GetCryptoKeyVersionRequest', +'GetEkmConnectionRequest', +'GetImportJobRequest', +'GetKeyRingRequest', +'GetPublicKeyRequest', +'ImportCryptoKeyVersionRequest', +'ImportJob', +'KeyManagementServiceClient', +'KeyOperationAttestation', +'KeyRing', +'ListCryptoKeyVersionsRequest', +'ListCryptoKeyVersionsResponse', +'ListCryptoKeysRequest', +'ListCryptoKeysResponse', +'ListEkmConnectionsRequest', +'ListEkmConnectionsResponse', +'ListImportJobsRequest', +'ListImportJobsResponse', +'ListKeyRingsRequest', +'ListKeyRingsResponse', +'LocationMetadata', +'MacSignRequest', +'MacSignResponse', +'MacVerifyRequest', +'MacVerifyResponse', +'ProtectionLevel', +'PublicKey', +'RestoreCryptoKeyVersionRequest', +'UpdateCryptoKeyPrimaryVersionRequest', +'UpdateCryptoKeyRequest', +'UpdateCryptoKeyVersionRequest', +'UpdateEkmConnectionRequest', +) 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..3b830979 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json @@ -0,0 +1,337 @@ + { + "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": { + "EkmService": { + "clients": { + "grpc": { + "libraryClient": "EkmServiceClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EkmServiceAsyncClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + } + } + } + } + }, + "KeyManagementService": { + "clients": { + "grpc": { + "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/ekm_service/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/__init__.py new file mode 100644 index 00000000..61e2ac84 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import EkmServiceClient +from .async_client import EkmServiceAsyncClient + +__all__ = ( + 'EkmServiceClient', + 'EkmServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/async_client.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/async_client.py new file mode 100644 index 00000000..142eccdf --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/async_client.py @@ -0,0 +1,898 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport +from .client import EkmServiceClient + + +class EkmServiceAsyncClient: + """Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + """ + + _client: EkmServiceClient + + DEFAULT_ENDPOINT = EkmServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EkmServiceClient.DEFAULT_MTLS_ENDPOINT + + ekm_connection_path = staticmethod(EkmServiceClient.ekm_connection_path) + parse_ekm_connection_path = staticmethod(EkmServiceClient.parse_ekm_connection_path) + service_path = staticmethod(EkmServiceClient.service_path) + parse_service_path = staticmethod(EkmServiceClient.parse_service_path) + common_billing_account_path = staticmethod(EkmServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EkmServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EkmServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(EkmServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(EkmServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(EkmServiceClient.parse_common_organization_path) + common_project_path = staticmethod(EkmServiceClient.common_project_path) + parse_common_project_path = staticmethod(EkmServiceClient.parse_common_project_path) + common_location_path = staticmethod(EkmServiceClient.common_location_path) + parse_common_location_path = staticmethod(EkmServiceClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceAsyncClient: The constructed client. + """ + return EkmServiceClient.from_service_account_info.__func__(EkmServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceAsyncClient: The constructed client. + """ + return EkmServiceClient.from_service_account_file.__func__(EkmServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return EkmServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EkmServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EkmServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(EkmServiceClient).get_transport_class, type(EkmServiceClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EkmServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the ekm service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.EkmServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EkmServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_ekm_connections(self, + request: Union[ekm_service.ListEkmConnectionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEkmConnectionsAsyncPager: + r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + Args: + request (Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListEkmConnections][]. + parent (:class:`str`): + Required. The resource name of the location associated + with the + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.ekm_service.pagers.ListEkmConnectionsAsyncPager: + Response message for + [KeyManagementService.ListEkmConnections][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = ekm_service.ListEkmConnectionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_ekm_connections, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEkmConnectionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_ekm_connection(self, + request: Union[ekm_service.GetEkmConnectionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Args: + request (Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.GetEkmConnection][]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = ekm_service.GetEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_ekm_connection, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_ekm_connection(self, + request: Union[ekm_service.CreateEkmConnectionRequest, dict] = None, + *, + parent: str = None, + ekm_connection_id: str = None, + ekm_connection: ekm_service.EkmConnection = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + Args: + request (Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateEkmConnection][]. + parent (:class:`str`): + Required. The resource name of the location associated + with the + [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection_id (:class:`str`): + Required. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``ekm_connection_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection (:class:`google.cloud.kms_v1.types.EkmConnection`): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, ekm_connection_id, ekm_connection]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = ekm_service.CreateEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if ekm_connection_id is not None: + request.ekm_connection_id = ekm_connection_id + if ekm_connection is not None: + request.ekm_connection = ekm_connection + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_ekm_connection, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_ekm_connection(self, + request: Union[ekm_service.UpdateEkmConnectionRequest, dict] = None, + *, + ekm_connection: ekm_service.EkmConnection = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + Args: + request (Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateEkmConnection][]. + ekm_connection (:class:`google.cloud.kms_v1.types.EkmConnection`): + Required. + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + updated values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([ekm_connection, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = ekm_service.UpdateEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ekm_connection is not None: + request.ekm_connection = ekm_connection + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_ekm_connection, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("ekm_connection.name", request.ekm_connection.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does + not have a policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified permissions against the IAM access control + policy for a function. + + If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-kms", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EkmServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/client.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/client.py new file mode 100644 index 00000000..7abc4198 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/client.py @@ -0,0 +1,1080 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EkmServiceGrpcTransport +from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport + + +class EkmServiceClientMeta(type): + """Metaclass for the EkmService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] + _transport_registry["grpc"] = EkmServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[EkmServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class EkmServiceClient(metaclass=EkmServiceClientMeta): + """Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudkms.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EkmServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EkmServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def ekm_connection_path(project: str,location: str,ekm_connection: str,) -> str: + """Returns a fully-qualified ekm_connection string.""" + return "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format(project=project, location=location, ekm_connection=ekm_connection, ) + + @staticmethod + def parse_ekm_connection_path(path: str) -> Dict[str,str]: + """Parses a ekm_connection path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/ekmConnections/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EkmServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the ekm service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, EkmServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EkmServiceTransport): + # transport is a EkmServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + ) + + def list_ekm_connections(self, + request: Union[ekm_service.ListEkmConnectionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEkmConnectionsPager: + r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + Args: + request (Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListEkmConnections][]. + parent (str): + Required. The resource name of the location associated + with the + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.ekm_service.pagers.ListEkmConnectionsPager: + Response message for + [KeyManagementService.ListEkmConnections][]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.ListEkmConnectionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.ListEkmConnectionsRequest): + request = ekm_service.ListEkmConnectionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_ekm_connections] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEkmConnectionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_ekm_connection(self, + request: Union[ekm_service.GetEkmConnectionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Args: + request (Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.GetEkmConnection][]. + name (str): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.GetEkmConnectionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.GetEkmConnectionRequest): + request = ekm_service.GetEkmConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_ekm_connection(self, + request: Union[ekm_service.CreateEkmConnectionRequest, dict] = None, + *, + parent: str = None, + ekm_connection_id: str = None, + ekm_connection: ekm_service.EkmConnection = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + Args: + request (Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateEkmConnection][]. + parent (str): + Required. The resource name of the location associated + with the + [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection_id (str): + Required. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``ekm_connection_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, ekm_connection_id, ekm_connection]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.CreateEkmConnectionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.CreateEkmConnectionRequest): + request = ekm_service.CreateEkmConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if ekm_connection_id is not None: + request.ekm_connection_id = ekm_connection_id + if ekm_connection is not None: + request.ekm_connection = ekm_connection + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_ekm_connection(self, + request: Union[ekm_service.UpdateEkmConnectionRequest, dict] = None, + *, + ekm_connection: ekm_service.EkmConnection = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + Args: + request (Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateEkmConnection][]. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + updated values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([ekm_connection, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a ekm_service.UpdateEkmConnectionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, ekm_service.UpdateEkmConnectionRequest): + request = ekm_service.UpdateEkmConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ekm_connection is not None: + request.ekm_connection = ekm_connection + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("ekm_connection.name", request.ekm_connection.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + **JSON Example** + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + **YAML Example** + :: + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-kms", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "EkmServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/pagers.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/pagers.py new file mode 100644 index 00000000..7d738d0d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.kms_v1.types import ekm_service + + +class ListEkmConnectionsPager: + """A pager for iterating through ``list_ekm_connections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``ekm_connections`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEkmConnections`` requests and continue to iterate + through the ``ekm_connections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., ekm_service.ListEkmConnectionsResponse], + request: ekm_service.ListEkmConnectionsRequest, + response: ekm_service.ListEkmConnectionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.kms_v1.types.ListEkmConnectionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListEkmConnectionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = ekm_service.ListEkmConnectionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[ekm_service.ListEkmConnectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[ekm_service.EkmConnection]: + for page in self.pages: + yield from page.ekm_connections + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEkmConnectionsAsyncPager: + """A pager for iterating through ``list_ekm_connections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``ekm_connections`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEkmConnections`` requests and continue to iterate + through the ``ekm_connections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[ekm_service.ListEkmConnectionsResponse]], + request: ekm_service.ListEkmConnectionsRequest, + response: ekm_service.ListEkmConnectionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.kms_v1.types.ListEkmConnectionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListEkmConnectionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = ekm_service.ListEkmConnectionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[ekm_service.ListEkmConnectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[ekm_service.EkmConnection]: + async def async_generator(): + async for page in self.pages: + for response in page.ekm_connections: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py new file mode 100644 index 00000000..37307beb --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EkmServiceTransport +from .grpc import EkmServiceGrpcTransport +from .grpc_asyncio import EkmServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] +_transport_registry['grpc'] = EkmServiceGrpcTransport +_transport_registry['grpc_asyncio'] = EkmServiceGrpcAsyncIOTransport + +__all__ = ( + 'EkmServiceTransport', + 'EkmServiceGrpcTransport', + 'EkmServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py new file mode 100644 index 00000000..d4524247 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py @@ -0,0 +1,247 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import pkg_resources + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-kms', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class EkmServiceTransport(abc.ABC): + """Abstract transport class for EkmService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', + ) + + DEFAULT_HOST: str = 'cloudkms.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_ekm_connections: gapic_v1.method.wrap_method( + self.list_ekm_connections, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_ekm_connection: gapic_v1.method.wrap_method( + self.get_ekm_connection, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_ekm_connection: gapic_v1.method.wrap_method( + self.create_ekm_connection, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_ekm_connection: gapic_v1.method.wrap_method( + self.update_ekm_connection, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_ekm_connections(self) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + Union[ + ekm_service.ListEkmConnectionsResponse, + Awaitable[ekm_service.ListEkmConnectionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_ekm_connection(self) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + Union[ + ekm_service.EkmConnection, + Awaitable[ekm_service.EkmConnection] + ]]: + raise NotImplementedError() + + @property + def create_ekm_connection(self) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + Union[ + ekm_service.EkmConnection, + Awaitable[ekm_service.EkmConnection] + ]]: + raise NotImplementedError() + + @property + def update_ekm_connection(self) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + Union[ + ekm_service.EkmConnection, + Awaitable[ekm_service.EkmConnection] + ]]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + +__all__ = ( + 'EkmServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py new file mode 100644 index 00000000..de0b8b46 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO + + +class EkmServiceGrpcTransport(EkmServiceTransport): + """gRPC backend transport for EkmService. + + Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudkms.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_ekm_connections(self) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + ekm_service.ListEkmConnectionsResponse]: + r"""Return a callable for the list ekm connections method over gRPC. + + Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.ListEkmConnectionsRequest], + ~.ListEkmConnectionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_ekm_connections' not in self._stubs: + self._stubs['list_ekm_connections'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/ListEkmConnections', + request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, + response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, + ) + return self._stubs['list_ekm_connections'] + + @property + def get_ekm_connection(self) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + ekm_service.EkmConnection]: + r"""Return a callable for the get ekm connection method over gRPC. + + Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.GetEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_ekm_connection' not in self._stubs: + self._stubs['get_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/GetEkmConnection', + request_serializer=ekm_service.GetEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['get_ekm_connection'] + + @property + def create_ekm_connection(self) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + ekm_service.EkmConnection]: + r"""Return a callable for the create ekm connection method over gRPC. + + Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + Returns: + Callable[[~.CreateEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_ekm_connection' not in self._stubs: + self._stubs['create_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/CreateEkmConnection', + request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['create_ekm_connection'] + + @property + def update_ekm_connection(self) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + ekm_service.EkmConnection]: + r"""Return a callable for the update ekm connection method over gRPC. + + Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + Returns: + Callable[[~.UpdateEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_ekm_connection' not in self._stubs: + self._stubs['update_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/UpdateEkmConnection', + request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['update_ekm_connection'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + self.grpc_channel.close() + +__all__ = ( + 'EkmServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..67560b8b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py @@ -0,0 +1,429 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import EkmServiceGrpcTransport + + +class EkmServiceGrpcAsyncIOTransport(EkmServiceTransport): + """gRPC AsyncIO backend transport for EkmService. + + Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'cloudkms.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_ekm_connections(self) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + Awaitable[ekm_service.ListEkmConnectionsResponse]]: + r"""Return a callable for the list ekm connections method over gRPC. + + Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.ListEkmConnectionsRequest], + Awaitable[~.ListEkmConnectionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_ekm_connections' not in self._stubs: + self._stubs['list_ekm_connections'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/ListEkmConnections', + request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, + response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, + ) + return self._stubs['list_ekm_connections'] + + @property + def get_ekm_connection(self) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + Awaitable[ekm_service.EkmConnection]]: + r"""Return a callable for the get ekm connection method over gRPC. + + Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.GetEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_ekm_connection' not in self._stubs: + self._stubs['get_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/GetEkmConnection', + request_serializer=ekm_service.GetEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['get_ekm_connection'] + + @property + def create_ekm_connection(self) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + Awaitable[ekm_service.EkmConnection]]: + r"""Return a callable for the create ekm connection method over gRPC. + + Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + Returns: + Callable[[~.CreateEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_ekm_connection' not in self._stubs: + self._stubs['create_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/CreateEkmConnection', + request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['create_ekm_connection'] + + @property + def update_ekm_connection(self) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + Awaitable[ekm_service.EkmConnection]]: + r"""Return a callable for the update ekm connection method over gRPC. + + Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + Returns: + Callable[[~.UpdateEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_ekm_connection' not in self._stubs: + self._stubs['update_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/UpdateEkmConnection', + request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['update_ekm_connection'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'EkmServiceGrpcAsyncIOTransport', +) diff --git a/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..4cdae615 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -0,0 +1,3197 @@ +# -*- 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, key_ring_id, key_ring]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, crypto_key_id, crypto_key]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, crypto_key_version]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, import_job_id, import_job]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([crypto_key, update_mask]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([crypto_key_version, update_mask]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, crypto_key_version_id]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, plaintext]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, ciphertext]) + if request is not None and has_flattened_params: + 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 field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + + This corresponds to the ``digest`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, digest]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, ciphertext]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data, mac]) + if request is not None and has_flattened_params: + 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. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] + protection level is supported. + + This corresponds to the ``protection_level`` field + on the ``request`` instance; if ``request`` is provided, this + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([location, length_bytes, protection_level]) + if request is not None and has_flattened_params: + 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..ed710138 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py @@ -0,0 +1,3267 @@ +# -*- 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, key_ring_id, key_ring]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, crypto_key_id, crypto_key]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, crypto_key_version]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, import_job_id, import_job]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([crypto_key, update_mask]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([crypto_key_version, update_mask]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, crypto_key_version_id]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, plaintext]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, ciphertext]) + if request is not None and has_flattened_params: + 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 field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + + This corresponds to the ``digest`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, digest]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, ciphertext]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data]) + if request is not None and has_flattened_params: + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, data, mac]) + if request is not None and has_flattened_params: + 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. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] + protection level is supported. + + This corresponds to the ``protection_level`` field + on the ``request`` instance; if ``request`` is provided, this + 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. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([location, length_bytes, protection_level]) + if request is not None and has_flattened_params: + 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..77e2ff65 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -0,0 +1,1118 @@ +# -*- 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, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudkms.googleapis.com', + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_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..5fd78d44 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -0,0 +1,1123 @@ +# -*- 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, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_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..80dba706 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py @@ -0,0 +1,134 @@ +# -*- 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 .ekm_service import ( + Certificate, + CreateEkmConnectionRequest, + EkmConnection, + GetEkmConnectionRequest, + ListEkmConnectionsRequest, + ListEkmConnectionsResponse, + UpdateEkmConnectionRequest, +) +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__ = ( + 'Certificate', + 'CreateEkmConnectionRequest', + 'EkmConnection', + 'GetEkmConnectionRequest', + 'ListEkmConnectionsRequest', + 'ListEkmConnectionsResponse', + 'UpdateEkmConnectionRequest', + '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/ekm_service.py b/owl-bot-staging/v1/google/cloud/kms_v1/types/ekm_service.py new file mode 100644 index 00000000..208115fc --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/types/ekm_service.py @@ -0,0 +1,377 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.kms.v1', + manifest={ + 'ListEkmConnectionsRequest', + 'ListEkmConnectionsResponse', + 'GetEkmConnectionRequest', + 'CreateEkmConnectionRequest', + 'UpdateEkmConnectionRequest', + 'Certificate', + 'EkmConnection', + }, +) + + +class ListEkmConnectionsRequest(proto.Message): + r"""Request message for [KeyManagementService.ListEkmConnections][]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + page_size (int): + Optional. Optional limit on the number of + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + include in the response. Further + [EkmConnections][google.cloud.kms.v1.EkmConnection] can + subsequently be obtained by including the + [ListEkmConnectionsResponse.next_page_token][google.cloud.kms.v1.ListEkmConnectionsResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListEkmConnectionsResponse.next_page_token][google.cloud.kms.v1.ListEkmConnectionsResponse.next_page_token]. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_size = proto.Field( + proto.INT32, + number=2, + ) + page_token = proto.Field( + proto.STRING, + number=3, + ) + filter = proto.Field( + proto.STRING, + number=4, + ) + order_by = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEkmConnectionsResponse(proto.Message): + r"""Response message for [KeyManagementService.ListEkmConnections][]. + + Attributes: + ekm_connections (Sequence[google.cloud.kms_v1.types.EkmConnection]): + The list of + [EkmConnections][google.cloud.kms.v1.EkmConnection]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListEkmConnectionsRequest.page_token][google.cloud.kms.v1.ListEkmConnectionsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [EkmConnections][google.cloud.kms.v1.EkmConnection] that + matched the query. + """ + + @property + def raw_page(self): + return self + + ekm_connections = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EkmConnection', + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + total_size = proto.Field( + proto.INT32, + number=3, + ) + + +class GetEkmConnectionRequest(proto.Message): + r"""Request message for [KeyManagementService.GetEkmConnection][]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.EkmConnection.name] + of the [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEkmConnectionRequest(proto.Message): + r"""Request message for [KeyManagementService.CreateEkmConnection][]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + ekm_connection_id (str): + Required. It must be unique within a location and match the + regular expression ``[a-zA-Z0-9_-]{1,63}``. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + ekm_connection_id = proto.Field( + proto.STRING, + number=2, + ) + ekm_connection = proto.Field( + proto.MESSAGE, + number=3, + message='EkmConnection', + ) + + +class UpdateEkmConnectionRequest(proto.Message): + r"""Request message for [KeyManagementService.UpdateEkmConnection][]. + + Attributes: + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. [EkmConnection][google.cloud.kms.v1.EkmConnection] + with updated values. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + ekm_connection = proto.Field( + proto.MESSAGE, + number=1, + message='EkmConnection', + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class Certificate(proto.Message): + r"""A [Certificate][google.cloud.kms.v1.Certificate] represents an X.509 + certificate used to authenticate HTTPS connections to EKM replicas. + + Attributes: + raw_der (bytes): + Required. The raw certificate bytes in DER + format. + parsed (bool): + Output only. True if the certificate was + parsed successfully. + issuer (str): + Output only. The issuer distinguished name in RFC 2253 + format. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + subject (str): + Output only. The subject distinguished name in RFC 2253 + format. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + subject_alternative_dns_names (Sequence[str]): + Output only. The subject Alternative DNS names. Only present + if [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + not_before_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The certificate is not valid before this time. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + not_after_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The certificate is not valid after this time. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + serial_number (str): + Output only. The certificate serial number as a hex string. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + sha256_fingerprint (str): + Output only. The SHA-256 certificate fingerprint as a hex + string. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + """ + + raw_der = proto.Field( + proto.BYTES, + number=1, + ) + parsed = proto.Field( + proto.BOOL, + number=2, + ) + issuer = proto.Field( + proto.STRING, + number=3, + ) + subject = proto.Field( + proto.STRING, + number=4, + ) + subject_alternative_dns_names = proto.RepeatedField( + proto.STRING, + number=5, + ) + not_before_time = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + not_after_time = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + serial_number = proto.Field( + proto.STRING, + number=8, + ) + sha256_fingerprint = proto.Field( + proto.STRING, + number=9, + ) + + +class EkmConnection(proto.Message): + r"""An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for creating + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], as + well as performing cryptographic operations using keys created + within the [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Attributes: + name (str): + Output only. The resource name for the + [EkmConnection][google.cloud.kms.v1.EkmConnection] in the + format ``projects/*/locations/*/ekmConnections/*``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + [EkmConnection][google.cloud.kms.v1.EkmConnection] was + created. + service_resolvers (Sequence[google.cloud.kms_v1.types.EkmConnection.ServiceResolver]): + A list of + [ServiceResolvers][google.cloud.kms.v1.EkmConnection.ServiceResolver] + where the EKM can be reached. There should be one + ServiceResolver per EKM replica. Currently, only a single + [ServiceResolver][google.cloud.kms.v1.EkmConnection.ServiceResolver] + is supported. + etag (str): + This checksum is computed by the server based + on the value of other fields, and may be sent on + update requests to ensure the client has an + up-to-date value before proceeding. + """ + + class ServiceResolver(proto.Message): + r"""A + [ServiceResolver][google.cloud.kms.v1.EkmConnection.ServiceResolver] + represents an EKM replica that can be reached within an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Attributes: + service_directory_service (str): + Required. The resource name of the Service Directory service + pointing to an EKM replica, in the format + ``projects/*/locations/*/namespaces/*/services/*``. + endpoint_filter (str): + Optional. The filter applied to the endpoints + of the resolved service. If no filter is + specified, all endpoints will be considered. An + endpoint will be chosen arbitrarily from the + filtered list for each request. + For endpoint filter syntax and examples, see + https://cloud.google.com/service-directory/docs/reference/rpc/google.cloud.servicedirectory.v1#resolveservicerequest. + hostname (str): + Required. The hostname of the EKM replica + used at TLS and HTTP layers. + server_certificates (Sequence[google.cloud.kms_v1.types.Certificate]): + Required. A list of leaf server certificates + used to authenticate HTTPS connections to the + EKM replica. + """ + + service_directory_service = proto.Field( + proto.STRING, + number=1, + ) + endpoint_filter = proto.Field( + proto.STRING, + number=2, + ) + hostname = proto.Field( + proto.STRING, + number=3, + ) + server_certificates = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Certificate', + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + create_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + service_resolvers = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ServiceResolver, + ) + etag = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/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..d33ffc1f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py @@ -0,0 +1,916 @@ +# -*- 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 + EXTERNAL_VPC = 4 + + +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. + crypto_key_backend (str): + Immutable. The resource name of the backend environment + where the key material for all + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + associated with this + [CryptoKey][google.cloud.kms.v1.CryptoKey] reside and where + all related cryptographic operations are performed. Only + applicable if + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + have a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + with the resource name in the format + ``projects/*/locations/*/ekmConnections/*``. Note, this list + is non-exhaustive and may apply to additional + [ProtectionLevels][google.cloud.kms.v1.ProtectionLevel] in + the future. + """ + class CryptoKeyPurpose(proto.Enum): + 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, + ) + crypto_key_backend = proto.Field( + proto.STRING, + number=15, + ) + + +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. + cert_chains (google.cloud.kms_v1.types.KeyOperationAttestation.CertificateChains): + Output only. The certificate chains needed to + validate the attestation + """ + class AttestationFormat(proto.Enum): + r"""Attestation formats provided by the HSM.""" + ATTESTATION_FORMAT_UNSPECIFIED = 0 + CAVIUM_V1_COMPRESSED = 3 + CAVIUM_V2_COMPRESSED = 4 + + class CertificateChains(proto.Message): + r"""Certificate chains needed to verify the attestation. + Certificates in chains are PEM-encoded and are ordered based on + https://tools.ietf.org/html/rfc5246#section-7.4.2. + + Attributes: + cavium_certs (Sequence[str]): + Cavium certificate chain corresponding to the + attestation. + google_card_certs (Sequence[str]): + Google card certificate chain corresponding + to the attestation. + google_partition_certs (Sequence[str]): + Google partition certificate chain + corresponding to the attestation. + """ + + cavium_certs = proto.RepeatedField( + proto.STRING, + number=1, + ) + google_card_certs = proto.RepeatedField( + proto.STRING, + number=2, + ) + google_partition_certs = proto.RepeatedField( + proto.STRING, + number=3, + ) + + format_ = proto.Field( + proto.ENUM, + number=4, + enum=AttestationFormat, + ) + content = proto.Field( + proto.BYTES, + number=5, + ) + cert_chains = proto.Field( + proto.MESSAGE, + number=6, + message=CertificateChains, + ) + + +class CryptoKeyVersion(proto.Message): + 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 and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + protection levels. + reimport_eligible (bool): + Output only. Whether or not this key version is eligible for + reimport, by being specified as a target in + [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 and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + protection levels. + + Attributes: + external_key_uri (str): + The URI for an external resource that this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents. + ekm_connection_key_path (str): + The path to the external key material on the EKM when using + [EkmConnection][google.cloud.kms.v1.EkmConnection] e.g., + "v0/my/key". Set this field instead of external_key_uri when + using an [EkmConnection][google.cloud.kms.v1.EkmConnection]. + """ + + external_key_uri = proto.Field( + proto.STRING, + number=1, + ) + ekm_connection_key_path = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/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..20fc0c49 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/kms_v1/types/service.py @@ -0,0 +1,1979 @@ +# -*- 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/SHA-256, MGF1 with SHA-1/SHA-256, 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]. + + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. + 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. The data to sign. It can't be supplied if + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] + is supplied. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]. + 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. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] protection + level is supported. + """ + + 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..d7527817 --- /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==4.0.1", "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..df767766 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py @@ -0,0 +1,208 @@ +#! /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_ekm_connection': ('parent', 'ekm_connection_id', 'ekm_connection', ), + 'create_import_job': ('parent', 'import_job_id', 'import_job', ), + 'create_key_ring': ('parent', 'key_ring_id', 'key_ring', ), + 'decrypt': ('name', 'ciphertext', 'additional_authenticated_data', 'ciphertext_crc32c', 'additional_authenticated_data_crc32c', ), + '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_ekm_connection': ('name', ), + 'get_import_job': ('name', ), + 'get_key_ring': ('name', ), + 'get_public_key': ('name', ), + 'import_crypto_key_version': ('parent', 'algorithm', 'import_job', 'crypto_key_version', 'rsa_aes_wrapped_key', ), + 'list_crypto_keys': ('parent', 'page_size', 'page_token', 'version_view', 'filter', 'order_by', ), + 'list_crypto_key_versions': ('parent', 'page_size', 'page_token', 'view', 'filter', 'order_by', ), + 'list_ekm_connections': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_import_jobs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_key_rings': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'mac_sign': ('name', 'data', 'data_crc32c', ), + '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', ), + 'update_ekm_connection': ('ekm_connection', '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_ekm_service.py b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_ekm_service.py new file mode 100644 index 00000000..85ad0f9d --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_ekm_service.py @@ -0,0 +1,2765 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.kms_v1.services.ekm_service import EkmServiceAsyncClient +from google.cloud.kms_v1.services.ekm_service import EkmServiceClient +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.services.ekm_service import transports +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EkmServiceClient._get_default_mtls_endpoint(None) is None + assert EkmServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EkmServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EkmServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EkmServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EkmServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + EkmServiceClient, + EkmServiceAsyncClient, +]) +def test_ekm_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudkms.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EkmServiceGrpcTransport, "grpc"), + (transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_ekm_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class", [ + EkmServiceClient, + EkmServiceAsyncClient, +]) +def test_ekm_service_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudkms.googleapis.com:443' + + +def test_ekm_service_client_get_transport_class(): + transport = EkmServiceClient.get_transport_class() + available_transports = [ + transports.EkmServiceGrpcTransport, + ] + assert transport in available_transports + + transport = EkmServiceClient.get_transport_class("grpc") + assert transport == transports.EkmServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient)) +@mock.patch.object(EkmServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceAsyncClient)) +def test_ekm_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(EkmServiceClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(EkmServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "true"), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "false"), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient)) +@mock.patch.object(EkmServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_ekm_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class", [ + EkmServiceClient, EkmServiceAsyncClient +]) +@mock.patch.object(EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient)) +@mock.patch.object(EkmServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceAsyncClient)) +def test_ekm_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_ekm_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_ekm_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_ekm_service_client_client_options_from_dict(): + with mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EkmServiceClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_ekm_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.ListEkmConnectionsRequest, + dict, +]) +def test_list_ekm_connections(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.ListEkmConnectionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEkmConnectionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_ekm_connections_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + client.list_ekm_connections() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.ListEkmConnectionsRequest() + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async(transport: str = 'grpc_asyncio', request_type=ekm_service.ListEkmConnectionsRequest): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.ListEkmConnectionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEkmConnectionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_from_dict(): + await test_list_ekm_connections_async(request_type=dict) + + +def test_list_ekm_connections_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.ListEkmConnectionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + call.return_value = ekm_service.ListEkmConnectionsResponse() + client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_ekm_connections_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.ListEkmConnectionsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse()) + await client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_list_ekm_connections_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_ekm_connections( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_ekm_connections_flattened_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_ekm_connections( + ekm_service.ListEkmConnectionsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_ekm_connections_flattened_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_ekm_connections( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_ekm_connections_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_ekm_connections( + ekm_service.ListEkmConnectionsRequest(), + parent='parent_value', + ) + + +def test_list_ekm_connections_pager(transport_name: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_ekm_connections(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, ekm_service.EkmConnection) + for i in results) +def test_list_ekm_connections_pages(transport_name: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + pages = list(client.list_ekm_connections(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_pager(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_ekm_connections(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, ekm_service.EkmConnection) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_pages(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_ekm_connections(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + ekm_service.GetEkmConnectionRequest, + dict, +]) +def test_get_ekm_connection(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + ) + response = client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.GetEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +def test_get_ekm_connection_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + client.get_ekm_connection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.GetEkmConnectionRequest() + + +@pytest.mark.asyncio +async def test_get_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.GetEkmConnectionRequest): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + )) + response = await client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.GetEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_ekm_connection_async_from_dict(): + await test_get_ekm_connection_async(request_type=dict) + + +def test_get_ekm_connection_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.GetEkmConnectionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.GetEkmConnectionRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + await client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name/value', + ) in kw['metadata'] + + +def test_get_ekm_connection_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_ekm_connection( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_ekm_connection_flattened_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_ekm_connection( + ekm_service.GetEkmConnectionRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_ekm_connection( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_ekm_connection( + ekm_service.GetEkmConnectionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.CreateEkmConnectionRequest, + dict, +]) +def test_create_ekm_connection(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + ) + response = client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.CreateEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +def test_create_ekm_connection_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + client.create_ekm_connection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.CreateEkmConnectionRequest() + + +@pytest.mark.asyncio +async def test_create_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.CreateEkmConnectionRequest): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + )) + response = await client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.CreateEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_create_ekm_connection_async_from_dict(): + await test_create_ekm_connection_async(request_type=dict) + + +def test_create_ekm_connection_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.CreateEkmConnectionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.CreateEkmConnectionRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + await client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent/value', + ) in kw['metadata'] + + +def test_create_ekm_connection_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_ekm_connection( + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].ekm_connection_id + mock_val = 'ekm_connection_id_value' + assert arg == mock_val + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name='name_value') + assert arg == mock_val + + +def test_create_ekm_connection_flattened_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_ekm_connection( + ekm_service.CreateEkmConnectionRequest(), + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_ekm_connection( + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(name='name_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].ekm_connection_id + mock_val = 'ekm_connection_id_value' + assert arg == mock_val + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name='name_value') + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_ekm_connection( + ekm_service.CreateEkmConnectionRequest(), + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.UpdateEkmConnectionRequest, + dict, +]) +def test_update_ekm_connection(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + ) + response = client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.UpdateEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +def test_update_ekm_connection_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + client.update_ekm_connection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.UpdateEkmConnectionRequest() + + +@pytest.mark.asyncio +async def test_update_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.UpdateEkmConnectionRequest): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + )) + response = await client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.UpdateEkmConnectionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_update_ekm_connection_async_from_dict(): + await test_update_ekm_connection_async(request_type=dict) + + +def test_update_ekm_connection_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.UpdateEkmConnectionRequest() + + request.ekm_connection.name = 'ekm_connection.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'ekm_connection.name=ekm_connection.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.UpdateEkmConnectionRequest() + + request.ekm_connection.name = 'ekm_connection.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + await client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'ekm_connection.name=ekm_connection.name/value', + ) in kw['metadata'] + + +def test_update_ekm_connection_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_ekm_connection( + ekm_connection=ekm_service.EkmConnection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_ekm_connection_flattened_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_ekm_connection( + ekm_service.UpdateEkmConnectionRequest(), + ekm_connection=ekm_service.EkmConnection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_ekm_connection( + ekm_connection=ekm_service.EkmConnection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_ekm_connection( + ekm_service.UpdateEkmConnectionRequest(), + ekm_connection=ekm_service.EkmConnection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EkmServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EkmServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceGrpcAsyncIOTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EkmServiceGrpcTransport, + ) + +def test_ekm_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EkmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_ekm_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EkmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_ekm_connections', + 'get_ekm_connection', + 'create_ekm_connection', + 'update_ekm_connection', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + +def test_ekm_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EkmServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id="octopus", + ) + + +def test_ekm_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EkmServiceTransport() + adc.assert_called_once() + + +def test_ekm_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EkmServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceGrpcAsyncIOTransport, + ], +) +def test_ekm_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloudkms',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EkmServiceGrpcTransport, grpc_helpers), + (transports.EkmServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) +def test_ekm_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + + +def test_ekm_service_host_no_port(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), + ) + assert client.transport._host == 'cloudkms.googleapis.com:443' + + +def test_ekm_service_host_with_port(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), + ) + assert client.transport._host == 'cloudkms.googleapis.com:8000' + +def test_ekm_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EkmServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_ekm_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EkmServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) +def test_ekm_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) +def test_ekm_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_ekm_connection_path(): + project = "squid" + location = "clam" + ekm_connection = "whelk" + expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format(project=project, location=location, ekm_connection=ekm_connection, ) + actual = EkmServiceClient.ekm_connection_path(project, location, ekm_connection) + assert expected == actual + + +def test_parse_ekm_connection_path(): + expected = { + "project": "octopus", + "location": "oyster", + "ekm_connection": "nudibranch", + } + path = EkmServiceClient.ekm_connection_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_ekm_connection_path(path) + assert expected == actual + +def test_service_path(): + project = "cuttlefish" + location = "mussel" + namespace = "winkle" + service = "nautilus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + actual = EkmServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "scallop", + "location": "abalone", + "namespace": "squid", + "service": "clam", + } + path = EkmServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EkmServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = EkmServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = EkmServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = EkmServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EkmServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = EkmServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = EkmServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = EkmServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = EkmServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = EkmServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.EkmServiceTransport, '_prep_wrapped_messages') as prep: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EkmServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = EkmServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_set_iam_policy(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EkmServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'grpc', + ] + for transport in transports: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/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..c9b24e3b --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -0,0 +1,8985 @@ +# -*- 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,grpc_helpers", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", grpc_helpers), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_key_management_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + +def test_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("client_class,transport_class,transport_name,grpc_helpers", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", grpc_helpers), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_key_management_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListKeyRingsRequest, + dict, +]) +def test_list_key_rings(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + 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, + crypto_key_backend='crypto_key_backend_value', + 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 + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +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, + crypto_key_backend='crypto_key_backend_value', + )) + 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 + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@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, + crypto_key_backend='crypto_key_backend_value', + 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 + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +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, + crypto_key_backend='crypto_key_backend_value', + )) + 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 + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@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, + crypto_key_backend='crypto_key_backend_value', + 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 + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +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, + crypto_key_backend='crypto_key_backend_value', + )) + 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 + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@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, + crypto_key_backend='crypto_key_backend_value', + 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 + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +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, + crypto_key_backend='crypto_key_backend_value', + )) + 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 + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@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 8b74820445f12f379e30be1fdf31e4c2c385b025 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Thu, 3 Feb 2022 01:52:23 +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 --- .../v1/docs => docs}/kms_v1/ekm_service.rst | 0 docs/kms_v1/services.rst | 1 + google/cloud/kms/__init__.py | 18 + google/cloud/kms_v1/__init__.py | 18 + google/cloud/kms_v1/gapic_metadata.json | 54 + .../kms_v1/services/ekm_service/__init__.py | 4 +- .../services/ekm_service/async_client.py | 254 +- .../kms_v1/services/ekm_service/client.py | 340 +- .../kms_v1/services/ekm_service/pagers.py | 46 +- .../ekm_service/transports/__init__.py | 10 +- .../services/ekm_service/transports/base.py | 136 +- .../services/ekm_service/transports/grpc.py | 117 +- .../ekm_service/transports/grpc_asyncio.py | 121 +- .../key_management_service/async_client.py | 151 +- .../services/key_management_service/client.py | 151 +- .../key_management_service/transports/grpc.py | 5 +- .../transports/grpc_asyncio.py | 5 +- google/cloud/kms_v1/types/__init__.py | 16 + .../cloud/kms_v1/types/ekm_service.py | 168 +- google/cloud/kms_v1/types/resources.py | 58 +- google/cloud/kms_v1/types/service.py | 21 +- 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 | 7 - owl-bot-staging/v1/docs/kms_v1/types.rst | 7 - .../v1/google/cloud/kms/__init__.py | 137 - owl-bot-staging/v1/google/cloud/kms/py.typed | 2 - .../v1/google/cloud/kms_v1/__init__.py | 138 - .../google/cloud/kms_v1/gapic_metadata.json | 337 - .../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 | 3197 ------ .../services/key_management_service/client.py | 3267 ------ .../services/key_management_service/pagers.py | 503 - .../transports/__init__.py | 33 - .../key_management_service/transports/base.py | 696 -- .../key_management_service/transports/grpc.py | 1118 -- .../transports/grpc_asyncio.py | 1123 -- .../v1/google/cloud/kms_v1/types/__init__.py | 134 - .../v1/google/cloud/kms_v1/types/resources.py | 916 -- .../v1/google/cloud/kms_v1/types/service.py | 1979 ---- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../v1/scripts/fixup_kms_v1_keywords.py | 208 - 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 | 8985 ----------------- scripts/fixup_kms_v1_keywords.py | 4 + .../unit/gapic/kms_v1/test_ekm_service.py | 1321 +-- .../kms_v1/test_key_management_service.py | 92 +- 58 files changed, 1720 insertions(+), 24932 deletions(-) rename {owl-bot-staging/v1/docs => docs}/kms_v1/ekm_service.rst (100%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/services/ekm_service/__init__.py (92%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/services/ekm_service/async_client.py (86%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/services/ekm_service/client.py (84%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/services/ekm_service/pagers.py (85%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/services/ekm_service/transports/__init__.py (81%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/services/ekm_service/transports/base.py (69%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/services/ekm_service/transports/grpc.py (85%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py (85%) rename {owl-bot-staging/v1/google => google}/cloud/kms_v1/types/ekm_service.py (78%) 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 rename {owl-bot-staging/v1/tests => tests}/unit/gapic/kms_v1/test_ekm_service.py (72%) diff --git a/owl-bot-staging/v1/docs/kms_v1/ekm_service.rst b/docs/kms_v1/ekm_service.rst similarity index 100% rename from owl-bot-staging/v1/docs/kms_v1/ekm_service.rst rename to docs/kms_v1/ekm_service.rst diff --git a/docs/kms_v1/services.rst b/docs/kms_v1/services.rst index 1edbf1d6..141ddfe4 100644 --- a/docs/kms_v1/services.rst +++ b/docs/kms_v1/services.rst @@ -3,4 +3,5 @@ Services for Google Cloud Kms v1 API .. toctree:: :maxdepth: 2 + ekm_service key_management_service diff --git a/google/cloud/kms/__init__.py b/google/cloud/kms/__init__.py index d2f8e067..eaca213b 100644 --- a/google/cloud/kms/__init__.py +++ b/google/cloud/kms/__init__.py @@ -14,6 +14,8 @@ # limitations under the License. # +from google.cloud.kms_v1.services.ekm_service.client import EkmServiceClient +from google.cloud.kms_v1.services.ekm_service.async_client import EkmServiceAsyncClient from google.cloud.kms_v1.services.key_management_service.client import ( KeyManagementServiceClient, ) @@ -21,6 +23,13 @@ KeyManagementServiceAsyncClient, ) +from google.cloud.kms_v1.types.ekm_service import Certificate +from google.cloud.kms_v1.types.ekm_service import CreateEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import EkmConnection +from google.cloud.kms_v1.types.ekm_service import GetEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsRequest +from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsResponse +from google.cloud.kms_v1.types.ekm_service import UpdateEkmConnectionRequest from google.cloud.kms_v1.types.resources import CryptoKey from google.cloud.kms_v1.types.resources import CryptoKeyVersion from google.cloud.kms_v1.types.resources import CryptoKeyVersionTemplate @@ -71,8 +80,17 @@ from google.cloud.kms_v1.types.service import UpdateCryptoKeyVersionRequest __all__ = ( + "EkmServiceClient", + "EkmServiceAsyncClient", "KeyManagementServiceClient", "KeyManagementServiceAsyncClient", + "Certificate", + "CreateEkmConnectionRequest", + "EkmConnection", + "GetEkmConnectionRequest", + "ListEkmConnectionsRequest", + "ListEkmConnectionsResponse", + "UpdateEkmConnectionRequest", "CryptoKey", "CryptoKeyVersion", "CryptoKeyVersionTemplate", diff --git a/google/cloud/kms_v1/__init__.py b/google/cloud/kms_v1/__init__.py index 42ba567c..cc0291a7 100644 --- a/google/cloud/kms_v1/__init__.py +++ b/google/cloud/kms_v1/__init__.py @@ -14,9 +14,18 @@ # limitations under the License. # +from .services.ekm_service import EkmServiceClient +from .services.ekm_service import EkmServiceAsyncClient from .services.key_management_service import KeyManagementServiceClient from .services.key_management_service import KeyManagementServiceAsyncClient +from .types.ekm_service import Certificate +from .types.ekm_service import CreateEkmConnectionRequest +from .types.ekm_service import EkmConnection +from .types.ekm_service import GetEkmConnectionRequest +from .types.ekm_service import ListEkmConnectionsRequest +from .types.ekm_service import ListEkmConnectionsResponse +from .types.ekm_service import UpdateEkmConnectionRequest from .types.resources import CryptoKey from .types.resources import CryptoKeyVersion from .types.resources import CryptoKeyVersionTemplate @@ -67,13 +76,16 @@ from .types.service import UpdateCryptoKeyVersionRequest __all__ = ( + "EkmServiceAsyncClient", "KeyManagementServiceAsyncClient", "AsymmetricDecryptRequest", "AsymmetricDecryptResponse", "AsymmetricSignRequest", "AsymmetricSignResponse", + "Certificate", "CreateCryptoKeyRequest", "CreateCryptoKeyVersionRequest", + "CreateEkmConnectionRequest", "CreateImportJobRequest", "CreateKeyRingRequest", "CryptoKey", @@ -83,6 +95,8 @@ "DecryptResponse", "DestroyCryptoKeyVersionRequest", "Digest", + "EkmConnection", + "EkmServiceClient", "EncryptRequest", "EncryptResponse", "ExternalProtectionLevelOptions", @@ -90,6 +104,7 @@ "GenerateRandomBytesResponse", "GetCryptoKeyRequest", "GetCryptoKeyVersionRequest", + "GetEkmConnectionRequest", "GetImportJobRequest", "GetKeyRingRequest", "GetPublicKeyRequest", @@ -102,6 +117,8 @@ "ListCryptoKeyVersionsResponse", "ListCryptoKeysRequest", "ListCryptoKeysResponse", + "ListEkmConnectionsRequest", + "ListEkmConnectionsResponse", "ListImportJobsRequest", "ListImportJobsResponse", "ListKeyRingsRequest", @@ -117,4 +134,5 @@ "UpdateCryptoKeyPrimaryVersionRequest", "UpdateCryptoKeyRequest", "UpdateCryptoKeyVersionRequest", + "UpdateEkmConnectionRequest", ) diff --git a/google/cloud/kms_v1/gapic_metadata.json b/google/cloud/kms_v1/gapic_metadata.json index 582da425..3b830979 100644 --- a/google/cloud/kms_v1/gapic_metadata.json +++ b/google/cloud/kms_v1/gapic_metadata.json @@ -5,6 +5,60 @@ "protoPackage": "google.cloud.kms.v1", "schema": "1.0", "services": { + "EkmService": { + "clients": { + "grpc": { + "libraryClient": "EkmServiceClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EkmServiceAsyncClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + } + } + } + } + }, "KeyManagementService": { "clients": { "grpc": { diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/__init__.py b/google/cloud/kms_v1/services/ekm_service/__init__.py similarity index 92% rename from owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/__init__.py rename to google/cloud/kms_v1/services/ekm_service/__init__.py index 61e2ac84..211dc4ab 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/__init__.py +++ b/google/cloud/kms_v1/services/ekm_service/__init__.py @@ -17,6 +17,6 @@ from .async_client import EkmServiceAsyncClient __all__ = ( - 'EkmServiceClient', - 'EkmServiceAsyncClient', + "EkmServiceClient", + "EkmServiceAsyncClient", ) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/async_client.py b/google/cloud/kms_v1/services/ekm_service/async_client.py similarity index 86% rename from owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/async_client.py rename to google/cloud/kms_v1/services/ekm_service/async_client.py index 142eccdf..9aab6c69 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/async_client.py +++ b/google/cloud/kms_v1/services/ekm_service/async_client.py @@ -23,8 +23,8 @@ 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.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] @@ -60,22 +60,31 @@ class EkmServiceAsyncClient: parse_ekm_connection_path = staticmethod(EkmServiceClient.parse_ekm_connection_path) service_path = staticmethod(EkmServiceClient.service_path) parse_service_path = staticmethod(EkmServiceClient.parse_service_path) - common_billing_account_path = staticmethod(EkmServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EkmServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + EkmServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + EkmServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(EkmServiceClient.common_folder_path) parse_common_folder_path = staticmethod(EkmServiceClient.parse_common_folder_path) common_organization_path = staticmethod(EkmServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(EkmServiceClient.parse_common_organization_path) + parse_common_organization_path = staticmethod( + EkmServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(EkmServiceClient.common_project_path) parse_common_project_path = staticmethod(EkmServiceClient.parse_common_project_path) common_location_path = staticmethod(EkmServiceClient.common_location_path) - parse_common_location_path = staticmethod(EkmServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + EkmServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. + Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. @@ -91,6 +100,7 @@ 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. @@ -105,7 +115,9 @@ 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): + 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: @@ -124,6 +136,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOption 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 @@ -147,16 +160,21 @@ def transport(self) -> EkmServiceTransport: """ return self._client.transport - get_transport_class = functools.partial(type(EkmServiceClient).get_transport_class, type(EkmServiceClient)) + get_transport_class = functools.partial( + type(EkmServiceClient).get_transport_class, type(EkmServiceClient) + ) - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, EkmServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, EkmServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the ekm service client. + Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These @@ -192,19 +210,20 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - async def list_ekm_connections(self, - request: Union[ekm_service.ListEkmConnectionsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEkmConnectionsAsyncPager: + async def list_ekm_connections( + self, + request: Union[ekm_service.ListEkmConnectionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEkmConnectionsAsyncPager: r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + Args: request (Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]): The request object. Request message for @@ -238,8 +257,10 @@ async def list_ekm_connections(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = ekm_service.ListEkmConnectionsRequest(request) @@ -253,7 +274,10 @@ async def list_ekm_connections(self, rpc = gapic_v1.method_async.wrap_method( self._client._transport.list_ekm_connections, default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), @@ -266,42 +290,34 @@ async def list_ekm_connections(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__aiter__` convenience method. response = pagers.ListEkmConnectionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response - async def get_ekm_connection(self, - request: Union[ekm_service.GetEkmConnectionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> ekm_service.EkmConnection: + async def get_ekm_connection( + self, + request: Union[ekm_service.GetEkmConnectionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: r"""Returns metadata for a given [EkmConnection][google.cloud.kms.v1.EkmConnection]. + Args: request (Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]): The request object. Request message for @@ -342,8 +358,10 @@ async def get_ekm_connection(self, # 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.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = ekm_service.GetEkmConnectionRequest(request) @@ -357,7 +375,10 @@ async def get_ekm_connection(self, rpc = gapic_v1.method_async.wrap_method( self._client._transport.get_ekm_connection, default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), @@ -370,35 +391,30 @@ async def get_ekm_connection(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def create_ekm_connection(self, - request: Union[ekm_service.CreateEkmConnectionRequest, dict] = None, - *, - parent: str = None, - ekm_connection_id: str = None, - ekm_connection: ekm_service.EkmConnection = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> ekm_service.EkmConnection: + async def create_ekm_connection( + self, + request: Union[ekm_service.CreateEkmConnectionRequest, dict] = None, + *, + parent: str = None, + ekm_connection_id: str = None, + ekm_connection: ekm_service.EkmConnection = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] in a given Project and Location. + Args: request (Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]): The request object. Request message for @@ -454,8 +470,10 @@ async def create_ekm_connection(self, # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, ekm_connection_id, ekm_connection]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = ekm_service.CreateEkmConnectionRequest(request) @@ -473,7 +491,10 @@ async def create_ekm_connection(self, rpc = gapic_v1.method_async.wrap_method( self._client._transport.create_ekm_connection, default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), @@ -486,34 +507,29 @@ async def create_ekm_connection(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - async def update_ekm_connection(self, - request: Union[ekm_service.UpdateEkmConnectionRequest, dict] = None, - *, - ekm_connection: ekm_service.EkmConnection = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> ekm_service.EkmConnection: + async def update_ekm_connection( + self, + request: Union[ekm_service.UpdateEkmConnectionRequest, dict] = None, + *, + ekm_connection: ekm_service.EkmConnection = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s metadata. + Args: request (Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]): The request object. Request message for @@ -560,8 +576,10 @@ async def update_ekm_connection(self, # gotten any keyword arguments that map to the request. has_flattened_params = any([ekm_connection, update_mask]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = ekm_service.UpdateEkmConnectionRequest(request) @@ -577,7 +595,10 @@ async def update_ekm_connection(self, rpc = gapic_v1.method_async.wrap_method( self._client._transport.update_ekm_connection, default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), @@ -590,18 +611,13 @@ async def update_ekm_connection(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("ekm_connection.name", request.ekm_connection.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("ekm_connection.name", request.ekm_connection.name),) + ), ) # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -618,6 +634,7 @@ async def set_iam_policy( Replaces any existing policy. + Args: request (:class:`~.policy_pb2.SetIamPolicyRequest`): The request object. Request message for `SetIamPolicy` @@ -642,8 +659,9 @@ async def set_iam_policy( expression that further constrains the role binding based on attributes about the request and/or target resource. - **JSON Example** - :: + + **JSON Example**:: + { "bindings": [ { @@ -667,8 +685,9 @@ async def set_iam_policy( } ] } - **YAML Example** - :: + + **YAML Example**:: + bindings: - members: - user:mike@example.com @@ -683,6 +702,7 @@ async def set_iam_policy( 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 `__. @@ -727,6 +747,7 @@ async def get_iam_policy( 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` @@ -751,8 +772,9 @@ async def get_iam_policy( expression that further constrains the role binding based on attributes about the request and/or target resource. - **JSON Example** - :: + + **JSON Example**:: + { "bindings": [ { @@ -776,8 +798,9 @@ async def get_iam_policy( } ] } - **YAML Example** - :: + + **YAML Example**:: + bindings: - members: - user:mike@example.com @@ -792,6 +815,7 @@ async def get_iam_policy( 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 `__. @@ -837,6 +861,7 @@ async def test_iam_permissions( 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 @@ -883,16 +908,13 @@ async def __aenter__(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, + gapic_version=pkg_resources.get_distribution("google-cloud-kms",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "EkmServiceAsyncClient", -) +__all__ = ("EkmServiceAsyncClient",) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/client.py b/google/cloud/kms_v1/services/ekm_service/client.py similarity index 84% rename from owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/client.py rename to google/cloud/kms_v1/services/ekm_service/client.py index 7abc4198..4b8e4374 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/client.py +++ b/google/cloud/kms_v1/services/ekm_service/client.py @@ -23,11 +23,11 @@ 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 +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] @@ -52,15 +52,15 @@ class EkmServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] _transport_registry["grpc"] = EkmServiceGrpcTransport _transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport - def get_transport_class(cls, - label: str = None, - ) -> Type[EkmServiceTransport]: + def get_transport_class(cls, label: str = None,) -> Type[EkmServiceTransport]: """Returns an appropriate transport class. + Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. @@ -92,6 +92,7 @@ def _get_default_mtls_endpoint(api_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: @@ -126,6 +127,7 @@ 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. @@ -143,6 +145,7 @@ 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. @@ -152,8 +155,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: EkmServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -170,84 +172,100 @@ def transport(self) -> EkmServiceTransport: return self._transport @staticmethod - def ekm_connection_path(project: str,location: str,ekm_connection: str,) -> str: + def ekm_connection_path(project: str, location: str, ekm_connection: str,) -> str: """Returns a fully-qualified ekm_connection string.""" - return "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format(project=project, location=location, ekm_connection=ekm_connection, ) + return "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format( + project=project, location=location, ekm_connection=ekm_connection, + ) @staticmethod - def parse_ekm_connection_path(path: str) -> Dict[str,str]: + def parse_ekm_connection_path(path: str) -> Dict[str, str]: """Parses a ekm_connection path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/ekmConnections/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/ekmConnections/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def service_path(project: str,location: str,namespace: str,service: str,) -> str: + def service_path(project: str, location: str, namespace: str, service: str,) -> str: """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: + def parse_service_path(path: str) -> Dict[str, str]: """Parses a service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path(folder: str,) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format(folder=folder,) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path(organization: str,) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format(organization=organization,) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path(project: str,) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format(project=project,) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + 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): + 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: @@ -266,6 +284,7 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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 @@ -283,9 +302,13 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio 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`") + 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`") + 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 @@ -298,21 +321,26 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT return api_endpoint, client_cert_source - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EkmServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EkmServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the ekm service client. + Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These @@ -353,11 +381,15 @@ def __init__(self, *, 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_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") + 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 @@ -365,8 +397,10 @@ def __init__(self, *, if isinstance(transport, EkmServiceTransport): # transport is a EkmServiceTransport instance. if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + 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 " @@ -376,8 +410,12 @@ def __init__(self, *, 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) + 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( @@ -391,16 +429,18 @@ def __init__(self, *, always_use_jwt_access=True, ) - def list_ekm_connections(self, - request: Union[ekm_service.ListEkmConnectionsRequest, dict] = None, - *, - parent: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEkmConnectionsPager: + def list_ekm_connections( + self, + request: Union[ekm_service.ListEkmConnectionsRequest, dict] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEkmConnectionsPager: r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + Args: request (Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]): The request object. Request message for @@ -434,8 +474,10 @@ def list_ekm_connections(self, # 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.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a ekm_service.ListEkmConnectionsRequest. @@ -455,42 +497,34 @@ def list_ekm_connections(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListEkmConnectionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response - def get_ekm_connection(self, - request: Union[ekm_service.GetEkmConnectionRequest, dict] = None, - *, - name: str = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> ekm_service.EkmConnection: + def get_ekm_connection( + self, + request: Union[ekm_service.GetEkmConnectionRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: r"""Returns metadata for a given [EkmConnection][google.cloud.kms.v1.EkmConnection]. + Args: request (Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]): The request object. Request message for @@ -531,8 +565,10 @@ def get_ekm_connection(self, # 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.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a ekm_service.GetEkmConnectionRequest. @@ -552,35 +588,30 @@ def get_ekm_connection(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def create_ekm_connection(self, - request: Union[ekm_service.CreateEkmConnectionRequest, dict] = None, - *, - parent: str = None, - ekm_connection_id: str = None, - ekm_connection: ekm_service.EkmConnection = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> ekm_service.EkmConnection: + def create_ekm_connection( + self, + request: Union[ekm_service.CreateEkmConnectionRequest, dict] = None, + *, + parent: str = None, + ekm_connection_id: str = None, + ekm_connection: ekm_service.EkmConnection = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] in a given Project and Location. + Args: request (Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]): The request object. Request message for @@ -636,8 +667,10 @@ def create_ekm_connection(self, # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, ekm_connection_id, ekm_connection]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a ekm_service.CreateEkmConnectionRequest. @@ -661,34 +694,29 @@ def create_ekm_connection(self, # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response - def update_ekm_connection(self, - request: Union[ekm_service.UpdateEkmConnectionRequest, dict] = None, - *, - ekm_connection: ekm_service.EkmConnection = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> ekm_service.EkmConnection: + def update_ekm_connection( + self, + request: Union[ekm_service.UpdateEkmConnectionRequest, dict] = None, + *, + ekm_connection: ekm_service.EkmConnection = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s metadata. + Args: request (Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]): The request object. Request message for @@ -735,8 +763,10 @@ def update_ekm_connection(self, # gotten any keyword arguments that map to the request. has_flattened_params = any([ekm_connection, update_mask]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a ekm_service.UpdateEkmConnectionRequest. @@ -758,18 +788,13 @@ def update_ekm_connection(self, # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("ekm_connection.name", request.ekm_connection.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("ekm_connection.name", request.ekm_connection.name),) + ), ) # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -799,6 +824,7 @@ def set_iam_policy( Replaces any existing policy. + Args: request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): The request object. Request message for `SetIamPolicy` @@ -823,8 +849,9 @@ def set_iam_policy( expression that further constrains the role binding based on attributes about the request and/or target resource. - **JSON Example** - :: + + **JSON Example**:: + { "bindings": [ { @@ -848,8 +875,9 @@ def set_iam_policy( } ] } - **YAML Example** - :: + + **YAML Example**:: + bindings: - members: - user:mike@example.com @@ -864,6 +892,7 @@ def set_iam_policy( 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 `__. @@ -886,13 +915,11 @@ def set_iam_policy( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -910,6 +937,7 @@ def get_iam_policy( 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` @@ -934,8 +962,9 @@ def get_iam_policy( expression that further constrains the role binding based on attributes about the request and/or target resource. - **JSON Example** - :: + + **JSON Example**:: + { "bindings": [ { @@ -959,8 +988,9 @@ def get_iam_policy( } ] } - **YAML Example** - :: + + **YAML Example**:: + bindings: - members: - user:mike@example.com @@ -975,6 +1005,7 @@ def get_iam_policy( 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 `__. @@ -997,13 +1028,11 @@ def get_iam_policy( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1022,6 +1051,7 @@ def test_iam_permissions( 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 @@ -1053,13 +1083,11 @@ def test_iam_permissions( # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), ) # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1067,14 +1095,10 @@ def test_iam_permissions( try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-kms", - ).version, + gapic_version=pkg_resources.get_distribution("google-cloud-kms",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() -__all__ = ( - "EkmServiceClient", -) +__all__ = ("EkmServiceClient",) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/pagers.py b/google/cloud/kms_v1/services/ekm_service/pagers.py similarity index 85% rename from owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/pagers.py rename to google/cloud/kms_v1/services/ekm_service/pagers.py index 7d738d0d..c4134305 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/pagers.py +++ b/google/cloud/kms_v1/services/ekm_service/pagers.py @@ -13,7 +13,16 @@ # 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 typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Sequence, + Tuple, + Optional, + Iterator, +) from google.cloud.kms_v1.types import ekm_service @@ -35,12 +44,15 @@ class ListEkmConnectionsPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - def __init__(self, - method: Callable[..., ekm_service.ListEkmConnectionsResponse], - request: ekm_service.ListEkmConnectionsRequest, - response: ekm_service.ListEkmConnectionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): + + def __init__( + self, + method: Callable[..., ekm_service.ListEkmConnectionsResponse], + request: ekm_service.ListEkmConnectionsRequest, + response: ekm_service.ListEkmConnectionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiate the pager. Args: @@ -74,7 +86,7 @@ def __iter__(self) -> Iterator[ekm_service.EkmConnection]: yield from page.ekm_connections def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListEkmConnectionsAsyncPager: @@ -94,12 +106,15 @@ class ListEkmConnectionsAsyncPager: attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ - def __init__(self, - method: Callable[..., Awaitable[ekm_service.ListEkmConnectionsResponse]], - request: ekm_service.ListEkmConnectionsRequest, - response: ekm_service.ListEkmConnectionsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): + + def __init__( + self, + method: Callable[..., Awaitable[ekm_service.ListEkmConnectionsResponse]], + request: ekm_service.ListEkmConnectionsRequest, + response: ekm_service.ListEkmConnectionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiates the pager. Args: @@ -127,6 +142,7 @@ async def pages(self) -> AsyncIterator[ekm_service.ListEkmConnectionsResponse]: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response + def __aiter__(self) -> AsyncIterator[ekm_service.EkmConnection]: async def async_generator(): async for page in self.pages: @@ -136,4 +152,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py b/google/cloud/kms_v1/services/ekm_service/transports/__init__.py similarity index 81% rename from owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py rename to google/cloud/kms_v1/services/ekm_service/transports/__init__.py index 37307beb..ee2056a3 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py +++ b/google/cloud/kms_v1/services/ekm_service/transports/__init__.py @@ -23,11 +23,11 @@ # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] -_transport_registry['grpc'] = EkmServiceGrpcTransport -_transport_registry['grpc_asyncio'] = EkmServiceGrpcAsyncIOTransport +_transport_registry["grpc"] = EkmServiceGrpcTransport +_transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport __all__ = ( - 'EkmServiceTransport', - 'EkmServiceGrpcTransport', - 'EkmServiceGrpcAsyncIOTransport', + "EkmServiceTransport", + "EkmServiceGrpcTransport", + "EkmServiceGrpcAsyncIOTransport", ) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py b/google/cloud/kms_v1/services/ekm_service/transports/base.py similarity index 69% rename from owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py rename to google/cloud/kms_v1/services/ekm_service/transports/base.py index d4524247..0ab2f36c 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py +++ b/google/cloud/kms_v1/services/ekm_service/transports/base.py @@ -23,7 +23,7 @@ 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.oauth2 import service_account # type: ignore from google.cloud.kms_v1.types import ekm_service from google.iam.v1 import iam_policy_pb2 # type: ignore @@ -31,9 +31,7 @@ try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-kms', - ).version, + gapic_version=pkg_resources.get_distribution("google-cloud-kms",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() @@ -43,22 +41,24 @@ class EkmServiceTransport(abc.ABC): """Abstract transport class for EkmService.""" AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", ) - DEFAULT_HOST: str = 'cloudkms.googleapis.com' + 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: + 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: @@ -84,8 +84,8 @@ def __init__( be used for service account credentials. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' + if ":" not in host: + host += ":443" self._host = host scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} @@ -96,19 +96,25 @@ def __init__( # 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") + 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 - ) + 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) + 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"): + 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. @@ -120,7 +126,10 @@ def _prep_wrapped_messages(self, client_info): self.list_ekm_connections: gapic_v1.method.wrap_method( self.list_ekm_connections, default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), @@ -132,7 +141,10 @@ def _prep_wrapped_messages(self, client_info): self.get_ekm_connection: gapic_v1.method.wrap_method( self.get_ekm_connection, default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), @@ -144,7 +156,10 @@ def _prep_wrapped_messages(self, client_info): self.create_ekm_connection: gapic_v1.method.wrap_method( self.create_ekm_connection, default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), @@ -156,7 +171,10 @@ def _prep_wrapped_messages(self, client_info): self.update_ekm_connection: gapic_v1.method.wrap_method( self.update_ekm_connection, default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), @@ -165,7 +183,7 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - } + } def close(self): """Closes resources associated with the transport. @@ -177,39 +195,42 @@ def close(self): raise NotImplementedError() @property - def list_ekm_connections(self) -> Callable[ - [ekm_service.ListEkmConnectionsRequest], - Union[ - ekm_service.ListEkmConnectionsResponse, - Awaitable[ekm_service.ListEkmConnectionsResponse] - ]]: + def list_ekm_connections( + self, + ) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + Union[ + ekm_service.ListEkmConnectionsResponse, + Awaitable[ekm_service.ListEkmConnectionsResponse], + ], + ]: raise NotImplementedError() @property - def get_ekm_connection(self) -> Callable[ - [ekm_service.GetEkmConnectionRequest], - Union[ - ekm_service.EkmConnection, - Awaitable[ekm_service.EkmConnection] - ]]: + def get_ekm_connection( + self, + ) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + Union[ekm_service.EkmConnection, Awaitable[ekm_service.EkmConnection]], + ]: raise NotImplementedError() @property - def create_ekm_connection(self) -> Callable[ - [ekm_service.CreateEkmConnectionRequest], - Union[ - ekm_service.EkmConnection, - Awaitable[ekm_service.EkmConnection] - ]]: + def create_ekm_connection( + self, + ) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + Union[ekm_service.EkmConnection, Awaitable[ekm_service.EkmConnection]], + ]: raise NotImplementedError() @property - def update_ekm_connection(self) -> Callable[ - [ekm_service.UpdateEkmConnectionRequest], - Union[ - ekm_service.EkmConnection, - Awaitable[ekm_service.EkmConnection] - ]]: + def update_ekm_connection( + self, + ) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + Union[ekm_service.EkmConnection, Awaitable[ekm_service.EkmConnection]], + ]: raise NotImplementedError() @property @@ -242,6 +263,5 @@ def test_iam_permissions( ]: raise NotImplementedError() -__all__ = ( - 'EkmServiceTransport', -) + +__all__ = ("EkmServiceTransport",) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py b/google/cloud/kms_v1/services/ekm_service/transports/grpc.py similarity index 85% rename from owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py rename to google/cloud/kms_v1/services/ekm_service/transports/grpc.py index de0b8b46..25eb8a18 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py +++ b/google/cloud/kms_v1/services/ekm_service/transports/grpc.py @@ -18,7 +18,7 @@ from google.api_core import grpc_helpers from google.api_core import gapic_v1 -import google.auth # type: ignore +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -47,22 +47,25 @@ class EkmServiceGrpcTransport(EkmServiceTransport): 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: + 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: @@ -180,13 +183,15 @@ def __init__(self, *, 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: + 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. @@ -221,7 +226,7 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property @@ -231,9 +236,11 @@ def grpc_channel(self) -> grpc.Channel: return self._grpc_channel @property - def list_ekm_connections(self) -> Callable[ - [ekm_service.ListEkmConnectionsRequest], - ekm_service.ListEkmConnectionsResponse]: + def list_ekm_connections( + self, + ) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], ekm_service.ListEkmConnectionsResponse + ]: r"""Return a callable for the list ekm connections method over gRPC. Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. @@ -248,18 +255,18 @@ def list_ekm_connections(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_ekm_connections' not in self._stubs: - self._stubs['list_ekm_connections'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/ListEkmConnections', + if "list_ekm_connections" not in self._stubs: + self._stubs["list_ekm_connections"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/ListEkmConnections", request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, ) - return self._stubs['list_ekm_connections'] + return self._stubs["list_ekm_connections"] @property - def get_ekm_connection(self) -> Callable[ - [ekm_service.GetEkmConnectionRequest], - ekm_service.EkmConnection]: + def get_ekm_connection( + self, + ) -> Callable[[ekm_service.GetEkmConnectionRequest], ekm_service.EkmConnection]: r"""Return a callable for the get ekm connection method over gRPC. Returns metadata for a given @@ -275,18 +282,18 @@ def get_ekm_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_ekm_connection' not in self._stubs: - self._stubs['get_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/GetEkmConnection', + if "get_ekm_connection" not in self._stubs: + self._stubs["get_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/GetEkmConnection", request_serializer=ekm_service.GetEkmConnectionRequest.serialize, response_deserializer=ekm_service.EkmConnection.deserialize, ) - return self._stubs['get_ekm_connection'] + return self._stubs["get_ekm_connection"] @property - def create_ekm_connection(self) -> Callable[ - [ekm_service.CreateEkmConnectionRequest], - ekm_service.EkmConnection]: + def create_ekm_connection( + self, + ) -> Callable[[ekm_service.CreateEkmConnectionRequest], ekm_service.EkmConnection]: r"""Return a callable for the create ekm connection method over gRPC. Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] @@ -302,18 +309,18 @@ def create_ekm_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_ekm_connection' not in self._stubs: - self._stubs['create_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/CreateEkmConnection', + if "create_ekm_connection" not in self._stubs: + self._stubs["create_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/CreateEkmConnection", request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, response_deserializer=ekm_service.EkmConnection.deserialize, ) - return self._stubs['create_ekm_connection'] + return self._stubs["create_ekm_connection"] @property - def update_ekm_connection(self) -> Callable[ - [ekm_service.UpdateEkmConnectionRequest], - ekm_service.EkmConnection]: + def update_ekm_connection( + self, + ) -> Callable[[ekm_service.UpdateEkmConnectionRequest], ekm_service.EkmConnection]: r"""Return a callable for the update ekm connection method over gRPC. Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s @@ -329,13 +336,13 @@ def update_ekm_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_ekm_connection' not in self._stubs: - self._stubs['update_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/UpdateEkmConnection', + if "update_ekm_connection" not in self._stubs: + self._stubs["update_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/UpdateEkmConnection", request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, response_deserializer=ekm_service.EkmConnection.deserialize, ) - return self._stubs['update_ekm_connection'] + return self._stubs["update_ekm_connection"] @property def set_iam_policy( @@ -392,7 +399,8 @@ def get_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + [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 @@ -419,6 +427,5 @@ def test_iam_permissions( def close(self): self.grpc_channel.close() -__all__ = ( - 'EkmServiceGrpcTransport', -) + +__all__ = ("EkmServiceGrpcTransport",) diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py b/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py similarity index 85% rename from owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py rename to google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py index 67560b8b..6f605381 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py +++ b/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py @@ -18,10 +18,10 @@ 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore -import grpc # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.kms_v1.types import ekm_service @@ -53,13 +53,15 @@ class EkmServiceGrpcAsyncIOTransport(EkmServiceTransport): _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: + 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. @@ -90,23 +92,25 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **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: + 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: @@ -234,9 +238,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def list_ekm_connections(self) -> Callable[ - [ekm_service.ListEkmConnectionsRequest], - Awaitable[ekm_service.ListEkmConnectionsResponse]]: + def list_ekm_connections( + self, + ) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + Awaitable[ekm_service.ListEkmConnectionsResponse], + ]: r"""Return a callable for the list ekm connections method over gRPC. Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. @@ -251,18 +258,20 @@ def list_ekm_connections(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_ekm_connections' not in self._stubs: - self._stubs['list_ekm_connections'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/ListEkmConnections', + if "list_ekm_connections" not in self._stubs: + self._stubs["list_ekm_connections"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/ListEkmConnections", request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, ) - return self._stubs['list_ekm_connections'] + return self._stubs["list_ekm_connections"] @property - def get_ekm_connection(self) -> Callable[ - [ekm_service.GetEkmConnectionRequest], - Awaitable[ekm_service.EkmConnection]]: + def get_ekm_connection( + self, + ) -> Callable[ + [ekm_service.GetEkmConnectionRequest], Awaitable[ekm_service.EkmConnection] + ]: r"""Return a callable for the get ekm connection method over gRPC. Returns metadata for a given @@ -278,18 +287,20 @@ def get_ekm_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_ekm_connection' not in self._stubs: - self._stubs['get_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/GetEkmConnection', + if "get_ekm_connection" not in self._stubs: + self._stubs["get_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/GetEkmConnection", request_serializer=ekm_service.GetEkmConnectionRequest.serialize, response_deserializer=ekm_service.EkmConnection.deserialize, ) - return self._stubs['get_ekm_connection'] + return self._stubs["get_ekm_connection"] @property - def create_ekm_connection(self) -> Callable[ - [ekm_service.CreateEkmConnectionRequest], - Awaitable[ekm_service.EkmConnection]]: + def create_ekm_connection( + self, + ) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], Awaitable[ekm_service.EkmConnection] + ]: r"""Return a callable for the create ekm connection method over gRPC. Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] @@ -305,18 +316,20 @@ def create_ekm_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_ekm_connection' not in self._stubs: - self._stubs['create_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/CreateEkmConnection', + if "create_ekm_connection" not in self._stubs: + self._stubs["create_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/CreateEkmConnection", request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, response_deserializer=ekm_service.EkmConnection.deserialize, ) - return self._stubs['create_ekm_connection'] + return self._stubs["create_ekm_connection"] @property - def update_ekm_connection(self) -> Callable[ - [ekm_service.UpdateEkmConnectionRequest], - Awaitable[ekm_service.EkmConnection]]: + def update_ekm_connection( + self, + ) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], Awaitable[ekm_service.EkmConnection] + ]: r"""Return a callable for the update ekm connection method over gRPC. Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s @@ -332,13 +345,13 @@ def update_ekm_connection(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_ekm_connection' not in self._stubs: - self._stubs['update_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/UpdateEkmConnection', + if "update_ekm_connection" not in self._stubs: + self._stubs["update_ekm_connection"] = self.grpc_channel.unary_unary( + "/google.cloud.kms.v1.EkmService/UpdateEkmConnection", request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, response_deserializer=ekm_service.EkmConnection.deserialize, ) - return self._stubs['update_ekm_connection'] + return self._stubs["update_ekm_connection"] @property def set_iam_policy( @@ -424,6 +437,4 @@ def close(self): return self.grpc_channel.close() -__all__ = ( - 'EkmServiceGrpcAsyncIOTransport', -) +__all__ = ("EkmServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/kms_v1/services/key_management_service/async_client.py b/google/cloud/kms_v1/services/key_management_service/async_client.py index 92b44094..9d3e4fe4 100644 --- a/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -277,14 +277,14 @@ async def list_key_rings( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsAsyncPager: Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -369,14 +369,14 @@ async def list_crypto_keys( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeysAsyncPager: Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -462,14 +462,14 @@ async def list_crypto_key_versions( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager: Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -554,14 +554,14 @@ async def list_import_jobs( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListImportJobsAsyncPager: Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -645,13 +645,12 @@ async def get_key_ring( Returns: google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -732,8 +731,8 @@ async def get_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -743,7 +742,7 @@ async def get_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -823,8 +822,9 @@ async def get_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -839,7 +839,7 @@ async def get_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -924,12 +924,14 @@ async def get_public_key( Returns: google.cloud.kms_v1.types.PublicKey: - The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via + The public key for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Obtained via [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1008,7 +1010,8 @@ async def get_import_job( Returns: google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using pre-existing key material, generated outside of Cloud KMS. @@ -1056,7 +1059,7 @@ async def get_import_job( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1151,13 +1154,12 @@ async def create_key_ring( Returns: google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, key_ring_id, key_ring]) if request is not None and has_flattened_params: @@ -1260,8 +1262,8 @@ async def create_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1271,7 +1273,7 @@ async def create_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, crypto_key_id, crypto_key]) if request is not None and has_flattened_params: @@ -1370,8 +1372,9 @@ async def create_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1386,7 +1389,7 @@ async def create_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, crypto_key_version]) if request is not None and has_flattened_params: @@ -1456,8 +1459,9 @@ async def import_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1546,7 +1550,8 @@ async def create_import_job( Returns: google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using pre-existing key material, generated outside of Cloud KMS. @@ -1594,7 +1599,7 @@ async def create_import_job( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, import_job_id, import_job]) if request is not None and has_flattened_params: @@ -1683,8 +1688,8 @@ async def update_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1694,7 +1699,7 @@ async def update_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([crypto_key, update_mask]) if request is not None and has_flattened_params: @@ -1797,8 +1802,9 @@ async def update_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1813,7 +1819,7 @@ async def update_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([crypto_key_version, update_mask]) if request is not None and has_flattened_params: @@ -1908,8 +1914,8 @@ async def update_crypto_key_primary_version( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1919,7 +1925,7 @@ async def update_crypto_key_primary_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, crypto_key_version_id]) if request is not None and has_flattened_params: @@ -2021,8 +2027,9 @@ async def destroy_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2037,7 +2044,7 @@ async def destroy_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -2126,8 +2133,9 @@ async def restore_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2142,7 +2150,7 @@ async def restore_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -2248,11 +2256,11 @@ async def encrypt( Returns: google.cloud.kms_v1.types.EncryptResponse: Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, plaintext]) if request is not None and has_flattened_params: @@ -2346,11 +2354,11 @@ async def decrypt( Returns: google.cloud.kms_v1.types.DecryptResponse: Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, ciphertext]) if request is not None and has_flattened_params: @@ -2434,6 +2442,10 @@ async def asymmetric_sign( specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + This corresponds to the ``digest`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2446,11 +2458,11 @@ async def asymmetric_sign( Returns: google.cloud.kms_v1.types.AsymmetricSignResponse: Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, digest]) if request is not None and has_flattened_params: @@ -2546,11 +2558,11 @@ async def asymmetric_decrypt( Returns: google.cloud.kms_v1.types.AsymmetricDecryptResponse: Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, ciphertext]) if request is not None and has_flattened_params: @@ -2644,11 +2656,11 @@ async def mac_sign( Returns: google.cloud.kms_v1.types.MacSignResponse: Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, data]) if request is not None and has_flattened_params: @@ -2748,11 +2760,11 @@ async def mac_verify( Returns: google.cloud.kms_v1.types.MacVerifyResponse: Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, data, mac]) if request is not None and has_flattened_params: @@ -2824,8 +2836,8 @@ async def generate_random_bytes( location (:class:`str`): The project-specific location in which to generate random bytes. For - example, "projects/my- - project/locations/us-central1". + example, + "projects/my-project/locations/us-central1". This corresponds to the ``location`` field on the ``request`` instance; if ``request`` is provided, this @@ -2841,8 +2853,9 @@ async def generate_random_bytes( protection_level (:class:`google.cloud.kms_v1.types.ProtectionLevel`): The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Defaults to - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] + protection level is supported. This corresponds to the ``protection_level`` field on the ``request`` instance; if ``request`` is provided, this @@ -2856,11 +2869,11 @@ async def generate_random_bytes( Returns: google.cloud.kms_v1.types.GenerateRandomBytesResponse: Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([location, length_bytes, protection_level]) if request is not None and has_flattened_params: diff --git a/google/cloud/kms_v1/services/key_management_service/client.py b/google/cloud/kms_v1/services/key_management_service/client.py index 3af40f42..c444d4fa 100644 --- a/google/cloud/kms_v1/services/key_management_service/client.py +++ b/google/cloud/kms_v1/services/key_management_service/client.py @@ -553,14 +553,14 @@ def list_key_rings( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsPager: Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -635,14 +635,14 @@ def list_crypto_keys( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeysPager: Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -718,14 +718,14 @@ def list_crypto_key_versions( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsPager: Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -800,14 +800,14 @@ def list_import_jobs( Returns: google.cloud.kms_v1.services.key_management_service.pagers.ListImportJobsPager: Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: @@ -881,13 +881,12 @@ def get_key_ring( Returns: google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -958,8 +957,8 @@ def get_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -969,7 +968,7 @@ def get_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1039,8 +1038,9 @@ def get_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1055,7 +1055,7 @@ def get_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1130,12 +1130,14 @@ def get_public_key( Returns: google.cloud.kms_v1.types.PublicKey: - The public key for a given [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained via + The public key for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Obtained via [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1204,7 +1206,8 @@ def get_import_job( Returns: google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using pre-existing key material, generated outside of Cloud KMS. @@ -1252,7 +1255,7 @@ def get_import_job( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -1337,13 +1340,12 @@ def create_key_ring( Returns: google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, key_ring_id, key_ring]) if request is not None and has_flattened_params: @@ -1436,8 +1438,8 @@ def create_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1447,7 +1449,7 @@ def create_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, crypto_key_id, crypto_key]) if request is not None and has_flattened_params: @@ -1536,8 +1538,9 @@ def create_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1552,7 +1555,7 @@ def create_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, crypto_key_version]) if request is not None and has_flattened_params: @@ -1624,8 +1627,9 @@ def import_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1717,7 +1721,8 @@ def create_import_job( Returns: google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using pre-existing key material, generated outside of Cloud KMS. @@ -1765,7 +1770,7 @@ def create_import_job( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, import_job_id, import_job]) if request is not None and has_flattened_params: @@ -1844,8 +1849,8 @@ def update_crypto_key( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -1855,7 +1860,7 @@ def update_crypto_key( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([crypto_key, update_mask]) if request is not None and has_flattened_params: @@ -1948,8 +1953,9 @@ def update_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -1964,7 +1970,7 @@ def update_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([crypto_key_version, update_mask]) if request is not None and has_flattened_params: @@ -2051,8 +2057,8 @@ def update_crypto_key_primary_version( Returns: google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that can be used for cryptographic - operations. + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or more @@ -2062,7 +2068,7 @@ def update_crypto_key_primary_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, crypto_key_version_id]) if request is not None and has_flattened_params: @@ -2156,8 +2162,9 @@ def destroy_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2172,7 +2179,7 @@ def destroy_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -2253,8 +2260,9 @@ def restore_crypto_key_version( Returns: google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an individual cryptographic key, and the - associated key material. + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. An [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] @@ -2269,7 +2277,7 @@ def restore_crypto_key_version( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: @@ -2367,11 +2375,11 @@ def encrypt( Returns: google.cloud.kms_v1.types.EncryptResponse: Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, plaintext]) if request is not None and has_flattened_params: @@ -2455,11 +2463,11 @@ def decrypt( Returns: google.cloud.kms_v1.types.DecryptResponse: Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, ciphertext]) if request is not None and has_flattened_params: @@ -2533,6 +2541,10 @@ def asymmetric_sign( specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + This corresponds to the ``digest`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2545,11 +2557,11 @@ def asymmetric_sign( Returns: google.cloud.kms_v1.types.AsymmetricSignResponse: Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, digest]) if request is not None and has_flattened_params: @@ -2635,11 +2647,11 @@ def asymmetric_decrypt( Returns: google.cloud.kms_v1.types.AsymmetricDecryptResponse: Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, ciphertext]) if request is not None and has_flattened_params: @@ -2723,11 +2735,11 @@ def mac_sign( Returns: google.cloud.kms_v1.types.MacSignResponse: Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, data]) if request is not None and has_flattened_params: @@ -2817,11 +2829,11 @@ def mac_verify( Returns: google.cloud.kms_v1.types.MacVerifyResponse: Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([name, data, mac]) if request is not None and has_flattened_params: @@ -2883,8 +2895,8 @@ def generate_random_bytes( location (str): The project-specific location in which to generate random bytes. For - example, "projects/my- - project/locations/us-central1". + example, + "projects/my-project/locations/us-central1". This corresponds to the ``location`` field on the ``request`` instance; if ``request`` is provided, this @@ -2900,8 +2912,9 @@ def generate_random_bytes( protection_level (google.cloud.kms_v1.types.ProtectionLevel): The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Defaults to - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] + protection level is supported. This corresponds to the ``protection_level`` field on the ``request`` instance; if ``request`` is provided, this @@ -2915,11 +2928,11 @@ def generate_random_bytes( Returns: google.cloud.kms_v1.types.GenerateRandomBytesResponse: Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([location, length_bytes, protection_level]) if request is not None and has_flattened_params: diff --git a/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/google/cloud/kms_v1/services/key_management_service/transports/grpc.py index 0fabb11e..742ac3cf 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -172,8 +172,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py index ccce24a4..659578be 100644 --- a/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ b/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -217,8 +217,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/kms_v1/types/__init__.py b/google/cloud/kms_v1/types/__init__.py index 85c10803..1e83b0db 100644 --- a/google/cloud/kms_v1/types/__init__.py +++ b/google/cloud/kms_v1/types/__init__.py @@ -13,6 +13,15 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .ekm_service import ( + Certificate, + CreateEkmConnectionRequest, + EkmConnection, + GetEkmConnectionRequest, + ListEkmConnectionsRequest, + ListEkmConnectionsResponse, + UpdateEkmConnectionRequest, +) from .resources import ( CryptoKey, CryptoKeyVersion, @@ -67,6 +76,13 @@ ) __all__ = ( + "Certificate", + "CreateEkmConnectionRequest", + "EkmConnection", + "GetEkmConnectionRequest", + "ListEkmConnectionsRequest", + "ListEkmConnectionsResponse", + "UpdateEkmConnectionRequest", "CryptoKey", "CryptoKeyVersion", "CryptoKeyVersionTemplate", diff --git a/owl-bot-staging/v1/google/cloud/kms_v1/types/ekm_service.py b/google/cloud/kms_v1/types/ekm_service.py similarity index 78% rename from owl-bot-staging/v1/google/cloud/kms_v1/types/ekm_service.py rename to google/cloud/kms_v1/types/ekm_service.py index 208115fc..42d9cdf0 100644 --- a/owl-bot-staging/v1/google/cloud/kms_v1/types/ekm_service.py +++ b/google/cloud/kms_v1/types/ekm_service.py @@ -20,15 +20,15 @@ __protobuf__ = proto.module( - package='google.cloud.kms.v1', + package="google.cloud.kms.v1", manifest={ - 'ListEkmConnectionsRequest', - 'ListEkmConnectionsResponse', - 'GetEkmConnectionRequest', - 'CreateEkmConnectionRequest', - 'UpdateEkmConnectionRequest', - 'Certificate', - 'EkmConnection', + "ListEkmConnectionsRequest", + "ListEkmConnectionsResponse", + "GetEkmConnectionRequest", + "CreateEkmConnectionRequest", + "UpdateEkmConnectionRequest", + "Certificate", + "EkmConnection", }, ) @@ -65,26 +65,11 @@ class ListEkmConnectionsRequest(proto.Message): 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, - ) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) + order_by = proto.Field(proto.STRING, number=5,) class ListEkmConnectionsResponse(proto.Message): @@ -109,18 +94,10 @@ def raw_page(self): return self ekm_connections = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EkmConnection', - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - total_size = proto.Field( - proto.INT32, - number=3, + proto.MESSAGE, number=1, message="EkmConnection", ) + next_page_token = proto.Field(proto.STRING, number=2,) + total_size = proto.Field(proto.INT32, number=3,) class GetEkmConnectionRequest(proto.Message): @@ -133,10 +110,7 @@ class GetEkmConnectionRequest(proto.Message): get. """ - name = proto.Field( - proto.STRING, - number=1, - ) + name = proto.Field(proto.STRING, number=1,) class CreateEkmConnectionRequest(proto.Message): @@ -156,19 +130,9 @@ class CreateEkmConnectionRequest(proto.Message): initial field values. """ - parent = proto.Field( - proto.STRING, - number=1, - ) - ekm_connection_id = proto.Field( - proto.STRING, - number=2, - ) - ekm_connection = proto.Field( - proto.MESSAGE, - number=3, - message='EkmConnection', - ) + parent = proto.Field(proto.STRING, number=1,) + ekm_connection_id = proto.Field(proto.STRING, number=2,) + ekm_connection = proto.Field(proto.MESSAGE, number=3, message="EkmConnection",) class UpdateEkmConnectionRequest(proto.Message): @@ -183,15 +147,9 @@ class UpdateEkmConnectionRequest(proto.Message): this request. """ - ekm_connection = proto.Field( - proto.MESSAGE, - number=1, - message='EkmConnection', - ) + ekm_connection = proto.Field(proto.MESSAGE, number=1, message="EkmConnection",) update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, ) @@ -235,44 +193,19 @@ class Certificate(proto.Message): [parsed][google.cloud.kms.v1.Certificate.parsed] is true. """ - raw_der = proto.Field( - proto.BYTES, - number=1, - ) - parsed = proto.Field( - proto.BOOL, - number=2, - ) - issuer = proto.Field( - proto.STRING, - number=3, - ) - subject = proto.Field( - proto.STRING, - number=4, - ) - subject_alternative_dns_names = proto.RepeatedField( - proto.STRING, - number=5, - ) + raw_der = proto.Field(proto.BYTES, number=1,) + parsed = proto.Field(proto.BOOL, number=2,) + issuer = proto.Field(proto.STRING, number=3,) + subject = proto.Field(proto.STRING, number=4,) + subject_alternative_dns_names = proto.RepeatedField(proto.STRING, number=5,) not_before_time = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, + proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, ) not_after_time = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - serial_number = proto.Field( - proto.STRING, - number=8, - ) - sha256_fingerprint = proto.Field( - proto.STRING, - number=9, + proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp, ) + serial_number = proto.Field(proto.STRING, number=8,) + sha256_fingerprint = proto.Field(proto.STRING, number=9,) class EkmConnection(proto.Message): @@ -336,42 +269,19 @@ class ServiceResolver(proto.Message): EKM replica. """ - service_directory_service = proto.Field( - proto.STRING, - number=1, - ) - endpoint_filter = proto.Field( - proto.STRING, - number=2, - ) - hostname = proto.Field( - proto.STRING, - number=3, - ) + service_directory_service = proto.Field(proto.STRING, number=1,) + endpoint_filter = proto.Field(proto.STRING, number=2,) + hostname = proto.Field(proto.STRING, number=3,) server_certificates = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Certificate', + proto.MESSAGE, number=4, message="Certificate", ) - name = proto.Field( - proto.STRING, - number=1, - ) - create_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) + name = proto.Field(proto.STRING, number=1,) + create_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) service_resolvers = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ServiceResolver, - ) - etag = proto.Field( - proto.STRING, - number=5, + proto.MESSAGE, number=3, message=ServiceResolver, ) + etag = proto.Field(proto.STRING, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/kms_v1/types/resources.py b/google/cloud/kms_v1/types/resources.py index 73b284ca..6737af3c 100644 --- a/google/cloud/kms_v1/types/resources.py +++ b/google/cloud/kms_v1/types/resources.py @@ -46,6 +46,7 @@ class ProtectionLevel(proto.Enum): SOFTWARE = 1 HSM = 2 EXTERNAL = 3 + EXTERNAL_VPC = 4 class KeyRing(proto.Message): @@ -166,6 +167,23 @@ class CryptoKey(proto.Message): [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. If not specified at creation time, the default duration is 24 hours. + crypto_key_backend (str): + Immutable. The resource name of the backend environment + where the key material for all + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + associated with this + [CryptoKey][google.cloud.kms.v1.CryptoKey] reside and where + all related cryptographic operations are performed. Only + applicable if + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + have a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + with the resource name in the format + ``projects/*/locations/*/ekmConnections/*``. Note, this list + is non-exhaustive and may apply to additional + [ProtectionLevels][google.cloud.kms.v1.ProtectionLevel] in + the future. """ class CryptoKeyPurpose(proto.Enum): @@ -203,6 +221,7 @@ class CryptoKeyPurpose(proto.Enum): destroy_scheduled_duration = proto.Field( proto.MESSAGE, number=14, message=duration_pb2.Duration, ) + crypto_key_backend = proto.Field(proto.STRING, number=15,) class CryptoKeyVersionTemplate(proto.Message): @@ -253,6 +272,9 @@ class KeyOperationAttestation(proto.Message): content (bytes): Output only. The attestation data provided by the HSM when the key operation was performed. + cert_chains (google.cloud.kms_v1.types.KeyOperationAttestation.CertificateChains): + Output only. The certificate chains needed to + validate the attestation """ class AttestationFormat(proto.Enum): @@ -261,8 +283,30 @@ class AttestationFormat(proto.Enum): CAVIUM_V1_COMPRESSED = 3 CAVIUM_V2_COMPRESSED = 4 + class CertificateChains(proto.Message): + r"""Certificate chains needed to verify the attestation. + Certificates in chains are PEM-encoded and are ordered based on + https://tools.ietf.org/html/rfc5246#section-7.4.2. + + Attributes: + cavium_certs (Sequence[str]): + Cavium certificate chain corresponding to the + attestation. + google_card_certs (Sequence[str]): + Google card certificate chain corresponding + to the attestation. + google_partition_certs (Sequence[str]): + Google partition certificate chain + corresponding to the attestation. + """ + + cavium_certs = proto.RepeatedField(proto.STRING, number=1,) + google_card_certs = proto.RepeatedField(proto.STRING, number=2,) + google_partition_certs = proto.RepeatedField(proto.STRING, number=3,) + format = proto.Field(proto.ENUM, number=4, enum=AttestationFormat,) content = proto.Field(proto.BYTES, number=5,) + cert_chains = proto.Field(proto.MESSAGE, number=6, message=CertificateChains,) class CryptoKeyVersion(proto.Message): @@ -347,7 +391,9 @@ class CryptoKeyVersion(proto.Message): [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that are specific to the [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] - protection level. + protection level and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + protection levels. reimport_eligible (bool): Output only. Whether or not this key version is eligible for reimport, by being specified as a target in @@ -689,16 +735,24 @@ class ExternalProtectionLevelOptions(proto.Message): [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that are specific to the [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] protection - level. + level and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + protection levels. Attributes: external_key_uri (str): The URI for an external resource that this [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents. + ekm_connection_key_path (str): + The path to the external key material on the EKM when using + [EkmConnection][google.cloud.kms.v1.EkmConnection] e.g., + "v0/my/key". Set this field instead of external_key_uri when + using an [EkmConnection][google.cloud.kms.v1.EkmConnection]. """ external_key_uri = proto.Field(proto.STRING, number=1,) + ekm_connection_key_path = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/kms_v1/types/service.py b/google/cloud/kms_v1/types/service.py index b3673654..3c79c548 100644 --- a/google/cloud/kms_v1/types/service.py +++ b/google/cloud/kms_v1/types/service.py @@ -560,8 +560,9 @@ class ImportCryptoKeyVersionRequest(proto.Message):
  1. An ephemeral AES-256 wrapping key wrapped with the - [public_key][google.cloud.kms.v1.ImportJob.public_key] using RSAES-OAEP with SHA-1, - MGF1 with SHA-1, and an empty label. + [public_key][google.cloud.kms.v1.ImportJob.public_key] using + RSAES-OAEP with SHA-1/SHA-256, MGF1 with SHA-1/SHA-256, and an + empty label.
  2. The key to be imported, wrapped with the ephemeral AES-256 key using AES-KWP (RFC 5649). @@ -878,6 +879,10 @@ class AsymmetricSignRequest(proto.Message): produced with the same digest algorithm as specified by the key version's [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. @@ -900,10 +905,9 @@ class AsymmetricSignRequest(proto.Message): exceed 2^32-1, and can be safely downconverted to uint32 in languages that support this type. data (bytes): - Optional. This field will only be honored for RAW_PKCS1 - keys. The data to sign. A digest is computed over the data - that will be signed, PKCS #1 padding is applied to the - digest directly and then encrypted. + Optional. The data to sign. It can't be supplied if + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] + is supplied. data_crc32c (google.protobuf.wrappers_pb2.Int64Value): Optional. An optional CRC32C checksum of the [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]. @@ -1100,8 +1104,9 @@ class GenerateRandomBytesRequest(proto.Message): maximum 1024 bytes. protection_level (google.cloud.kms_v1.types.ProtectionLevel): The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Defaults to - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] protection + level is supported. """ location = proto.Field(proto.STRING, number=1,) diff --git a/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 12cf25d1..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 = "4.0.1" - -# 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 root toctree document. -root_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 = [ - ( - root_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 = [ - ( - root_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 = [ - ( - root_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 141ddfe4..00000000 --- a/owl-bot-staging/v1/docs/kms_v1/services.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Kms v1 API -==================================== -.. toctree:: - :maxdepth: 2 - - ekm_service - 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 e4f07546..00000000 --- a/owl-bot-staging/v1/google/cloud/kms/__init__.py +++ /dev/null @@ -1,137 +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.ekm_service.client import EkmServiceClient -from google.cloud.kms_v1.services.ekm_service.async_client import EkmServiceAsyncClient -from google.cloud.kms_v1.services.key_management_service.client import KeyManagementServiceClient -from google.cloud.kms_v1.services.key_management_service.async_client import KeyManagementServiceAsyncClient - -from google.cloud.kms_v1.types.ekm_service import Certificate -from google.cloud.kms_v1.types.ekm_service import CreateEkmConnectionRequest -from google.cloud.kms_v1.types.ekm_service import EkmConnection -from google.cloud.kms_v1.types.ekm_service import GetEkmConnectionRequest -from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsRequest -from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsResponse -from google.cloud.kms_v1.types.ekm_service import UpdateEkmConnectionRequest -from google.cloud.kms_v1.types.resources import CryptoKey -from google.cloud.kms_v1.types.resources import CryptoKeyVersion -from google.cloud.kms_v1.types.resources import CryptoKeyVersionTemplate -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__ = ('EkmServiceClient', - 'EkmServiceAsyncClient', - 'KeyManagementServiceClient', - 'KeyManagementServiceAsyncClient', - 'Certificate', - 'CreateEkmConnectionRequest', - 'EkmConnection', - 'GetEkmConnectionRequest', - 'ListEkmConnectionsRequest', - 'ListEkmConnectionsResponse', - 'UpdateEkmConnectionRequest', - '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 74317d3a..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/__init__.py +++ /dev/null @@ -1,138 +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.ekm_service import EkmServiceClient -from .services.ekm_service import EkmServiceAsyncClient -from .services.key_management_service import KeyManagementServiceClient -from .services.key_management_service import KeyManagementServiceAsyncClient - -from .types.ekm_service import Certificate -from .types.ekm_service import CreateEkmConnectionRequest -from .types.ekm_service import EkmConnection -from .types.ekm_service import GetEkmConnectionRequest -from .types.ekm_service import ListEkmConnectionsRequest -from .types.ekm_service import ListEkmConnectionsResponse -from .types.ekm_service import UpdateEkmConnectionRequest -from .types.resources import CryptoKey -from .types.resources import CryptoKeyVersion -from .types.resources import CryptoKeyVersionTemplate -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__ = ( - 'EkmServiceAsyncClient', - 'KeyManagementServiceAsyncClient', -'AsymmetricDecryptRequest', -'AsymmetricDecryptResponse', -'AsymmetricSignRequest', -'AsymmetricSignResponse', -'Certificate', -'CreateCryptoKeyRequest', -'CreateCryptoKeyVersionRequest', -'CreateEkmConnectionRequest', -'CreateImportJobRequest', -'CreateKeyRingRequest', -'CryptoKey', -'CryptoKeyVersion', -'CryptoKeyVersionTemplate', -'DecryptRequest', -'DecryptResponse', -'DestroyCryptoKeyVersionRequest', -'Digest', -'EkmConnection', -'EkmServiceClient', -'EncryptRequest', -'EncryptResponse', -'ExternalProtectionLevelOptions', -'GenerateRandomBytesRequest', -'GenerateRandomBytesResponse', -'GetCryptoKeyRequest', -'GetCryptoKeyVersionRequest', -'GetEkmConnectionRequest', -'GetImportJobRequest', -'GetKeyRingRequest', -'GetPublicKeyRequest', -'ImportCryptoKeyVersionRequest', -'ImportJob', -'KeyManagementServiceClient', -'KeyOperationAttestation', -'KeyRing', -'ListCryptoKeyVersionsRequest', -'ListCryptoKeyVersionsResponse', -'ListCryptoKeysRequest', -'ListCryptoKeysResponse', -'ListEkmConnectionsRequest', -'ListEkmConnectionsResponse', -'ListImportJobsRequest', -'ListImportJobsResponse', -'ListKeyRingsRequest', -'ListKeyRingsResponse', -'LocationMetadata', -'MacSignRequest', -'MacSignResponse', -'MacVerifyRequest', -'MacVerifyResponse', -'ProtectionLevel', -'PublicKey', -'RestoreCryptoKeyVersionRequest', -'UpdateCryptoKeyPrimaryVersionRequest', -'UpdateCryptoKeyRequest', -'UpdateCryptoKeyVersionRequest', -'UpdateEkmConnectionRequest', -) 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 3b830979..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/gapic_metadata.json +++ /dev/null @@ -1,337 +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": { - "EkmService": { - "clients": { - "grpc": { - "libraryClient": "EkmServiceClient", - "rpcs": { - "CreateEkmConnection": { - "methods": [ - "create_ekm_connection" - ] - }, - "GetEkmConnection": { - "methods": [ - "get_ekm_connection" - ] - }, - "ListEkmConnections": { - "methods": [ - "list_ekm_connections" - ] - }, - "UpdateEkmConnection": { - "methods": [ - "update_ekm_connection" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EkmServiceAsyncClient", - "rpcs": { - "CreateEkmConnection": { - "methods": [ - "create_ekm_connection" - ] - }, - "GetEkmConnection": { - "methods": [ - "get_ekm_connection" - ] - }, - "ListEkmConnections": { - "methods": [ - "list_ekm_connections" - ] - }, - "UpdateEkmConnection": { - "methods": [ - "update_ekm_connection" - ] - } - } - } - } - }, - "KeyManagementService": { - "clients": { - "grpc": { - "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 4cdae615..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/async_client.py +++ /dev/null @@ -1,3197 +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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, key_ring_id, key_ring]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, crypto_key_id, crypto_key]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, crypto_key_version]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, import_job_id, import_job]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([crypto_key, update_mask]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([crypto_key_version, update_mask]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, crypto_key_version_id]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, plaintext]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, ciphertext]) - if request is not None and has_flattened_params: - 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 field may not be supplied if - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] - is supplied. - - This corresponds to the ``digest`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, digest]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, ciphertext]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data, mac]) - if request is not None and has_flattened_params: - 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. Currently, only - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] - protection level is supported. - - This corresponds to the ``protection_level`` field - on the ``request`` instance; if ``request`` is provided, this - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([location, length_bytes, protection_level]) - if request is not None and has_flattened_params: - 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 ed710138..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/client.py +++ /dev/null @@ -1,3267 +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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, key_ring_id, key_ring]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, crypto_key_id, crypto_key]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, crypto_key_version]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, import_job_id, import_job]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([crypto_key, update_mask]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([crypto_key_version, update_mask]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, crypto_key_version_id]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, plaintext]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, ciphertext]) - if request is not None and has_flattened_params: - 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 field may not be supplied if - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] - is supplied. - - This corresponds to the ``digest`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, digest]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, ciphertext]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data]) - if request is not None and has_flattened_params: - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, data, mac]) - if request is not None and has_flattened_params: - 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. Currently, only - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] - protection level is supported. - - This corresponds to the ``protection_level`` field - on the ``request`` instance; if ``request`` is provided, this - 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. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([location, length_bytes, protection_level]) - if request is not None and has_flattened_params: - 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 77e2ff65..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ /dev/null @@ -1,1118 +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, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudkms.googleapis.com', - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_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 5fd78d44..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,1123 +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, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_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 80dba706..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/types/__init__.py +++ /dev/null @@ -1,134 +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 .ekm_service import ( - Certificate, - CreateEkmConnectionRequest, - EkmConnection, - GetEkmConnectionRequest, - ListEkmConnectionsRequest, - ListEkmConnectionsResponse, - UpdateEkmConnectionRequest, -) -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__ = ( - 'Certificate', - 'CreateEkmConnectionRequest', - 'EkmConnection', - 'GetEkmConnectionRequest', - 'ListEkmConnectionsRequest', - 'ListEkmConnectionsResponse', - 'UpdateEkmConnectionRequest', - '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 d33ffc1f..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/types/resources.py +++ /dev/null @@ -1,916 +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 - EXTERNAL_VPC = 4 - - -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. - crypto_key_backend (str): - Immutable. The resource name of the backend environment - where the key material for all - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - associated with this - [CryptoKey][google.cloud.kms.v1.CryptoKey] reside and where - all related cryptographic operations are performed. Only - applicable if - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - have a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - with the resource name in the format - ``projects/*/locations/*/ekmConnections/*``. Note, this list - is non-exhaustive and may apply to additional - [ProtectionLevels][google.cloud.kms.v1.ProtectionLevel] in - the future. - """ - class CryptoKeyPurpose(proto.Enum): - 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, - ) - crypto_key_backend = proto.Field( - proto.STRING, - number=15, - ) - - -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. - cert_chains (google.cloud.kms_v1.types.KeyOperationAttestation.CertificateChains): - Output only. The certificate chains needed to - validate the attestation - """ - class AttestationFormat(proto.Enum): - r"""Attestation formats provided by the HSM.""" - ATTESTATION_FORMAT_UNSPECIFIED = 0 - CAVIUM_V1_COMPRESSED = 3 - CAVIUM_V2_COMPRESSED = 4 - - class CertificateChains(proto.Message): - r"""Certificate chains needed to verify the attestation. - Certificates in chains are PEM-encoded and are ordered based on - https://tools.ietf.org/html/rfc5246#section-7.4.2. - - Attributes: - cavium_certs (Sequence[str]): - Cavium certificate chain corresponding to the - attestation. - google_card_certs (Sequence[str]): - Google card certificate chain corresponding - to the attestation. - google_partition_certs (Sequence[str]): - Google partition certificate chain - corresponding to the attestation. - """ - - cavium_certs = proto.RepeatedField( - proto.STRING, - number=1, - ) - google_card_certs = proto.RepeatedField( - proto.STRING, - number=2, - ) - google_partition_certs = proto.RepeatedField( - proto.STRING, - number=3, - ) - - format_ = proto.Field( - proto.ENUM, - number=4, - enum=AttestationFormat, - ) - content = proto.Field( - proto.BYTES, - number=5, - ) - cert_chains = proto.Field( - proto.MESSAGE, - number=6, - message=CertificateChains, - ) - - -class CryptoKeyVersion(proto.Message): - 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 and - [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] - protection levels. - reimport_eligible (bool): - Output only. Whether or not this key version is eligible for - reimport, by being specified as a target in - [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 and - [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] - protection levels. - - Attributes: - external_key_uri (str): - The URI for an external resource that this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents. - ekm_connection_key_path (str): - The path to the external key material on the EKM when using - [EkmConnection][google.cloud.kms.v1.EkmConnection] e.g., - "v0/my/key". Set this field instead of external_key_uri when - using an [EkmConnection][google.cloud.kms.v1.EkmConnection]. - """ - - external_key_uri = proto.Field( - proto.STRING, - number=1, - ) - ekm_connection_key_path = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/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 20fc0c49..00000000 --- a/owl-bot-staging/v1/google/cloud/kms_v1/types/service.py +++ /dev/null @@ -1,1979 +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/SHA-256, MGF1 with SHA-1/SHA-256, 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]. - - This field may not be supplied if - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] - is supplied. - digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. - 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. The data to sign. It can't be supplied if - [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] - is supplied. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]. - 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. Currently, only - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] protection - level is supported. - """ - - 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 d7527817..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==4.0.1", "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 df767766..00000000 --- a/owl-bot-staging/v1/scripts/fixup_kms_v1_keywords.py +++ /dev/null @@ -1,208 +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_ekm_connection': ('parent', 'ekm_connection_id', 'ekm_connection', ), - 'create_import_job': ('parent', 'import_job_id', 'import_job', ), - 'create_key_ring': ('parent', 'key_ring_id', 'key_ring', ), - 'decrypt': ('name', 'ciphertext', 'additional_authenticated_data', 'ciphertext_crc32c', 'additional_authenticated_data_crc32c', ), - '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_ekm_connection': ('name', ), - 'get_import_job': ('name', ), - 'get_key_ring': ('name', ), - 'get_public_key': ('name', ), - 'import_crypto_key_version': ('parent', 'algorithm', 'import_job', 'crypto_key_version', 'rsa_aes_wrapped_key', ), - 'list_crypto_keys': ('parent', 'page_size', 'page_token', 'version_view', 'filter', 'order_by', ), - 'list_crypto_key_versions': ('parent', 'page_size', 'page_token', 'view', 'filter', 'order_by', ), - 'list_ekm_connections': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_import_jobs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_key_rings': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'mac_sign': ('name', 'data', 'data_crc32c', ), - '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', ), - 'update_ekm_connection': ('ekm_connection', '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 c9b24e3b..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_key_management_service.py +++ /dev/null @@ -1,8985 +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,grpc_helpers", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", grpc_helpers), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_key_management_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - -def test_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("client_class,transport_class,transport_name,grpc_helpers", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", grpc_helpers), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_key_management_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=None, - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - service.ListKeyRingsRequest, - dict, -]) -def test_list_key_rings(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - 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, - crypto_key_backend='crypto_key_backend_value', - 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 - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -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, - crypto_key_backend='crypto_key_backend_value', - )) - 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 - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@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, - crypto_key_backend='crypto_key_backend_value', - 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 - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -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, - crypto_key_backend='crypto_key_backend_value', - )) - 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 - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@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, - crypto_key_backend='crypto_key_backend_value', - 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 - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -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, - crypto_key_backend='crypto_key_backend_value', - )) - 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 - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@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, - crypto_key_backend='crypto_key_backend_value', - 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 - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -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, - crypto_key_backend='crypto_key_backend_value', - )) - 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 - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@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/scripts/fixup_kms_v1_keywords.py b/scripts/fixup_kms_v1_keywords.py index 1c0a208b..df767766 100644 --- a/scripts/fixup_kms_v1_keywords.py +++ b/scripts/fixup_kms_v1_keywords.py @@ -43,6 +43,7 @@ class kmsCallTransformer(cst.CSTTransformer): 'asymmetric_sign': ('name', 'digest', 'digest_crc32c', 'data', 'data_crc32c', ), 'create_crypto_key': ('parent', 'crypto_key_id', 'crypto_key', 'skip_initial_version_creation', ), 'create_crypto_key_version': ('parent', 'crypto_key_version', ), + 'create_ekm_connection': ('parent', 'ekm_connection_id', 'ekm_connection', ), 'create_import_job': ('parent', 'import_job_id', 'import_job', ), 'create_key_ring': ('parent', 'key_ring_id', 'key_ring', ), 'decrypt': ('name', 'ciphertext', 'additional_authenticated_data', 'ciphertext_crc32c', 'additional_authenticated_data_crc32c', ), @@ -51,12 +52,14 @@ class kmsCallTransformer(cst.CSTTransformer): 'generate_random_bytes': ('location', 'length_bytes', 'protection_level', ), 'get_crypto_key': ('name', ), 'get_crypto_key_version': ('name', ), + 'get_ekm_connection': ('name', ), 'get_import_job': ('name', ), 'get_key_ring': ('name', ), 'get_public_key': ('name', ), 'import_crypto_key_version': ('parent', 'algorithm', 'import_job', 'crypto_key_version', 'rsa_aes_wrapped_key', ), 'list_crypto_keys': ('parent', 'page_size', 'page_token', 'version_view', 'filter', 'order_by', ), 'list_crypto_key_versions': ('parent', 'page_size', 'page_token', 'view', 'filter', 'order_by', ), + 'list_ekm_connections': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_import_jobs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_key_rings': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'mac_sign': ('name', 'data', 'data_crc32c', ), @@ -65,6 +68,7 @@ class kmsCallTransformer(cst.CSTTransformer): 'update_crypto_key': ('crypto_key', 'update_mask', ), 'update_crypto_key_primary_version': ('name', 'crypto_key_version_id', ), 'update_crypto_key_version': ('crypto_key_version', 'update_mask', ), + 'update_ekm_connection': ('ekm_connection', 'update_mask', ), 'get_iam_policy': ('resource', 'options', ), 'set_iam_policy': ('resource', 'policy', ), 'test_iam_permissions': ('resource', 'permissions', ), diff --git a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_ekm_service.py b/tests/unit/gapic/kms_v1/test_ekm_service.py similarity index 72% rename from owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_ekm_service.py rename to tests/unit/gapic/kms_v1/test_ekm_service.py index 85ad0f9d..2f00f3a8 100644 --- a/owl-bot-staging/v1/tests/unit/gapic/kms_v1/test_ekm_service.py +++ b/tests/unit/gapic/kms_v1/test_ekm_service.py @@ -53,7 +53,11 @@ def client_cert_source_callback(): # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) def test__get_default_mtls_endpoint(): @@ -64,52 +68,70 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert EkmServiceClient._get_default_mtls_endpoint(None) is None - assert EkmServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EkmServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EkmServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EkmServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ( + EkmServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + EkmServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + EkmServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EkmServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) assert EkmServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi -@pytest.mark.parametrize("client_class", [ - EkmServiceClient, - EkmServiceAsyncClient, -]) +@pytest.mark.parametrize("client_class", [EkmServiceClient, EkmServiceAsyncClient,]) def test_ekm_service_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + 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' + assert client.transport._host == "cloudkms.googleapis.com:443" -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EkmServiceGrpcTransport, "grpc"), - (transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_ekm_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.EkmServiceGrpcTransport, "grpc"), + (transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_ekm_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() -@pytest.mark.parametrize("client_class", [ - EkmServiceClient, - EkmServiceAsyncClient, -]) +@pytest.mark.parametrize("client_class", [EkmServiceClient, EkmServiceAsyncClient,]) def test_ekm_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + 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 @@ -119,7 +141,7 @@ def test_ekm_service_client_from_service_account_file(client_class): assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == 'cloudkms.googleapis.com:443' + assert client.transport._host == "cloudkms.googleapis.com:443" def test_ekm_service_client_get_transport_class(): @@ -133,29 +155,42 @@ def test_ekm_service_client_get_transport_class(): assert transport == transports.EkmServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient)) -@mock.patch.object(EkmServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceAsyncClient)) -def test_ekm_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient) +) +@mock.patch.object( + EkmServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EkmServiceAsyncClient), +) +def test_ekm_service_client_client_options( + client_class, transport_class, transport_name +): # Check that if channel is provided we won't create a new one. - with mock.patch.object(EkmServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(EkmServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. - with mock.patch.object(EkmServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(EkmServiceClient, "get_transport_class") as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -172,7 +207,7 @@ def test_ekm_service_client_client_options(client_class, transport_class, transp # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -189,7 +224,7 @@ def test_ekm_service_client_client_options(client_class, transport_class, transp # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -210,13 +245,15 @@ def test_ekm_service_client_client_options(client_class, transport_class, transp 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 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: + 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( @@ -230,24 +267,50 @@ def test_ekm_service_client_client_options(client_class, transport_class, transp always_use_jwt_access=True, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "true"), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "false"), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient)) -@mock.patch.object(EkmServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceAsyncClient)) + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "true"), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "false"), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient) +) +@mock.patch.object( + EkmServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EkmServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_ekm_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_ekm_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: + 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) @@ -271,10 +334,18 @@ def test_ekm_service_client_mtls_env_auto(client_class, transport_class, transpo # 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): + 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 @@ -296,9 +367,14 @@ def test_ekm_service_client_mtls_env_auto(client_class, transport_class, transpo ) # 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): + 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( @@ -313,19 +389,27 @@ def test_ekm_service_client_mtls_env_auto(client_class, transport_class, transpo ) -@pytest.mark.parametrize("client_class", [ - EkmServiceClient, EkmServiceAsyncClient -]) -@mock.patch.object(EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient)) -@mock.patch.object(EkmServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceAsyncClient)) +@pytest.mark.parametrize("client_class", [EkmServiceClient, EkmServiceAsyncClient]) +@mock.patch.object( + EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient) +) +@mock.patch.object( + EkmServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EkmServiceAsyncClient), +) def test_ekm_service_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + 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 @@ -333,8 +417,12 @@ def test_ekm_service_client_get_mtls_endpoint_and_cert_source(client_class): 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) + 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 @@ -352,30 +440,49 @@ def test_ekm_service_client_get_mtls_endpoint_and_cert_source(client_class): # 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): + 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() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_ekm_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_ekm_service_client_client_options_scopes( + client_class, transport_class, transport_name +): # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -389,17 +496,26 @@ def test_ekm_service_client_client_options_scopes(client_class, transport_class, always_use_jwt_access=True, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_ekm_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_ekm_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -413,12 +529,13 @@ def test_ekm_service_client_client_options_credentials_file(client_class, transp always_use_jwt_access=True, ) + def test_ekm_service_client_client_options_from_dict(): - with mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None - client = EkmServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) + client = EkmServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) grpc_transport.assert_called_once_with( credentials=None, credentials_file=None, @@ -431,17 +548,25 @@ def test_ekm_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_ekm_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), + ( + EkmServiceAsyncClient, + transports.EkmServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_ekm_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -474,9 +599,9 @@ def test_ekm_service_client_create_channel_credentials_file(client_class, transp credentials_file=None, quota_project_id=None, default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), scopes=None, default_host="cloudkms.googleapis.com", ssl_credentials=None, @@ -487,14 +612,10 @@ def test_ekm_service_client_create_channel_credentials_file(client_class, transp ) -@pytest.mark.parametrize("request_type", [ - ekm_service.ListEkmConnectionsRequest, - dict, -]) -def test_list_ekm_connections(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize("request_type", [ekm_service.ListEkmConnectionsRequest, dict,]) +def test_list_ekm_connections(request_type, transport: str = "grpc"): client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -503,12 +624,11 @@ def test_list_ekm_connections(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: + type(client.transport.list_ekm_connections), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.ListEkmConnectionsResponse( - next_page_token='next_page_token_value', - total_size=1086, + next_page_token="next_page_token_value", total_size=1086, ) response = client.list_ekm_connections(request) @@ -519,7 +639,7 @@ def test_list_ekm_connections(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEkmConnectionsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" assert response.total_size == 1086 @@ -527,14 +647,13 @@ def test_list_ekm_connections_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: + type(client.transport.list_ekm_connections), "__call__" + ) as call: client.list_ekm_connections() call.assert_called() _, args, _ = call.mock_calls[0] @@ -542,10 +661,11 @@ def test_list_ekm_connections_empty_call(): @pytest.mark.asyncio -async def test_list_ekm_connections_async(transport: str = 'grpc_asyncio', request_type=ekm_service.ListEkmConnectionsRequest): +async def test_list_ekm_connections_async( + transport: str = "grpc_asyncio", request_type=ekm_service.ListEkmConnectionsRequest +): client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -554,13 +674,14 @@ async def test_list_ekm_connections_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: + type(client.transport.list_ekm_connections), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.ListEkmConnectionsResponse( + next_page_token="next_page_token_value", total_size=1086, + ) + ) response = await client.list_ekm_connections(request) # Establish that the underlying gRPC stub method was called. @@ -570,7 +691,7 @@ async def test_list_ekm_connections_async(transport: str = 'grpc_asyncio', reque # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEkmConnectionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" assert response.total_size == 1086 @@ -580,20 +701,18 @@ async def test_list_ekm_connections_async_from_dict(): def test_list_ekm_connections_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ekm_service.ListEkmConnectionsRequest() - request.parent = 'parent/value' + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: + type(client.transport.list_ekm_connections), "__call__" + ) as call: call.return_value = ekm_service.ListEkmConnectionsResponse() client.list_ekm_connections(request) @@ -604,29 +723,26 @@ def test_list_ekm_connections_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] @pytest.mark.asyncio async def test_list_ekm_connections_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ekm_service.ListEkmConnectionsRequest() - request.parent = 'parent/value' + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse()) + type(client.transport.list_ekm_connections), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.ListEkmConnectionsResponse() + ) await client.list_ekm_connections(request) # Establish that the underlying gRPC stub method was called. @@ -636,106 +752,90 @@ async def test_list_ekm_connections_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_list_ekm_connections_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: + type(client.transport.list_ekm_connections), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.ListEkmConnectionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_ekm_connections( - parent='parent_value', - ) + client.list_ekm_connections(parent="parent_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val def test_list_ekm_connections_flattened_error(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.list_ekm_connections( - ekm_service.ListEkmConnectionsRequest(), - parent='parent_value', + ekm_service.ListEkmConnectionsRequest(), parent="parent_value", ) @pytest.mark.asyncio async def test_list_ekm_connections_flattened_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: + type(client.transport.list_ekm_connections), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.ListEkmConnectionsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.ListEkmConnectionsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_ekm_connections( - parent='parent_value', - ) + response = await client.list_ekm_connections(parent="parent_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio async def test_list_ekm_connections_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.list_ekm_connections( - ekm_service.ListEkmConnectionsRequest(), - parent='parent_value', + ekm_service.ListEkmConnectionsRequest(), parent="parent_value", ) def test_list_ekm_connections_pager(transport_name: str = "grpc"): client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: + type(client.transport.list_ekm_connections), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( ekm_service.ListEkmConnectionsResponse( @@ -744,17 +844,13 @@ def test_list_ekm_connections_pager(transport_name: str = "grpc"): ekm_service.EkmConnection(), ekm_service.EkmConnection(), ], - next_page_token='abc', + next_page_token="abc", ), ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', + ekm_connections=[], next_page_token="def", ), ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', + ekm_connections=[ekm_service.EkmConnection(),], next_page_token="ghi", ), ekm_service.ListEkmConnectionsResponse( ekm_connections=[ @@ -767,9 +863,7 @@ def test_list_ekm_connections_pager(transport_name: str = "grpc"): metadata = () metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_ekm_connections(request={}) @@ -777,18 +871,18 @@ def test_list_ekm_connections_pager(transport_name: str = "grpc"): results = [i for i in pager] assert len(results) == 6 - assert all(isinstance(i, ekm_service.EkmConnection) - for i in results) + assert all(isinstance(i, ekm_service.EkmConnection) for i in results) + + def test_list_ekm_connections_pages(transport_name: str = "grpc"): client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, + credentials=ga_credentials.AnonymousCredentials, transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: + type(client.transport.list_ekm_connections), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( ekm_service.ListEkmConnectionsResponse( @@ -797,17 +891,13 @@ def test_list_ekm_connections_pages(transport_name: str = "grpc"): ekm_service.EkmConnection(), ekm_service.EkmConnection(), ], - next_page_token='abc', + next_page_token="abc", ), ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', + ekm_connections=[], next_page_token="def", ), ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', + ekm_connections=[ekm_service.EkmConnection(),], next_page_token="ghi", ), ekm_service.ListEkmConnectionsResponse( ekm_connections=[ @@ -818,19 +908,20 @@ def test_list_ekm_connections_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_ekm_connections(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token + @pytest.mark.asyncio async def test_list_ekm_connections_async_pager(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_ekm_connections), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( ekm_service.ListEkmConnectionsResponse( @@ -839,17 +930,13 @@ async def test_list_ekm_connections_async_pager(): ekm_service.EkmConnection(), ekm_service.EkmConnection(), ], - next_page_token='abc', + next_page_token="abc", ), ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', + ekm_connections=[], next_page_token="def", ), ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', + ekm_connections=[ekm_service.EkmConnection(),], next_page_token="ghi", ), ekm_service.ListEkmConnectionsResponse( ekm_connections=[ @@ -860,26 +947,25 @@ async def test_list_ekm_connections_async_pager(): RuntimeError, ) async_pager = await client.list_ekm_connections(request={},) - assert async_pager.next_page_token == 'abc' + assert async_pager.next_page_token == "abc" responses = [] async for response in async_pager: responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, ekm_service.EkmConnection) - for i in responses) + assert all(isinstance(i, ekm_service.EkmConnection) for i in responses) @pytest.mark.asyncio async def test_list_ekm_connections_async_pages(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_ekm_connections), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( ekm_service.ListEkmConnectionsResponse( @@ -888,17 +974,13 @@ async def test_list_ekm_connections_async_pages(): ekm_service.EkmConnection(), ekm_service.EkmConnection(), ], - next_page_token='abc', + next_page_token="abc", ), ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', + ekm_connections=[], next_page_token="def", ), ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', + ekm_connections=[ekm_service.EkmConnection(),], next_page_token="ghi", ), ekm_service.ListEkmConnectionsResponse( ekm_connections=[ @@ -911,17 +993,14 @@ async def test_list_ekm_connections_async_pages(): pages = [] async for page_ in (await client.list_ekm_connections(request={})).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize("request_type", [ - ekm_service.GetEkmConnectionRequest, - dict, -]) -def test_get_ekm_connection(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize("request_type", [ekm_service.GetEkmConnectionRequest, dict,]) +def test_get_ekm_connection(request_type, transport: str = "grpc"): client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -930,12 +1009,11 @@ def test_get_ekm_connection(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: + type(client.transport.get_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', + name="name_value", etag="etag_value", ) response = client.get_ekm_connection(request) @@ -946,22 +1024,21 @@ def test_get_ekm_connection(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" def test_get_ekm_connection_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: + type(client.transport.get_ekm_connection), "__call__" + ) as call: client.get_ekm_connection() call.assert_called() _, args, _ = call.mock_calls[0] @@ -969,10 +1046,11 @@ def test_get_ekm_connection_empty_call(): @pytest.mark.asyncio -async def test_get_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.GetEkmConnectionRequest): +async def test_get_ekm_connection_async( + transport: str = "grpc_asyncio", request_type=ekm_service.GetEkmConnectionRequest +): client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -981,13 +1059,12 @@ async def test_get_ekm_connection_async(transport: str = 'grpc_asyncio', request # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: + type(client.transport.get_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection(name="name_value", etag="etag_value",) + ) response = await client.get_ekm_connection(request) # Establish that the underlying gRPC stub method was called. @@ -997,8 +1074,8 @@ async def test_get_ekm_connection_async(transport: str = 'grpc_asyncio', request # Establish that the response is the type that we expect. assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio @@ -1007,20 +1084,18 @@ async def test_get_ekm_connection_async_from_dict(): def test_get_ekm_connection_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ekm_service.GetEkmConnectionRequest() - request.name = 'name/value' + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: + type(client.transport.get_ekm_connection), "__call__" + ) as call: call.return_value = ekm_service.EkmConnection() client.get_ekm_connection(request) @@ -1031,29 +1106,26 @@ def test_get_ekm_connection_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] @pytest.mark.asyncio async def test_get_ekm_connection_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ekm_service.GetEkmConnectionRequest() - request.name = 'name/value' + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + type(client.transport.get_ekm_connection), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) await client.get_ekm_connection(request) # Establish that the underlying gRPC stub method was called. @@ -1063,104 +1135,87 @@ async def test_get_ekm_connection_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_get_ekm_connection_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: + type(client.transport.get_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_ekm_connection( - name='name_value', - ) + client.get_ekm_connection(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val def test_get_ekm_connection_flattened_error(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_ekm_connection( - ekm_service.GetEkmConnectionRequest(), - name='name_value', + ekm_service.GetEkmConnectionRequest(), name="name_value", ) @pytest.mark.asyncio async def test_get_ekm_connection_flattened_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: + type(client.transport.get_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_ekm_connection( - name='name_value', - ) + response = await client.get_ekm_connection(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio async def test_get_ekm_connection_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_ekm_connection( - ekm_service.GetEkmConnectionRequest(), - name='name_value', + ekm_service.GetEkmConnectionRequest(), name="name_value", ) -@pytest.mark.parametrize("request_type", [ - ekm_service.CreateEkmConnectionRequest, - dict, -]) -def test_create_ekm_connection(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", [ekm_service.CreateEkmConnectionRequest, dict,] +) +def test_create_ekm_connection(request_type, transport: str = "grpc"): client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1169,12 +1224,11 @@ def test_create_ekm_connection(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: + type(client.transport.create_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', + name="name_value", etag="etag_value", ) response = client.create_ekm_connection(request) @@ -1185,22 +1239,21 @@ def test_create_ekm_connection(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" def test_create_ekm_connection_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: + type(client.transport.create_ekm_connection), "__call__" + ) as call: client.create_ekm_connection() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1208,10 +1261,11 @@ def test_create_ekm_connection_empty_call(): @pytest.mark.asyncio -async def test_create_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.CreateEkmConnectionRequest): +async def test_create_ekm_connection_async( + transport: str = "grpc_asyncio", request_type=ekm_service.CreateEkmConnectionRequest +): client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1220,13 +1274,12 @@ async def test_create_ekm_connection_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: + type(client.transport.create_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection(name="name_value", etag="etag_value",) + ) response = await client.create_ekm_connection(request) # Establish that the underlying gRPC stub method was called. @@ -1236,8 +1289,8 @@ async def test_create_ekm_connection_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio @@ -1246,20 +1299,18 @@ async def test_create_ekm_connection_async_from_dict(): def test_create_ekm_connection_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ekm_service.CreateEkmConnectionRequest() - request.parent = 'parent/value' + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: + type(client.transport.create_ekm_connection), "__call__" + ) as call: call.return_value = ekm_service.EkmConnection() client.create_ekm_connection(request) @@ -1270,29 +1321,26 @@ def test_create_ekm_connection_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] @pytest.mark.asyncio async def test_create_ekm_connection_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ekm_service.CreateEkmConnectionRequest() - request.parent = 'parent/value' + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + type(client.transport.create_ekm_connection), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) await client.create_ekm_connection(request) # Establish that the underlying gRPC stub method was called. @@ -1302,29 +1350,24 @@ async def test_create_ekm_connection_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent/value', - ) in kw['metadata'] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] def test_create_ekm_connection_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: + type(client.transport.create_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_ekm_connection( - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(name='name_value'), + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -1332,52 +1375,50 @@ def test_create_ekm_connection_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].ekm_connection_id - mock_val = 'ekm_connection_id_value' + mock_val = "ekm_connection_id_value" assert arg == mock_val arg = args[0].ekm_connection - mock_val = ekm_service.EkmConnection(name='name_value') + mock_val = ekm_service.EkmConnection(name="name_value") assert arg == mock_val def test_create_ekm_connection_flattened_error(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.create_ekm_connection( ekm_service.CreateEkmConnectionRequest(), - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(name='name_value'), + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), ) @pytest.mark.asyncio async def test_create_ekm_connection_flattened_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: + type(client.transport.create_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_ekm_connection( - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(name='name_value'), + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -1385,41 +1426,37 @@ async def test_create_ekm_connection_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].ekm_connection_id - mock_val = 'ekm_connection_id_value' + mock_val = "ekm_connection_id_value" assert arg == mock_val arg = args[0].ekm_connection - mock_val = ekm_service.EkmConnection(name='name_value') + mock_val = ekm_service.EkmConnection(name="name_value") assert arg == mock_val @pytest.mark.asyncio async def test_create_ekm_connection_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.create_ekm_connection( ekm_service.CreateEkmConnectionRequest(), - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(name='name_value'), + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ekm_connection=ekm_service.EkmConnection(name="name_value"), ) -@pytest.mark.parametrize("request_type", [ - ekm_service.UpdateEkmConnectionRequest, - dict, -]) -def test_update_ekm_connection(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", [ekm_service.UpdateEkmConnectionRequest, dict,] +) +def test_update_ekm_connection(request_type, transport: str = "grpc"): client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1428,12 +1465,11 @@ def test_update_ekm_connection(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: + type(client.transport.update_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', + name="name_value", etag="etag_value", ) response = client.update_ekm_connection(request) @@ -1444,22 +1480,21 @@ def test_update_ekm_connection(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" def test_update_ekm_connection_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: + type(client.transport.update_ekm_connection), "__call__" + ) as call: client.update_ekm_connection() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1467,10 +1502,11 @@ def test_update_ekm_connection_empty_call(): @pytest.mark.asyncio -async def test_update_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.UpdateEkmConnectionRequest): +async def test_update_ekm_connection_async( + transport: str = "grpc_asyncio", request_type=ekm_service.UpdateEkmConnectionRequest +): client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1479,13 +1515,12 @@ async def test_update_ekm_connection_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: + type(client.transport.update_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection(name="name_value", etag="etag_value",) + ) response = await client.update_ekm_connection(request) # Establish that the underlying gRPC stub method was called. @@ -1495,8 +1530,8 @@ async def test_update_ekm_connection_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio @@ -1505,20 +1540,18 @@ async def test_update_ekm_connection_async_from_dict(): def test_update_ekm_connection_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ekm_service.UpdateEkmConnectionRequest() - request.ekm_connection.name = 'ekm_connection.name/value' + request.ekm_connection.name = "ekm_connection.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: + type(client.transport.update_ekm_connection), "__call__" + ) as call: call.return_value = ekm_service.EkmConnection() client.update_ekm_connection(request) @@ -1530,28 +1563,28 @@ def test_update_ekm_connection_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'ekm_connection.name=ekm_connection.name/value', - ) in kw['metadata'] + "x-goog-request-params", + "ekm_connection.name=ekm_connection.name/value", + ) in kw["metadata"] @pytest.mark.asyncio async def test_update_ekm_connection_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = ekm_service.UpdateEkmConnectionRequest() - request.ekm_connection.name = 'ekm_connection.name/value' + request.ekm_connection.name = "ekm_connection.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + type(client.transport.update_ekm_connection), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) await client.update_ekm_connection(request) # Establish that the underlying gRPC stub method was called. @@ -1562,27 +1595,25 @@ async def test_update_ekm_connection_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'ekm_connection.name=ekm_connection.name/value', - ) in kw['metadata'] + "x-goog-request-params", + "ekm_connection.name=ekm_connection.name/value", + ) in kw["metadata"] def test_update_ekm_connection_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: + type(client.transport.update_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_ekm_connection( - ekm_connection=ekm_service.EkmConnection(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1590,47 +1621,45 @@ def test_update_ekm_connection_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].ekm_connection - mock_val = ekm_service.EkmConnection(name='name_value') + mock_val = ekm_service.EkmConnection(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val def test_update_ekm_connection_flattened_error(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.update_ekm_connection( ekm_service.UpdateEkmConnectionRequest(), - ekm_connection=ekm_service.EkmConnection(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_ekm_connection_flattened_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: + type(client.transport.update_ekm_connection), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = ekm_service.EkmConnection() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + ekm_service.EkmConnection() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_ekm_connection( - ekm_connection=ekm_service.EkmConnection(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1638,26 +1667,24 @@ async def test_update_ekm_connection_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].ekm_connection - mock_val = ekm_service.EkmConnection(name='name_value') + mock_val = ekm_service.EkmConnection(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio async def test_update_ekm_connection_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.update_ekm_connection( ekm_service.UpdateEkmConnectionRequest(), - ekm_connection=ekm_service.EkmConnection(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ekm_connection=ekm_service.EkmConnection(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1668,8 +1695,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. @@ -1689,18 +1715,14 @@ def test_credentials_transport_error(): options = client_options.ClientOptions() options.api_key = "api_key" with pytest.raises(ValueError): - client = EkmServiceClient( - client_options=options, - transport=transport, - ) + client = EkmServiceClient(client_options=options, transport=transport,) # It is an error to provide an api_key and a credential. options = mock.Mock() options.api_key = "api_key" with pytest.raises(ValueError): client = EkmServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() + client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -1709,8 +1731,7 @@ def test_credentials_transport_error(): ) with pytest.raises(ValueError): client = EkmServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client_options={"scopes": ["1", "2"]}, transport=transport, ) @@ -1722,6 +1743,7 @@ def test_transport_instance(): client = EkmServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EkmServiceGrpcTransport( @@ -1736,39 +1758,39 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.EkmServiceGrpcTransport, - transports.EkmServiceGrpcAsyncIOTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport,], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() + def test_transport_grpc_default(): # A client should use the gRPC transport by default. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EkmServiceGrpcTransport, - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.EkmServiceGrpcTransport,) + def test_ekm_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EkmServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_ekm_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport.__init__') as Transport: + with mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.EkmServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -1777,13 +1799,13 @@ def test_ekm_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'list_ekm_connections', - 'get_ekm_connection', - 'create_ekm_connection', - 'update_ekm_connection', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', + "list_ekm_connections", + "get_ekm_connection", + "create_ekm_connection", + "update_ekm_connection", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", ) for method in methods: with pytest.raises(NotImplementedError): @@ -1795,26 +1817,32 @@ def test_ekm_service_base_transport(): def test_ekm_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EkmServiceTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + 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', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), quota_project_id="octopus", ) def test_ekm_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EkmServiceTransport() @@ -1823,35 +1851,35 @@ def test_ekm_service_base_transport_with_adc(): def test_ekm_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) EkmServiceClient() adc.assert_called_once_with( scopes=None, default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), quota_project_id=None, ) @pytest.mark.parametrize( "transport_class", - [ - transports.EkmServiceGrpcTransport, - transports.EkmServiceGrpcAsyncIOTransport, - ], + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport,], ) def test_ekm_service_transport_auth_adc(transport_class): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + 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',), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), quota_project_id="octopus", ) @@ -1860,21 +1888,20 @@ def test_ekm_service_transport_auth_adc(transport_class): "transport_class,grpc_helpers", [ (transports.EkmServiceGrpcTransport, grpc_helpers), - (transports.EkmServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.EkmServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): # If credentials and host are not provided, the transport class should use # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "cloudkms.googleapis.com:443", @@ -1882,9 +1909,9 @@ def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): credentials_file=None, quota_project_id="octopus", default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), scopes=["1", "2"], default_host="cloudkms.googleapis.com", ssl_credentials=None, @@ -1895,10 +1922,11 @@ def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) -def test_ekm_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -1907,7 +1935,7 @@ def test_ekm_service_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -1928,37 +1956,40 @@ def test_ekm_service_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) def test_ekm_service_host_no_port(): client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com" + ), ) - assert client.transport._host == 'cloudkms.googleapis.com:443' + assert client.transport._host == "cloudkms.googleapis.com:443" def test_ekm_service_host_with_port(): client = EkmServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="cloudkms.googleapis.com:8000" + ), ) - assert client.transport._host == 'cloudkms.googleapis.com:8000' + assert client.transport._host == "cloudkms.googleapis.com:8000" + def test_ekm_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.EkmServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -1966,12 +1997,11 @@ def test_ekm_service_grpc_transport_channel(): def test_ekm_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.EkmServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + host="squid.clam.whelk", channel=channel, ) assert transport.grpc_channel == channel assert transport._host == "squid.clam.whelk:443" @@ -1980,12 +2010,17 @@ def test_ekm_service_grpc_asyncio_transport_channel(): # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) -def test_ekm_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: mock_ssl_cred = mock.Mock() grpc_ssl_channel_cred.return_value = mock_ssl_cred @@ -1994,7 +2029,7 @@ def test_ekm_service_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2024,17 +2059,20 @@ def test_ekm_service_transport_channel_mtls_with_client_cert_source( # Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are # removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) -def test_ekm_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport], +) +def test_ekm_service_transport_channel_mtls_with_adc(transport_class): mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + 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() @@ -2066,7 +2104,9 @@ def test_ekm_connection_path(): project = "squid" location = "clam" ekm_connection = "whelk" - expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format(project=project, location=location, ekm_connection=ekm_connection, ) + expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format( + project=project, location=location, ekm_connection=ekm_connection, + ) actual = EkmServiceClient.ekm_connection_path(project, location, ekm_connection) assert expected == actual @@ -2083,12 +2123,15 @@ def test_parse_ekm_connection_path(): actual = EkmServiceClient.parse_ekm_connection_path(path) assert expected == actual + def test_service_path(): project = "cuttlefish" location = "mussel" namespace = "winkle" service = "nautilus" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) actual = EkmServiceClient.service_path(project, location, namespace, service) assert expected == actual @@ -2106,9 +2149,12 @@ def test_parse_service_path(): actual = EkmServiceClient.parse_service_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = EkmServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2123,9 +2169,10 @@ def test_parse_common_billing_account_path(): actual = EkmServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format(folder=folder,) actual = EkmServiceClient.common_folder_path(folder) assert expected == actual @@ -2140,9 +2187,10 @@ def test_parse_common_folder_path(): actual = EkmServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format(organization=organization,) actual = EkmServiceClient.common_organization_path(organization) assert expected == actual @@ -2157,9 +2205,10 @@ def test_parse_common_organization_path(): actual = EkmServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format(project=project,) actual = EkmServiceClient.common_project_path(project) assert expected == actual @@ -2174,10 +2223,13 @@ def test_parse_common_project_path(): actual = EkmServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) actual = EkmServiceClient.common_location_path(project, location) assert expected == actual @@ -2197,18 +2249,20 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.EkmServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.EkmServiceTransport, "_prep_wrapped_messages" + ) as prep: client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.EkmServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.EkmServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = EkmServiceClient.get_transport_class() transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2254,9 +2308,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): 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: + 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",) @@ -2279,9 +2331,7 @@ async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): def test_set_iam_policy_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -2306,9 +2356,7 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -2316,9 +2364,7 @@ async def test_set_iam_policy_field_headers_async(): 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: + 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) @@ -2334,9 +2380,7 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. @@ -2353,15 +2397,11 @@ def test_set_iam_policy_from_dict(): @pytest.mark.asyncio async def test_set_iam_policy_from_dict_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.set_iam_policy( request={ @@ -2413,9 +2453,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): 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: + 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",) @@ -2438,9 +2476,7 @@ async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): def test_get_iam_policy_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -2465,9 +2501,7 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -2475,9 +2509,7 @@ async def test_get_iam_policy_field_headers_async(): 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: + 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) @@ -2493,9 +2525,7 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. @@ -2509,17 +2539,14 @@ def test_get_iam_policy_from_dict(): ) call.assert_called() + @pytest.mark.asyncio async def test_get_iam_policy_from_dict_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) response = await client.get_iam_policy( request={ @@ -2578,7 +2605,9 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) response = await client.test_iam_permissions(request) @@ -2596,9 +2625,7 @@ async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): def test_test_iam_permissions_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -2625,9 +2652,7 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. @@ -2655,9 +2680,7 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" @@ -2673,11 +2696,10 @@ def test_test_iam_permissions_from_dict(): ) call.assert_called() + @pytest.mark.asyncio async def test_test_iam_permissions_from_dict_async(): - client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) + client = EkmServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" @@ -2699,14 +2721,16 @@ async def test_test_iam_permissions_from_dict_async(): @pytest.mark.asyncio async def test_transport_close_async(): client = EkmServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + 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", @@ -2714,22 +2738,23 @@ def test_transport_close(): for transport, close_name in transports.items(): client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + 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', + "grpc", ] for transport in transports: client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -2738,10 +2763,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (EkmServiceClient, transports.EkmServiceGrpcTransport), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True diff --git a/tests/unit/gapic/kms_v1/test_key_management_service.py b/tests/unit/gapic/kms_v1/test_key_management_service.py index 68c2de4e..f05188f8 100644 --- a/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -539,25 +539,28 @@ def test_key_management_service_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ ( KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", + grpc_helpers, ), ( KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_key_management_service_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) @@ -593,6 +596,75 @@ def test_key_management_service_client_client_options_from_dict(): ) +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + KeyManagementServiceClient, + transports.KeyManagementServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + KeyManagementServiceAsyncClient, + transports.KeyManagementServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_key_management_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloudkms", + ), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize("request_type", [service.ListKeyRingsRequest, dict,]) def test_list_key_rings(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( @@ -2295,6 +2367,7 @@ def test_get_crypto_key(request_type, transport: str = "grpc"): name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", rotation_period=duration_pb2.Duration(seconds=751), ) response = client.get_crypto_key(request) @@ -2309,6 +2382,7 @@ def test_get_crypto_key(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" def test_get_crypto_key_empty_call(): @@ -2346,6 +2420,7 @@ async def test_get_crypto_key_async( name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.get_crypto_key(request) @@ -2360,6 +2435,7 @@ async def test_get_crypto_key_async( assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio @@ -3453,6 +3529,7 @@ def test_create_crypto_key(request_type, transport: str = "grpc"): name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", rotation_period=duration_pb2.Duration(seconds=751), ) response = client.create_crypto_key(request) @@ -3467,6 +3544,7 @@ def test_create_crypto_key(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" def test_create_crypto_key_empty_call(): @@ -3508,6 +3586,7 @@ async def test_create_crypto_key_async( name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.create_crypto_key(request) @@ -3522,6 +3601,7 @@ async def test_create_crypto_key_async( assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio @@ -4432,6 +4512,7 @@ def test_update_crypto_key(request_type, transport: str = "grpc"): name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", rotation_period=duration_pb2.Duration(seconds=751), ) response = client.update_crypto_key(request) @@ -4446,6 +4527,7 @@ def test_update_crypto_key(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" def test_update_crypto_key_empty_call(): @@ -4487,6 +4569,7 @@ async def test_update_crypto_key_async( name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.update_crypto_key(request) @@ -4501,6 +4584,7 @@ async def test_update_crypto_key_async( assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio @@ -4967,6 +5051,7 @@ def test_update_crypto_key_primary_version(request_type, transport: str = "grpc" name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", rotation_period=duration_pb2.Duration(seconds=751), ) response = client.update_crypto_key_primary_version(request) @@ -4981,6 +5066,7 @@ def test_update_crypto_key_primary_version(request_type, transport: str = "grpc" assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" def test_update_crypto_key_primary_version_empty_call(): @@ -5023,6 +5109,7 @@ async def test_update_crypto_key_primary_version_async( name="name_value", purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) response = await client.update_crypto_key_primary_version(request) @@ -5037,6 +5124,7 @@ async def test_update_crypto_key_primary_version_async( assert response.name == "name_value" assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" @pytest.mark.asyncio