From b8122cf41f10499034d0f53772f5eebd26e24720 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 23 Jul 2021 20:57:54 +0000 Subject: [PATCH 1/2] fix: enable self signed jwt for grpc chore: use gapic-generator-python 0.50.5 PiperOrigin-RevId: 386504689 Source-Link: https://github.com/googleapis/googleapis/commit/762094a99ac6e03a17516b13dfbef37927267a70 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6bfc480e1a161d5de121c2bcc3745885d33b265a --- 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 + .../securitycenter_v1/security_center.rst | 10 + .../v1/docs/securitycenter_v1/services.rst | 6 + .../v1/docs/securitycenter_v1/types.rst | 7 + .../google/cloud/securitycenter/__init__.py | 97 + .../v1/google/cloud/securitycenter/py.typed | 2 + .../cloud/securitycenter_v1/__init__.py | 98 + .../securitycenter_v1/gapic_metadata.json | 253 + .../google/cloud/securitycenter_v1/py.typed | 2 + .../securitycenter_v1/services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 2340 +++++ .../services/security_center/client.py | 2510 ++++++ .../services/security_center/pagers.py | 752 ++ .../security_center/transports/__init__.py | 33 + .../security_center/transports/base.py | 572 ++ .../security_center/transports/grpc.py | 876 ++ .../transports/grpc_asyncio.py | 880 ++ .../cloud/securitycenter_v1/types/__init__.py | 114 + .../cloud/securitycenter_v1/types/asset.py | 223 + .../cloud/securitycenter_v1/types/finding.py | 178 + .../cloud/securitycenter_v1/types/folder.py | 50 + .../types/notification_config.py | 115 + .../types/notification_message.py | 61 + .../types/organization_settings.py | 104 + .../cloud/securitycenter_v1/types/resource.py | 80 + .../types/run_asset_discovery_response.py | 57 + .../securitycenter_v1/types/security_marks.py | 76 + .../types/securitycenter_service.py | 1611 ++++ .../cloud/securitycenter_v1/types/source.py | 83 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../fixup_securitycenter_v1_keywords.py | 198 + owl-bot-staging/v1/setup.py | 54 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/securitycenter_v1/__init__.py | 16 + .../securitycenter_v1/test_security_center.py | 7619 ++++++++++++++++ owl-bot-staging/v1beta1/.coveragerc | 17 + owl-bot-staging/v1beta1/MANIFEST.in | 2 + owl-bot-staging/v1beta1/README.rst | 49 + owl-bot-staging/v1beta1/docs/conf.py | 376 + owl-bot-staging/v1beta1/docs/index.rst | 7 + .../security_center.rst | 10 + .../docs/securitycenter_v1beta1/services.rst | 6 + .../docs/securitycenter_v1beta1/types.rst | 7 + .../google/cloud/securitycenter/__init__.py | 77 + .../google/cloud/securitycenter/py.typed | 2 + .../cloud/securitycenter_v1beta1/__init__.py | 78 + .../gapic_metadata.json | 203 + .../cloud/securitycenter_v1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 1886 ++++ .../services/security_center/client.py | 2052 +++++ .../services/security_center/pagers.py | 630 ++ .../security_center/transports/__init__.py | 33 + .../security_center/transports/base.py | 485 + .../security_center/transports/grpc.py | 742 ++ .../transports/grpc_asyncio.py | 746 ++ .../securitycenter_v1beta1/types/__init__.py | 86 + .../securitycenter_v1beta1/types/asset.py | 151 + .../securitycenter_v1beta1/types/finding.py | 148 + .../types/organization_settings.py | 96 + .../types/run_asset_discovery_response.py | 57 + .../types/security_marks.py | 64 + .../types/securitycenter_service.py | 1016 +++ .../securitycenter_v1beta1/types/source.py | 72 + owl-bot-staging/v1beta1/mypy.ini | 3 + owl-bot-staging/v1beta1/noxfile.py | 132 + .../fixup_securitycenter_v1beta1_keywords.py | 193 + owl-bot-staging/v1beta1/setup.py | 54 + owl-bot-staging/v1beta1/tests/__init__.py | 16 + .../v1beta1/tests/unit/__init__.py | 16 + .../v1beta1/tests/unit/gapic/__init__.py | 16 + .../gapic/securitycenter_v1beta1/__init__.py | 16 + .../test_security_center.py | 6133 +++++++++++++ owl-bot-staging/v1p1beta1/.coveragerc | 17 + owl-bot-staging/v1p1beta1/MANIFEST.in | 2 + owl-bot-staging/v1p1beta1/README.rst | 49 + owl-bot-staging/v1p1beta1/docs/conf.py | 376 + owl-bot-staging/v1p1beta1/docs/index.rst | 7 + .../security_center.rst | 10 + .../securitycenter_v1p1beta1/services.rst | 6 + .../docs/securitycenter_v1p1beta1/types.rst | 7 + .../google/cloud/securitycenter/__init__.py | 97 + .../google/cloud/securitycenter/py.typed | 2 + .../securitycenter_v1p1beta1/__init__.py | 98 + .../gapic_metadata.json | 253 + .../cloud/securitycenter_v1p1beta1/py.typed | 2 + .../services/__init__.py | 15 + .../services/security_center/__init__.py | 22 + .../services/security_center/async_client.py | 2432 +++++ .../services/security_center/client.py | 2600 ++++++ .../services/security_center/pagers.py | 752 ++ .../security_center/transports/__init__.py | 33 + .../security_center/transports/base.py | 572 ++ .../security_center/transports/grpc.py | 877 ++ .../transports/grpc_asyncio.py | 881 ++ .../types/__init__.py | 114 + .../securitycenter_v1p1beta1/types/asset.py | 223 + .../securitycenter_v1p1beta1/types/finding.py | 180 + .../securitycenter_v1p1beta1/types/folder.py | 50 + .../types/notification_config.py | 126 + .../types/notification_message.py | 60 + .../types/organization_settings.py | 104 + .../types/resource.py | 80 + .../types/run_asset_discovery_response.py | 57 + .../types/security_marks.py | 76 + .../types/securitycenter_service.py | 1581 ++++ .../securitycenter_v1p1beta1/types/source.py | 83 + owl-bot-staging/v1p1beta1/mypy.ini | 3 + owl-bot-staging/v1p1beta1/noxfile.py | 132 + ...fixup_securitycenter_v1p1beta1_keywords.py | 198 + owl-bot-staging/v1p1beta1/setup.py | 54 + owl-bot-staging/v1p1beta1/tests/__init__.py | 16 + .../v1p1beta1/tests/unit/__init__.py | 16 + .../v1p1beta1/tests/unit/gapic/__init__.py | 16 + .../securitycenter_v1p1beta1/__init__.py | 16 + .../test_security_center.py | 7809 +++++++++++++++++ 125 files changed, 55568 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/securitycenter_v1/security_center.rst create mode 100644 owl-bot-staging/v1/docs/securitycenter_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/securitycenter_v1/types.rst create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/client.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/asset.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/finding.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/folder.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_config.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_message.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/organization_settings.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/resource.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/security_marks.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py create mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/source.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_securitycenter_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/securitycenter_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py create mode 100644 owl-bot-staging/v1beta1/.coveragerc create mode 100644 owl-bot-staging/v1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1beta1/README.rst create mode 100644 owl-bot-staging/v1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/security_center.rst create mode 100644 owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/services.rst create mode 100644 owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/types.rst create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/py.typed create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py create mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py create mode 100644 owl-bot-staging/v1beta1/mypy.ini create mode 100644 owl-bot-staging/v1beta1/noxfile.py create mode 100644 owl-bot-staging/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py create mode 100644 owl-bot-staging/v1beta1/setup.py create mode 100644 owl-bot-staging/v1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py create mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py create mode 100644 owl-bot-staging/v1p1beta1/.coveragerc create mode 100644 owl-bot-staging/v1p1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1p1beta1/README.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1p1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/services.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/types.rst create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter/py.typed create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py create mode 100644 owl-bot-staging/v1p1beta1/mypy.ini create mode 100644 owl-bot-staging/v1p1beta1/noxfile.py create mode 100644 owl-bot-staging/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py create mode 100644 owl-bot-staging/v1p1beta1/setup.py create mode 100644 owl-bot-staging/v1p1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..3655af7f --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__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..a18e3d0b --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..f8c63f4c --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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..f4837604 --- /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-securitycenter documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-securitycenter" +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-securitycenter-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-securitycenter.tex", + u"google-cloud-securitycenter Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-securitycenter", + u"Google Cloud Securitycenter Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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..47fc2db7 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1/services + securitycenter_v1/types diff --git a/owl-bot-staging/v1/docs/securitycenter_v1/security_center.rst b/owl-bot-staging/v1/docs/securitycenter_v1/security_center.rst new file mode 100644 index 00000000..bc6175c8 --- /dev/null +++ b/owl-bot-staging/v1/docs/securitycenter_v1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/securitycenter_v1/services.rst b/owl-bot-staging/v1/docs/securitycenter_v1/services.rst new file mode 100644 index 00000000..295acede --- /dev/null +++ b/owl-bot-staging/v1/docs/securitycenter_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1 API +=============================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/v1/docs/securitycenter_v1/types.rst b/owl-bot-staging/v1/docs/securitycenter_v1/types.rst new file mode 100644 index 00000000..460aec08 --- /dev/null +++ b/owl-bot-staging/v1/docs/securitycenter_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Securitycenter v1 API +============================================ + +.. automodule:: google.cloud.securitycenter_v1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter/__init__.py new file mode 100644 index 00000000..2626e614 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter/__init__.py @@ -0,0 +1,97 @@ +# -*- 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.securitycenter_v1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1.types.asset import Asset +from google.cloud.securitycenter_v1.types.finding import Finding +from google.cloud.securitycenter_v1.types.folder import Folder +from google.cloud.securitycenter_v1.types.notification_config import NotificationConfig +from google.cloud.securitycenter_v1.types.notification_message import NotificationMessage +from google.cloud.securitycenter_v1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1.types.resource import Resource +from google.cloud.securitycenter_v1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateNotificationConfigRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1.types.source import Source + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Asset', + 'Finding', + 'Folder', + 'NotificationConfig', + 'NotificationMessage', + 'OrganizationSettings', + 'Resource', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter/py.typed b/owl-bot-staging/v1/google/cloud/securitycenter/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/__init__.py new file mode 100644 index 00000000..ca8f63fd --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/__init__.py @@ -0,0 +1,98 @@ +# -*- 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.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.asset import Asset +from .types.finding import Finding +from .types.folder import Folder +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.organization_settings import OrganizationSettings +from .types.resource import Resource +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source + +__all__ = ( + 'SecurityCenterAsyncClient', +'Asset', +'CreateFindingRequest', +'CreateNotificationConfigRequest', +'CreateSourceRequest', +'DeleteNotificationConfigRequest', +'Finding', +'Folder', +'GetNotificationConfigRequest', +'GetOrganizationSettingsRequest', +'GetSourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListNotificationConfigsRequest', +'ListNotificationConfigsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'NotificationConfig', +'NotificationMessage', +'OrganizationSettings', +'Resource', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityCenterClient', +'SecurityMarks', +'SetFindingStateRequest', +'Source', +'UpdateFindingRequest', +'UpdateNotificationConfigRequest', +'UpdateOrganizationSettingsRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/securitycenter_v1/gapic_metadata.json new file mode 100644 index 00000000..e3afaeec --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/gapic_metadata.json @@ -0,0 +1,253 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1", + "protoPackage": "google.cloud.securitycenter.v1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/py.typed b/owl-bot-staging/v1/google/cloud/securitycenter_v1/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_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/securitycenter_v1/services/security_center/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py new file mode 100644 index 00000000..fce6b0c5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py new file mode 100644 index 00000000..d5d056ed --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -0,0 +1,2340 @@ +# -*- 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1 APIs for Security Center service.""" + + _client: SecurityCenterClient + + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) + parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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, ~.SecurityCenterTransport]): 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_source(self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``source`` 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.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, source]) + 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 = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # 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_source, + 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_finding(self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` 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.securitycenter_v1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + 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 = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # 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_finding, + 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_notification_config(self, + request: securitycenter_service.CreateNotificationConfigRequest = None, + *, + parent: str = None, + config_id: str = None, + notification_config: gcs_notification_config.NotificationConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest`): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters, and + contains alphanumeric characters, + underscores or hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` 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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_config]) + 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 = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # 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_notification_config, + 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 delete_notification_config(self, + request: securitycenter_service.DeleteNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a notification config. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest`): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.DeleteNotificationConfigRequest(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.delete_notification_config, + 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_iam_policy(self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # 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_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(( + ("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_notification_config(self, + request: securitycenter_service.GetNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.GetNotificationConfigRequest`): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + + 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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.GetNotificationConfigRequest(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_notification_config, + 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_organization_settings(self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + 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.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings, + 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_source(self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + + 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.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.GetSourceRequest(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_source, + 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 group_assets(self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = securitycenter_service.GroupAssetsRequest(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.group_assets, + 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=480.0, + ), + default_timeout=480.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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Args: + request (:class:`google.cloud.securitycenter_v1.types.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` 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.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + 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 = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_findings, + 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=480.0, + ), + default_timeout=480.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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: securitycenter_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.ListAssetsRequest`): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = securitycenter_service.ListAssetsRequest(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.list_assets, + 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=480.0, + ), + default_timeout=480.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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: securitycenter_service.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`google.cloud.securitycenter_v1.types.ListFindingsRequest`): + The request object. Request message for listing + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = securitycenter_service.ListFindingsRequest(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.list_findings, + 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=480.0, + ), + default_timeout=480.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.ListFindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs(self, + request: securitycenter_service.ListNotificationConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest`): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + + 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs, + 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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". + + 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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.ListSourcesRequest(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_sources, + 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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp_pb2.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` 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.securitycenter_v1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + 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 = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # 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_finding_state, + 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 set_iam_policy(self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # 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=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(( + ("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, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # 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_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(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_finding(self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` 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.securitycenter_v1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + 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 = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # 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_finding, + 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(( + ("finding.name", request.finding.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_notification_config(self, + request: securitycenter_service.UpdateNotificationConfigRequest = None, + *, + notification_config: gcs_notification_config.NotificationConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Args: + request (:class:`google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + + 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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([notification_config, 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 = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_config + 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_notification_config, + 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(( + ("notification_config.name", request.notification_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_organization_settings(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` 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.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + 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 = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # 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_organization_settings, + 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(( + ("organization_settings.name", request.organization_settings.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_source(self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``source`` 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.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([source]) + 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 = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # 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_source, + 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(( + ("source.name", request.source.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_security_marks(self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` 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.securitycenter_v1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + 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 = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # 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_security_marks, + default_timeout=480.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(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Send the request. + response = await 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-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/client.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/client.py new file mode 100644 index 00000000..bdcd1cca --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/client.py @@ -0,0 +1,2510 @@ +# -*- 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1 APIs for Security Center service.""" + + @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 = "securitycenter.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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str,notification_config: str,) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str,str]: + """Parses a notification_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SecurityCenterTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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, SecurityCenterTransport]): 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # 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, SecurityCenterTransport): + # transport is a SecurityCenterTransport instance. + if credentials or client_options.credentials_file: + 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: + 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=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def create_source(self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (google.cloud.securitycenter_v1.types.CreateSourceRequest): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``source`` 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.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, source]) + 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 securitycenter_service.CreateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_source] + + # 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_finding(self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (google.cloud.securitycenter_v1.types.CreateFindingRequest): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` 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.securitycenter_v1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + 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 securitycenter_service.CreateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # 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_notification_config(self, + request: securitycenter_service.CreateNotificationConfigRequest = None, + *, + parent: str = None, + config_id: str = None, + notification_config: gcs_notification_config.NotificationConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + Args: + request (google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters, and + contains alphanumeric characters, + underscores or hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` 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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_config]) + 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 securitycenter_service.CreateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_config] + + # 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 delete_notification_config(self, + request: securitycenter_service.DeleteNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a notification config. + + Args: + request (google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.DeleteNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(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.delete_notification_config] + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_iam_policy(self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): + The request object. Request message for `GetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_notification_config(self, + request: securitycenter_service.GetNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + Args: + request (google.cloud.securitycenter_v1.types.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + + 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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(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_notification_config] + + # 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_organization_settings(self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + 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.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings] + + # 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_source(self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (google.cloud.securitycenter_v1.types.GetSourceRequest): + The request object. Request message for getting a + source. + name (str): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + + 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.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(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_source] + + # 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 group_assets(self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (google.cloud.securitycenter_v1.types.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # 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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Args: + request (google.cloud.securitycenter_v1.types.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` 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.securitycenter_v1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + 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 securitycenter_service.GroupFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_findings] + + # 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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: securitycenter_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + Args: + request (google.cloud.securitycenter_v1.types.ListAssetsRequest): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # 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.ListAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: securitycenter_service.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Args: + request (google.cloud.securitycenter_v1.types.ListFindingsRequest): + The request object. Request message for listing + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_findings] + + # 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.ListFindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs(self, + request: securitycenter_service.ListNotificationConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotificationConfigsPager: + r"""Lists notification configs. + + Args: + request (google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + parent (str): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + + 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListNotificationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs] + + # 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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + Args: + request (google.cloud.securitycenter_v1.types.ListSourcesRequest): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". + + 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.securitycenter_v1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListSourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(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_sources] + + # 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.ListSourcesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.RunAssetDiscoveryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp_pb2.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (google.cloud.securitycenter_v1.types.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + name (str): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` 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.securitycenter_v1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + 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 securitycenter_service.SetFindingStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_state] + + # 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 set_iam_policy(self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): + The request object. Request message for `SetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # 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, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): + The request object. Request message for + `TestIamPermissions` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (Sequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_finding(self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (google.cloud.securitycenter_v1.types.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` 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.securitycenter_v1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + 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 securitycenter_service.UpdateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_notification_config(self, + request: securitycenter_service.UpdateNotificationConfigRequest = None, + *, + notification_config: gcs_notification_config.NotificationConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Args: + request (google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + + 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.securitycenter_v1.types.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([notification_config, 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 securitycenter_service.UpdateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_config + 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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_organization_settings(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` 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.securitycenter_v1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + 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 securitycenter_service.UpdateOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_settings.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_source(self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (google.cloud.securitycenter_v1.types.UpdateSourceRequest): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``source`` 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.securitycenter_v1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([source]) + 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 securitycenter_service.UpdateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.source.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_security_marks(self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` 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.securitycenter_v1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + 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 securitycenter_service.UpdateSecurityMarksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # 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-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py new file mode 100644 index 00000000..bef157b5 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py @@ -0,0 +1,752 @@ +# -*- 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` + 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[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: + 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) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` + 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: + 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) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` + 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[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: + 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) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` + 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: + 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) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` + 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[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: + 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) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` + 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: + 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) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` + 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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + 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.securitycenter_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListFindingsResponse): + 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 = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: + 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) -> Iterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` + 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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + 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.securitycenter_v1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListFindingsResponse): + 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 = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: + 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) -> AsyncIterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` + 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[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListNotificationConfigsResponse]: + 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) -> Iterable[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` + 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[securitycenter_service.ListNotificationConfigsResponse]], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListNotificationConfigsResponse]: + 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) -> AsyncIterable[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` + 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[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: + 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) -> Iterable[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` + 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: + 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) -> AsyncIterable[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + 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/securitycenter_v1/services/security_center/transports/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..8bdaf713 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py new file mode 100644 index 00000000..3e6da749 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -0,0 +1,572 @@ +# -*- 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 packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-securitycenter', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.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 = self._get_scopes_kwargs(self._host, 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 is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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_notification_config: gapic_v1.method.wrap_method( + self.get_notification_config, + 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_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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_source: gapic_v1.method.wrap_method( + self.get_source, + 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.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_configs, + 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_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + 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 get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..fc23cf67 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py @@ -0,0 +1,876 @@ +# -*- 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 # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # 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 + +import grpc # type: ignore + +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1 APIs for Security Center service. + + 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 = 'securitycenter.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 applicatin 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 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 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'securitycenter.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_notification_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..b1461886 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,880 @@ +# -*- 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1 APIs for Security Center service. + + 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 = 'securitycenter.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 = 'securitycenter.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 applicatin 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 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 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_notification_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig]]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/__init__.py new file mode 100644 index 00000000..f490e7f6 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/__init__.py @@ -0,0 +1,114 @@ +# -*- 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 .asset import ( + Asset, +) +from .finding import ( + Finding, +) +from .folder import ( + Folder, +) +from .notification_config import ( + NotificationConfig, +) +from .notification_message import ( + NotificationMessage, +) +from .organization_settings import ( + OrganizationSettings, +) +from .resource import ( + Resource, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_marks import ( + SecurityMarks, +) +from .securitycenter_service import ( + CreateFindingRequest, + CreateNotificationConfigRequest, + CreateSourceRequest, + DeleteNotificationConfigRequest, + GetNotificationConfigRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + UpdateFindingRequest, + UpdateNotificationConfigRequest, + UpdateOrganizationSettingsRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .source import ( + Source, +) + +__all__ = ( + 'Asset', + 'Finding', + 'Folder', + 'NotificationConfig', + 'NotificationMessage', + 'OrganizationSettings', + 'Resource', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/asset.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/asset.py new file mode 100644 index 00000000..2552d58f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/asset.py @@ -0,0 +1,223 @@ +# -*- 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.securitycenter_v1.types import folder +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (Sequence[google.cloud.securitycenter_v1.types.Asset.ResourcePropertiesEntry]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated + or added in Cloud SCC. + iam_policy (google.cloud.securitycenter_v1.types.Asset.IamPolicy): + Cloud IAM Policy information associated with + the Google Cloud resource described by the + Security Command Center asset. This information + is managed and defined by the Google Cloud + resource and cannot be modified by the user. + canonical_name (str): + The canonical name of the resource. It's either + "organizations/{organization_id}/assets/{asset_id}", + "folders/{folder_id}/assets/{asset_id}" or + "projects/{project_number}/assets/{asset_id}", depending on + the closest CRM ancestor of the resource. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + The full resource name of the Google Cloud resource this + asset represents. This field is immutable after create time. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (Sequence[str]): + Owners of the Google Cloud resource. + resource_display_name (str): + The user defined display name for this + resource. + resource_parent_display_name (str): + The user defined display name for the parent + of this resource. + resource_project_display_name (str): + The user defined display name for the project + of this resource. + folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + resource_name = proto.Field( + proto.STRING, + number=1, + ) + resource_type = proto.Field( + proto.STRING, + number=2, + ) + resource_parent = proto.Field( + proto.STRING, + number=3, + ) + resource_project = proto.Field( + proto.STRING, + number=4, + ) + resource_owners = proto.RepeatedField( + proto.STRING, + number=5, + ) + resource_display_name = proto.Field( + proto.STRING, + number=6, + ) + resource_parent_display_name = proto.Field( + proto.STRING, + number=7, + ) + resource_project_display_name = proto.Field( + proto.STRING, + number=8, + ) + folders = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + class IamPolicy(proto.Message): + r"""Cloud IAM Policy information associated with the Google Cloud + resource described by the Security Command Center asset. This + information is managed and defined by the Google Cloud resource + and cannot be modified by the user. + + Attributes: + policy_blob (str): + The JSON representation of the Policy + associated with the asset. See + https://cloud.google.com/iam/reference/rest/v1/Policy + for format details. + """ + + policy_blob = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + iam_policy = proto.Field( + proto.MESSAGE, + number=11, + message=IamPolicy, + ) + canonical_name = proto.Field( + proto.STRING, + number=13, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/finding.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/finding.py new file mode 100644 index 00000000..7d29c2f4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/finding.py @@ -0,0 +1,178 @@ +# -*- 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.securitycenter_v1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + A finding is a record of assessment data like security, risk, + health, or privacy, that is ingested into Security Command + Center for presentation, notification, analysis, policy testing, + and enforcement. For example, a cross-site scripting (XSS) + vulnerability in an App Engine application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + The relative resource name of the source the finding belongs + to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (Sequence[google.cloud.securitycenter_v1.types.Finding.SourcePropertiesEntry]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the event took place, or + when an update to the finding occurred. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. If the finding + were to be resolved afterward, this time would + reflect when the finding was resolved. Must not + be set to a value greater than the current + timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + severity (google.cloud.securitycenter_v1.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" + or + "projects/{project_number}/sources/{source_id}/findings/{finding_id}", + depending on the closest CRM ancestor of the resource + associated with the finding. + """ + class State(proto.Enum): + r"""The state of the finding.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding.""" + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + name = proto.Field( + proto.STRING, + number=1, + ) + parent = proto.Field( + proto.STRING, + number=2, + ) + resource_name = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category = proto.Field( + proto.STRING, + number=5, + ) + external_uri = proto.Field( + proto.STRING, + number=6, + ) + source_properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + severity = proto.Field( + proto.ENUM, + number=12, + enum=Severity, + ) + canonical_name = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/folder.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/folder.py new file mode 100644 index 00000000..bca1c34f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/folder.py @@ -0,0 +1,50 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Folder', + }, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder = proto.Field( + proto.STRING, + number=1, + ) + resource_folder_display_name = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_config.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_config.py new file mode 100644 index 00000000..c4d0175f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_config.py @@ -0,0 +1,115 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'NotificationConfig', + }, +) + + +class NotificationConfig(proto.Message): + r"""Cloud Security Command Center (Cloud SCC) notification + configs. + A notification config is a Cloud SCC resource that contains the + configuration to send notifications for create/update events of + findings, assets and etc. + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/notificationConfigs/notify_public_bucket". + description (str): + The description of the notification config + (max of 1024 characters). + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v1.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + """ + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + pubsub_topic = proto.Field( + proto.STRING, + number=3, + ) + service_account = proto.Field( + proto.STRING, + number=4, + ) + streaming_config = proto.Field( + proto.MESSAGE, + number=5, + oneof='notify_config', + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_message.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_message.py new file mode 100644 index 00000000..b5b4b34e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_message.py @@ -0,0 +1,61 @@ +# -*- 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.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'NotificationMessage', + }, +) + + +class NotificationMessage(proto.Message): + r"""Cloud SCC's Notification + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v1.types.Finding): + If it's a Finding based notification config, + this field will be populated. + resource (google.cloud.securitycenter_v1.types.Resource): + The Cloud resource tied to this + notification's Finding. + """ + + notification_config_name = proto.Field( + proto.STRING, + number=1, + ) + finding = proto.Field( + proto.MESSAGE, + number=2, + oneof='event', + message=gcs_finding.Finding, + ) + resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/organization_settings.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/organization_settings.py new file mode 100644 index 00000000..f9e655a0 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/organization_settings.py @@ -0,0 +1,104 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + Attributes: + project_ids (Sequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + folder_ids (Sequence[str]): + The folder ids to use for filtering asset + discovery. It consists of only digits, e.g., + 756619654966. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + folder_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/resource.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/resource.py new file mode 100644 index 00000000..46aeddd8 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/resource.py @@ -0,0 +1,80 @@ +# -*- 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.securitycenter_v1.types import folder + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Resource', + }, +) + + +class Resource(proto.Message): + r"""Information related to the Google Cloud resource. + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + project = proto.Field( + proto.STRING, + number=2, + ) + project_display_name = proto.Field( + proto.STRING, + number=3, + ) + parent = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name = proto.Field( + proto.STRING, + number=5, + ) + folders = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..9abefa4d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py @@ -0,0 +1,57 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + Attributes: + state (google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run.""" + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/security_marks.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/security_marks.py new file mode 100644 index 00000000..34b696c4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/security_marks.py @@ -0,0 +1,76 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (Sequence[google.cloud.securitycenter_v1.types.SecurityMarks.MarksEntry]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "folders/{folder_id}/assets/{asset_id}/securityMarks" + "projects/{project_number}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + marks = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py new file mode 100644 index 00000000..6543ec9b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py @@ -0,0 +1,1611 @@ +# -*- 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.securitycenter_v1.types import asset as gcs_asset +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import folder +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'RunAssetDiscoveryRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + finding_id = proto.Field( + proto.STRING, + number=2, + ) + finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + config_id (str): + Required. + Unique identifier provided by the client within + the parent scope. It must be between 1 and 128 + characters, and contains alphanumeric + characters, underscores or hyphens only. + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + config_id = proto.Field( + proto.STRING, + number=2, + ) + notification_config = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (google.cloud.securitycenter_v1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + Attributes: + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + Attributes: + name (str): + Required. Name of the notification config to get. Its format + is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id], folders/[folder_id], or + projects/[project_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" property is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + group_by = proto.Field( + proto.STRING, + number=3, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token = proto.Field( + proto.STRING, + number=7, + ) + page_size = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + Attributes: + group_by_results (Sequence[google.cloud.securitycenter_v1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - workflow_state: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based + on a property existing: + ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state_change``). The string value + should follow SQL syntax: comma separated list of fields. + For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + group_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + page_token = proto.Field( + proto.STRING, + number=7, + ) + page_size = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + Attributes: + group_by_results (Sequence[google.cloud.securitycenter_v1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (Sequence[google.cloud.securitycenter_v1.types.GroupResult.PropertiesEntry]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count = proto.Field( + proto.INT64, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + Attributes: + parent (str): + Required. Name of the organization to list notification + configs. Its format is "organizations/[organization_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + Attributes: + notification_configs (Sequence[google.cloud.securitycenter_v1.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + Attributes: + sources (Sequence[google.cloud.securitycenter_v1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following are the allowed field and operator + combinations: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + + The following fields are supported: name update_time + resource_properties security_marks.marks + security_center_properties.resource_name + security_center_properties.resource_display_name + security_center_properties.resource_parent + security_center_properties.resource_parent_display_name + security_center_properties.resource_project + security_center_properties.resource_project_display_name + security_center_properties.resource_type + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetsResult's + "state_change" attribute is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the ListAssetsResult + fields to be listed in the response. + An empty field mask will list all fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + order_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + page_size = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + Attributes: + list_assets_results (Sequence[google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + Attributes: + asset (google.cloud.securitycenter_v1.types.Asset): + Asset matching the search request. + state_change (google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult.StateChange): + State change of the asset between the points + in time. + """ + class StateChange(proto.Enum): + r"""The change in state of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state change will be: + UNUSED + """ + UNUSED = 0 + ADDED = 1 + REMOVED = 2 + ACTIVE = 3 + + asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state_change = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.StateChange', + ) + + @property + def raw_page(self): + return self + + list_assets_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - severity: ``=``, ``:`` + + - workflow_state: ``=``, ``:`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based + on a property existing: + ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + + - resource: + + - resource.name: ``=``, ``:`` + - resource.parent_name: ``=``, ``:`` + - resource.parent_display_name: ``=``, ``:`` + - resource.project_name: ``=``, ``:`` + - resource.project_display_name: ``=``, ``:`` + - resource.type: ``=``, ``:`` + - resource.folders.resource_folder: ``=``, ``:`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time source_properties + security_marks.marks + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListFindingsResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added in any state during + the compare_duration period of time that precedes the + read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + order_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + page_size = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + Attributes: + list_findings_results (Sequence[google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding and its StateChange. + Attributes: + finding (google.cloud.securitycenter_v1.types.Finding): + Finding matching the search request. + state_change (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + class StateChange(proto.Enum): + r"""The change in state of the finding. + + When querying across two points in time this describes the change in + the finding between the two points: CHANGED, UNCHANGED, ADDED, or + REMOVED. Findings can not be deleted, so REMOVED implies that the + finding at timestamp does not match the filter specified, but it did + at timestamp - compare_duration. If there was no compare_duration + supplied in the request the state change will be: UNUSED + """ + UNUSED = 0 + CHANGED = 1 + UNCHANGED = 2 + ADDED = 3 + REMOVED = 4 + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project_name (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent_name (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + project_name = proto.Field( + proto.STRING, + number=2, + ) + project_display_name = proto.Field( + proto.STRING, + number=3, + ) + parent_name = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name = proto.Field( + proto.STRING, + number=5, + ) + folders = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + + finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + state_change = proto.Field( + proto.ENUM, + number=2, + enum='ListFindingsResponse.ListFindingsResult.StateChange', + ) + resource = proto.Field( + proto.MESSAGE, + number=3, + message='ListFindingsResponse.ListFindingsResult.Resource', + ) + + @property + def raw_page(self): + return self + + list_findings_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (google.cloud.securitycenter_v1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + state = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + Attributes: + finding (google.cloud.securitycenter_v1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + Attributes: + notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + Attributes: + organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + If empty all mutable fields will be updated. + """ + + organization_settings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + Attributes: + source (google.cloud.securitycenter_v1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + Attributes: + security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. If not set uses current server + time. Updates will be applied to the + SecurityMarks that are active immediately + preceding this time. + """ + + security_marks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/source.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/source.py new file mode 100644 index 00000000..f738daab --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/source.py @@ -0,0 +1,83 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, and other tools. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and outdated or + insecure libraries.". + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}" or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + canonical_name = proto.Field( + proto.STRING, + number=14, + ) + + +__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..07aa30ac --- /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']) +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/securitycenter_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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']) +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.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1/scripts/fixup_securitycenter_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_securitycenter_v1_keywords.py new file mode 100644 index 00000000..43acd75e --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_securitycenter_v1_keywords.py @@ -0,0 +1,198 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_notification_config': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_notification_config': ('name', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('source', 'update_mask', ), + } + + 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: not a.keyword.value 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=securitycenterCallTransformer(), +): + """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 securitycenter 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..0653f115 --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,54 @@ +# -*- 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-securitycenter', + 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.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', '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/securitycenter_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/securitycenter_v1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/securitycenter_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/securitycenter_v1/test_security_center.py b/owl-bot-staging/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py new file mode 100644 index 00000000..e397902d --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -0,0 +1,7619 @@ +# -*- 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 packaging.version + +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 future +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 operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.securitycenter_v1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.services.security_center import transports +from google.cloud.securitycenter_v1.services.security_center.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +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.longrunning import operations_pb2 +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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SecurityCenterClient, + SecurityCenterAsyncClient, +]) +def test_security_center_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 == 'securitycenter.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_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", [ + SecurityCenterClient, + SecurityCenterAsyncClient, +]) +def test_security_center_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 == 'securitycenter.googleapis.com:443' + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_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(SecurityCenterClient, '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(SecurityCenterClient, '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(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() + 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() + 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() + + # 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() + + # 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) + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_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) + + 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() + 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() + 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,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_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) + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + 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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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, + ) + + +def test_create_source(transport: str = 'grpc', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_create_source_from_dict(): + test_create_source(request_type=dict) + + +def test_create_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_source(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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_source(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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.Source(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] + assert args[0].parent == 'parent_value' + assert args[0].source == gcs_source.Source(name='name_value') + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.Source(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] + assert args[0].parent == 'parent_value' + assert args[0].source == gcs_source.Source(name='name_value') + + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_finding(transport: str = 'grpc', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_create_finding_from_dict(): + test_create_finding(request_type=dict) + + +def test_create_finding_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 = SecurityCenterClient( + 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_finding), + '__call__') as call: + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_finding(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_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_finding(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_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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] + assert args[0].parent == 'parent_value' + assert args[0].finding_id == 'finding_id_value' + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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] + assert args[0].parent == 'parent_value' + assert args[0].finding_id == 'finding_id_value' + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_create_notification_config(transport: str = 'grpc', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + streaming_config=gcs_notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), + ) + response = client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_create_notification_config_from_dict(): + test_create_notification_config(request_type=dict) + + +def test_create_notification_config_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 = SecurityCenterClient( + 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_notification_config), + '__call__') as call: + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_config(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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.create_notification_config(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_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(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] + assert args[0].parent == 'parent_value' + assert args[0].config_id == 'config_id_value' + assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(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] + assert args[0].parent == 'parent_value' + assert args[0].config_id == 'config_id_value' + assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') + + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +def test_delete_notification_config(transport: str = 'grpc', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_from_dict(): + test_delete_notification_config(request_type=dict) + + +def test_delete_notification_config_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 = SecurityCenterClient( + 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.delete_notification_config), + '__call__') as call: + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_notification_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value = None + client.delete_notification_config(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_delete_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_config(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_delete_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_notification_config( + 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] + assert args[0].name == 'name_value' + + +def test_delete_notification_config_flattened_error(): + client = SecurityCenterClient( + 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.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_notification_config( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_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 = SecurityCenterClient( + 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_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_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] + assert args[0].resource == 'resource_value' + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_notification_config(transport: str = 'grpc', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + streaming_config=notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), + ) + response = client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_get_notification_config_from_dict(): + test_get_notification_config(request_type=dict) + + +def test_get_notification_config_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 = SecurityCenterClient( + 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_notification_config), + '__call__') as call: + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_config(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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + await client.get_notification_config(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_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_config( + 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] + assert args[0].name == 'name_value' + + +def test_get_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_config( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_from_dict(): + test_get_organization_settings(request_type=dict) + + +def test_get_organization_settings_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 = SecurityCenterClient( + 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_organization_settings), + '__call__') as call: + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_settings(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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_settings(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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_settings( + 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] + assert args[0].name == 'name_value' + + +def test_get_organization_settings_flattened_error(): + client = SecurityCenterClient( + 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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_settings( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_source(transport: str = 'grpc', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_get_source_from_dict(): + test_get_source(request_type=dict) + + +def test_get_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_source(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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_source(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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_source( + 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] + assert args[0].name == 'name_value' + + +def test_get_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_source( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_group_assets(transport: str = 'grpc', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_assets_from_dict(): + test_group_assets(request_type=dict) + + +def test_group_assets_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 = SecurityCenterClient( + 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.group_assets), + '__call__') as call: + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(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_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(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_group_assets_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + +def test_group_assets_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.group_assets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_group_findings(transport: str = 'grpc', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_findings_from_dict(): + test_group_findings(request_type=dict) + + +def test_group_findings_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 = SecurityCenterClient( + 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.group_findings), + '__call__') as call: + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_findings(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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_findings(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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_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] + assert args[0].parent == 'parent_value' + assert args[0].group_by == 'group_by_value' + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + 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.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].group_by == 'group_by_value' + + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_findings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + +def test_group_findings_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_findings(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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_findings(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, securitycenter_service.GroupResult) + for i in responses) + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.group_findings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_assets(transport: str = 'grpc', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_from_dict(): + test_list_assets(request_type=dict) + + +def test_list_assets_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 = SecurityCenterClient( + 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_assets), + '__call__') as call: + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(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_assets_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + +def test_list_assets_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_assets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_findings(transport: str = 'grpc', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_findings_from_dict(): + test_list_findings(request_type=dict) + + +def test_list_findings_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 = SecurityCenterClient( + 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_findings), + '__call__') as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + + +def test_list_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = securitycenter_service.ListFindingsResponse() + client.list_findings(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_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse()) + await client.list_findings(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_findings_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_findings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in results) + +def test_list_findings_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_findings(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_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_findings(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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in responses) + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_findings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_notification_configs(transport: str = 'grpc', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_configs_from_dict(): + test_list_notification_configs(request_type=dict) + + +def test_list_notification_configs_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 = SecurityCenterClient( + 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_notification_configs), + '__call__') as call: + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_configs(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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + await client.list_notification_configs(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_notification_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_configs( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_notification_configs_flattened_error(): + client = SecurityCenterClient( + 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_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_configs( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_notification_configs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, notification_config.NotificationConfig) + for i in results) + +def test_list_notification_configs_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_configs(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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_configs(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, notification_config.NotificationConfig) + for i in responses) + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_notification_configs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_sources(transport: str = 'grpc', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_from_dict(): + test_list_sources(request_type=dict) + + +def test_list_sources_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 = SecurityCenterClient( + 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_sources), + '__call__') as call: + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_sources(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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_sources(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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sources( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_sources_flattened_error(): + client = SecurityCenterClient( + 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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sources( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_sources(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + +def test_list_sources_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sources(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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sources(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, source.Source) + for i in responses) + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_sources(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_run_asset_discovery(transport: str = 'grpc', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_from_dict(): + test_run_asset_discovery(request_type=dict) + + +def test_run_asset_discovery_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 = SecurityCenterClient( + 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.run_asset_discovery), + '__call__') as call: + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(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_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(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_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.run_asset_discovery( + 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] + assert args[0].parent == 'parent_value' + + +def test_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + 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.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.run_asset_discovery( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_set_finding_state(transport: str = 'grpc', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_set_finding_state_from_dict(): + test_set_finding_state(request_type=dict) + + +def test_set_finding_state_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 = SecurityCenterClient( + 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.set_finding_state), + '__call__') as call: + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_state(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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_state(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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].state == finding.Finding.State.ACTIVE + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + 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.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].state == finding.Finding.State.ACTIVE + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_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 = SecurityCenterClient( + 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.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_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] + assert args[0].resource == 'resource_value' + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_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 = SecurityCenterClient( + 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.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_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] + assert args[0].resource == 'resource_value' + assert args[0].permissions == ['permissions_value'] + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + assert args[0].permissions == ['permissions_value'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_update_finding(transport: str = 'grpc', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_update_finding_from_dict(): + test_update_finding(request_type=dict) + + +def test_update_finding_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 = SecurityCenterClient( + 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_finding), + '__call__') as call: + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'finding.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_finding(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', + 'finding.name=finding.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'finding.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_finding(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', + 'finding.name=finding.name/value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.Finding(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] + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +def test_update_finding_flattened_error(): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.Finding(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] + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +@pytest.mark.asyncio +async def test_update_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_update_notification_config(transport: str = 'grpc', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + streaming_config=gcs_notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), + ) + response = client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_update_notification_config_from_dict(): + test_update_notification_config(request_type=dict) + + +def test_update_notification_config_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 = SecurityCenterClient( + 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_notification_config), + '__call__') as call: + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'notification_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_config(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', + 'notification_config.name=notification_config.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'notification_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.update_notification_config(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', + 'notification_config.name=notification_config.name/value', + ) in kw['metadata'] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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] + assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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] + assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_from_dict(): + test_update_organization_settings(request_type=dict) + + +def test_update_organization_settings_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 = SecurityCenterClient( + 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_organization_settings), + '__call__') as call: + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'organization_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_settings(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', + 'organization_settings.name=organization_settings.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'organization_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_settings(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', + 'organization_settings.name=organization_settings.name/value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(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] + assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + 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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(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] + assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') + + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_source(transport: str = 'grpc', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_source_from_dict(): + test_update_source(request_type=dict) + + +def test_update_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'source.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_source(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', + 'source.name=source.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'source.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_source(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', + 'source.name=source.name/value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.Source(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] + assert args[0].source == gcs_source.Source(name='name_value') + + +def test_update_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.Source(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] + assert args[0].source == gcs_source.Source(name='name_value') + + +@pytest.mark.asyncio +async def test_update_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +def test_update_security_marks(transport: str = 'grpc', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_security_marks_from_dict(): + test_update_security_marks(request_type=dict) + + +def test_update_security_marks_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 = SecurityCenterClient( + 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_security_marks), + '__call__') as call: + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'security_marks.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(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', + 'security_marks.name=security_marks.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'security_marks.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(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', + 'security_marks.name=security_marks.name/value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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] + assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') + + +def test_update_security_marks_flattened_error(): + client = SecurityCenterClient( + 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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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] + assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, +]) +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_source', + 'create_finding', + 'create_notification_config', + 'delete_notification_config', + 'get_iam_policy', + 'get_notification_config', + 'get_organization_settings', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_findings', + 'list_notification_configs', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_iam_policy', + 'test_iam_permissions', + 'update_finding', + 'update_notification_config', + 'update_organization_settings', + 'update_source', + 'update_security_marks', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_security_center_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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_center_base_transport_with_credentials_file_old_google_auth(): + # 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_security_center_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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_security_center_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) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_center_auth_adc_old_google_auth(): + # 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) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_security_center_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',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_security_center_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_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( + "securitycenter.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_host_no_port(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + ) + assert client.transport._host == 'securitycenter.googleapis.com:443' + + +def test_security_center_host_with_port(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + ) + assert client.transport._host == 'securitycenter.googleapis.com:8000' + +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_notification_config_path(): + organization = "scallop" + notification_config = "abalone" + expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + actual = SecurityCenterClient.notification_config_path(organization, notification_config) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "squid", + "notification_config": "clam", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "whelk" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "octopus", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "oyster" + asset = "nudibranch" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "cuttlefish", + "asset": "mussel", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_source_path(): + organization = "winkle" + source = "nautilus" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "scallop", + "source": "abalone", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_topic_path(): + project = "squid" + topic = "clam" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "whelk", + "topic": "octopus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc new file mode 100644 index 00000000..3655af7f --- /dev/null +++ b/owl-bot-staging/v1beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__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/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in new file mode 100644 index 00000000..328e3b89 --- /dev/null +++ b/owl-bot-staging/v1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst new file mode 100644 index 00000000..f8c63f4c --- /dev/null +++ b/owl-bot-staging/v1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py new file mode 100644 index 00000000..f4837604 --- /dev/null +++ b/owl-bot-staging/v1beta1/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-securitycenter documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-securitycenter" +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-securitycenter-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-securitycenter.tex", + u"google-cloud-securitycenter Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-securitycenter", + u"Google Cloud Securitycenter Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst new file mode 100644 index 00000000..88360626 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1beta1/services + securitycenter_v1beta1/types diff --git a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/security_center.rst b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/security_center.rst new file mode 100644 index 00000000..304849ec --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/services.rst new file mode 100644 index 00000000..a09a4b86 --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1beta1 API +==================================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/types.rst new file mode 100644 index 00000000..44bb4fec --- /dev/null +++ b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Securitycenter v1beta1 API +================================================= + +.. automodule:: google.cloud.securitycenter_v1beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter/__init__.py new file mode 100644 index 00000000..c85455c8 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter/__init__.py @@ -0,0 +1,77 @@ +# -*- 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.securitycenter_v1beta1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1beta1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1beta1.types.asset import Asset +from google.cloud.securitycenter_v1beta1.types.finding import Finding +from google.cloud.securitycenter_v1beta1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1beta1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1beta1.types.source import Source + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Asset', + 'Finding', + 'OrganizationSettings', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/v1beta1/google/cloud/securitycenter/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py new file mode 100644 index 00000000..2787c7bd --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py @@ -0,0 +1,78 @@ +# -*- 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.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.asset import Asset +from .types.finding import Finding +from .types.organization_settings import OrganizationSettings +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source + +__all__ = ( + 'SecurityCenterAsyncClient', +'Asset', +'CreateFindingRequest', +'CreateSourceRequest', +'Finding', +'GetOrganizationSettingsRequest', +'GetSourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'OrganizationSettings', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityCenterClient', +'SecurityMarks', +'SetFindingStateRequest', +'Source', +'UpdateFindingRequest', +'UpdateOrganizationSettingsRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json new file mode 100644 index 00000000..56b17ccf --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json @@ -0,0 +1,203 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1beta1", + "protoPackage": "google.cloud.securitycenter.v1beta1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/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/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py new file mode 100644 index 00000000..fce6b0c5 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py new file mode 100644 index 00000000..b00ba609 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -0,0 +1,1886 @@ +# -*- 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1 Beta APIs for Security Center service.""" + + _client: SecurityCenterClient + + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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, ~.SecurityCenterTransport]): 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_source(self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``source`` 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.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, source]) + 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 = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # 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_source, + 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_finding(self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` 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.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + 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 = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # 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_finding, + 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 get_iam_policy(self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # 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_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(( + ("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_organization_settings(self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + 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.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings, + 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_source(self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + + 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.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.GetSourceRequest(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_source, + 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 group_assets(self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = securitycenter_service.GroupAssetsRequest(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.group_assets, + 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=480.0, + ), + default_timeout=480.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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state``). The string value + should follow SQL syntax: comma separated list of + fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + This corresponds to the ``group_by`` 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.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + 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 = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_findings, + 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=480.0, + ), + default_timeout=480.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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: securitycenter_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.ListAssetsRequest`): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = securitycenter_service.ListAssetsRequest(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.list_assets, + 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=480.0, + ), + default_timeout=480.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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: securitycenter_service.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.ListFindingsRequest`): + The request object. Request message for listing + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = securitycenter_service.ListFindingsRequest(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.list_findings, + 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=480.0, + ), + default_timeout=480.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.ListFindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + + 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.ListSourcesRequest(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_sources, + 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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp_pb2.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1beta1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` 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.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + 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 = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # 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_finding_state, + 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 set_iam_policy(self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # 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=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(( + ("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, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # 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_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(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_finding(self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` 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.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + 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 = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # 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_finding, + 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(( + ("finding.name", request.finding.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_organization_settings(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1beta1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` 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.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + 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 = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # 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_organization_settings, + 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(( + ("organization_settings.name", request.organization_settings.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_source(self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``source`` 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.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([source]) + 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 = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # 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_source, + 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(( + ("source.name", request.source.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_security_marks(self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1beta1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` 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.securitycenter_v1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + 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 = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # 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_security_marks, + default_timeout=480.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(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Send the request. + response = await 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-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py new file mode 100644 index 00000000..ac50243b --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -0,0 +1,2052 @@ +# -*- 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1 Beta APIs for Security Center service.""" + + @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 = "securitycenter.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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SecurityCenterTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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, SecurityCenterTransport]): 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # 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, SecurityCenterTransport): + # transport is a SecurityCenterTransport instance. + if credentials or client_options.credentials_file: + 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: + 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=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def create_source(self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (google.cloud.securitycenter_v1beta1.types.CreateSourceRequest): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``source`` 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.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, source]) + 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 securitycenter_service.CreateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_source] + + # 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_finding(self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (google.cloud.securitycenter_v1beta1.types.CreateFindingRequest): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` 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.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + 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 securitycenter_service.CreateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # 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 get_iam_policy(self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): + The request object. Request message for `GetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_organization_settings(self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + 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.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings] + + # 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_source(self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (google.cloud.securitycenter_v1beta1.types.GetSourceRequest): + The request object. Request message for getting a + source. + name (str): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + + 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.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(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_source] + + # 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 group_assets(self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # 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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state``). The string value + should follow SQL syntax: comma separated list of + fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + This corresponds to the ``group_by`` 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.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + 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 securitycenter_service.GroupFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_findings] + + # 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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: securitycenter_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + Args: + request (google.cloud.securitycenter_v1beta1.types.ListAssetsRequest): + The request object. Request message for listing assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # 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.ListAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: securitycenter_service.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (google.cloud.securitycenter_v1beta1.types.ListFindingsRequest): + The request object. Request message for listing + findings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_findings] + + # 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.ListFindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + Args: + request (google.cloud.securitycenter_v1beta1.types.ListSourcesRequest): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + + 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListSourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(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_sources] + + # 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.ListSourcesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.RunAssetDiscoveryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp_pb2.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + name (str): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` 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.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + 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 securitycenter_service.SetFindingStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_state] + + # 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 set_iam_policy(self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): + The request object. Request message for `SetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # 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, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): + The request object. Request message for + `TestIamPermissions` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (Sequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_finding(self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` 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.securitycenter_v1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding]) + 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 securitycenter_service.UpdateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_organization_settings(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` 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.securitycenter_v1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + 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 securitycenter_service.UpdateOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_settings.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_source(self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``source`` 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.securitycenter_v1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([source]) + 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 securitycenter_service.UpdateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.source.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_security_marks(self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` 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.securitycenter_v1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks]) + 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 securitycenter_service.UpdateSecurityMarksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # 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-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py new file mode 100644 index 00000000..eef89b03 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py @@ -0,0 +1,630 @@ +# -*- 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` + 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[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: + 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) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` + 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: + 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) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` + 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[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: + 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) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` + 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: + 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) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` + 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[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: + 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) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` + 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: + 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) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` + 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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + 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.securitycenter_v1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListFindingsResponse): + 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 = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: + 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) -> Iterable[finding.Finding]: + for page in self.pages: + yield from page.findings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` + 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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + 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.securitycenter_v1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListFindingsResponse): + 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 = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: + 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) -> AsyncIterable[finding.Finding]: + async def async_generator(): + async for page in self.pages: + for response in page.findings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` + 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[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: + 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) -> Iterable[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` + 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: + 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) -> AsyncIterable[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + 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/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..8bdaf713 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py new file mode 100644 index 00000000..0166afdc --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py @@ -0,0 +1,485 @@ +# -*- 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 packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-securitycenter', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.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 = self._get_scopes_kwargs(self._host, 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 is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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_source: gapic_v1.method.wrap_method( + self.get_source, + 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.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + 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 get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..10b4ae08 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py @@ -0,0 +1,742 @@ +# -*- 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 # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # 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 + +import grpc # type: ignore + +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1 Beta APIs for Security Center service. + + 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 = 'securitycenter.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 applicatin 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 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 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'securitycenter.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..5d7fd656 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,746 @@ +# -*- 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1 Beta APIs for Security Center service. + + 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 = 'securitycenter.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 = 'securitycenter.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 applicatin 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 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 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py new file mode 100644 index 00000000..abeb0314 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py @@ -0,0 +1,86 @@ +# -*- 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 .asset import ( + Asset, +) +from .finding import ( + Finding, +) +from .organization_settings import ( + OrganizationSettings, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_marks import ( + SecurityMarks, +) +from .securitycenter_service import ( + CreateFindingRequest, + CreateSourceRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListSourcesRequest, + ListSourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + UpdateFindingRequest, + UpdateOrganizationSettingsRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .source import ( + Source, +) + +__all__ = ( + 'Asset', + 'Finding', + 'OrganizationSettings', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py new file mode 100644 index 00000000..692b5856 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py @@ -0,0 +1,151 @@ +# -*- 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.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1beta1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (Sequence[google.cloud.securitycenter_v1beta1.types.Asset.ResourcePropertiesEntry]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated, + added, or deleted in Security Command Center. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + Immutable. The full resource name of the Google Cloud + resource this asset represents. This field is immutable + after create time. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (Sequence[str]): + Owners of the Google Cloud resource. + """ + + resource_name = proto.Field( + proto.STRING, + number=1, + ) + resource_type = proto.Field( + proto.STRING, + number=2, + ) + resource_parent = proto.Field( + proto.STRING, + number=3, + ) + resource_project = proto.Field( + proto.STRING, + number=4, + ) + resource_owners = proto.RepeatedField( + proto.STRING, + number=5, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py new file mode 100644 index 00000000..77e085cd --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py @@ -0,0 +1,148 @@ +# -*- 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.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + A finding is a record of assessment data (security, risk, health + or privacy) ingested into Security Command Center for + presentation, notification, analysis, policy testing, and + enforcement. For example, an XSS vulnerability in an App Engine + application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + Immutable. The relative resource name of the source the + finding belongs to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (Sequence[google.cloud.securitycenter_v1beta1.types.Finding.SourcePropertiesEntry]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the event took place, or + when an update to the finding occurred. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. If the finding + were to be resolved afterward, this time would + reflect when the finding was resolved. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + """ + class State(proto.Enum): + r"""The state of the finding.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + name = proto.Field( + proto.STRING, + number=1, + ) + parent = proto.Field( + proto.STRING, + number=2, + ) + resource_name = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category = proto.Field( + proto.STRING, + number=5, + ) + external_uri = proto.Field( + proto.STRING, + number=6, + ) + source_properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py new file mode 100644 index 00000000..fe9c8e1d --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py @@ -0,0 +1,96 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + Attributes: + project_ids (Sequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..6b4a7a57 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py @@ -0,0 +1,57 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + Attributes: + state (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run.""" + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py new file mode 100644 index 00000000..7d0b12c2 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py @@ -0,0 +1,64 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (Sequence[google.cloud.securitycenter_v1beta1.types.SecurityMarks.MarksEntry]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + marks = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py new file mode 100644 index 00000000..020504b4 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py @@ -0,0 +1,1016 @@ +# -*- 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.securitycenter_v1beta1.types import asset as gcs_asset +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'CreateFindingRequest', + 'CreateSourceRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'RunAssetDiscoveryRequest', + 'UpdateFindingRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + finding_id = proto.Field( + proto.STRING, + number=2, + ) + finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``resource_properties.size = 100`` is a valid + filter string. + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_type + - security_center_properties.resource_parent + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the Asset's "state" property + is updated to indicate whether the asset was added, removed, + or remained present during the compare_duration period of + time that precedes the read_time. This is the time between + (read_time - compare_duration) and read_time. + + The state value is derived based on the presence of the + asset at the two points in time. Intermediate state changes + between the two times don't affect the result. For example, + the results aren't affected if the asset is removed and + re-created again. + + Possible "state" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present before + compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + This field is ignored if ``state`` is not a field in + ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + group_by = proto.Field( + proto.STRING, + number=3, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token = proto.Field( + proto.STRING, + number=7, + ) + page_size = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + Attributes: + group_by_results (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To + groupBy across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``source_properties.size = 100`` is a valid + filter string. + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state``). The string value should + follow SQL syntax: comma separated list of fields. For + example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + group_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + page_token = proto.Field( + proto.STRING, + number=5, + ) + page_size = proto.Field( + proto.INT32, + number=6, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + Attributes: + group_by_results (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult.PropertiesEntry]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count = proto.Field( + proto.INT64, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + Attributes: + sources (Sequence[google.cloud.securitycenter_v1beta1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``resource_properties.size = 100`` is a valid + filter string. + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetResult's "state" + attribute is updated to indicate whether the asset was + added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state value is derived based on the presence of the + asset at the two points in time. Intermediate state changes + between the two times don't affect the result. For example, + the results aren't affected if the asset is removed and + re-created again. + + Possible "state" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present before + compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state is "UNUSED", which indicates that the asset is present + at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A field mask to specify the + ListAssetsResult fields to be listed in the + response. An empty field mask will list all + fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + order_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + page_size = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + Attributes: + list_assets_results (Sequence[google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + Attributes: + asset (google.cloud.securitycenter_v1beta1.types.Asset): + Asset matching the search request. + state (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult.State): + State of the asset. + """ + class State(proto.Enum): + r"""State of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state should be: UNUSED + """ + STATE_UNSPECIFIED = 0 + UNUSED = 1 + ADDED = 2 + REMOVED = 3 + ACTIVE = 4 + + asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.State', + ) + + @property + def raw_page(self): + return self + + list_assets_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id]". To + list across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``source_properties.size = 100`` is a valid + filter string. + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A field mask to specify the Finding + fields to be listed in the response. An empty + field mask will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + order_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + field_mask = proto.Field( + proto.MESSAGE, + number=5, + message=field_mask_pb2.FieldMask, + ) + page_token = proto.Field( + proto.STRING, + number=6, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + Attributes: + findings (Sequence[google.cloud.securitycenter_v1beta1.types.Finding]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + @property + def raw_page(self): + return self + + findings = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (google.cloud.securitycenter_v1beta1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + state = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + Attributes: + finding (google.cloud.securitycenter_v1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + finding resource. This field should not be + specified when creating a finding. + """ + + finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + Attributes: + organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + """ + + organization_settings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + Attributes: + source (google.cloud.securitycenter_v1beta1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + """ + + source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + Attributes: + security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + security marks resource. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. + """ + + security_marks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py new file mode 100644 index 00000000..140027f0 --- /dev/null +++ b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py @@ -0,0 +1,72 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1beta1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, etc. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and + outdated/insecure libraries.". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py new file mode 100644 index 00000000..713b8907 --- /dev/null +++ b/owl-bot-staging/v1beta1/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']) +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/securitycenter_v1beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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']) +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.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py new file mode 100644 index 00000000..c85a7b83 --- /dev/null +++ b/owl-bot-staging/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py @@ -0,0 +1,193 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_source': ('parent', 'source', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('source', 'update_mask', ), + } + + 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: not a.keyword.value 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=securitycenterCallTransformer(), +): + """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 securitycenter 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py new file mode 100644 index 00000000..0653f115 --- /dev/null +++ b/owl-bot-staging/v1beta1/setup.py @@ -0,0 +1,54 @@ +# -*- 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-securitycenter', + 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.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', '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/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__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/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py new file mode 100644 index 00000000..aa8d8dbe --- /dev/null +++ b/owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py @@ -0,0 +1,6133 @@ +# -*- 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 packaging.version + +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 future +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 operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.securitycenter_v1beta1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1beta1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.services.security_center import transports +from google.cloud.securitycenter_v1beta1.services.security_center.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +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.longrunning import operations_pb2 +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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SecurityCenterClient, + SecurityCenterAsyncClient, +]) +def test_security_center_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 == 'securitycenter.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_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", [ + SecurityCenterClient, + SecurityCenterAsyncClient, +]) +def test_security_center_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 == 'securitycenter.googleapis.com:443' + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_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(SecurityCenterClient, '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(SecurityCenterClient, '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(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() + 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() + 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() + + # 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() + + # 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) + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_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) + + 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() + 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() + 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,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_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) + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + 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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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, + ) + + +def test_create_source(transport: str = 'grpc', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_create_source_from_dict(): + test_create_source(request_type=dict) + + +def test_create_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_source(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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_source(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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.Source(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] + assert args[0].parent == 'parent_value' + assert args[0].source == gcs_source.Source(name='name_value') + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.Source(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] + assert args[0].parent == 'parent_value' + assert args[0].source == gcs_source.Source(name='name_value') + + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_finding(transport: str = 'grpc', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_create_finding_from_dict(): + test_create_finding(request_type=dict) + + +def test_create_finding_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 = SecurityCenterClient( + 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_finding), + '__call__') as call: + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_finding(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_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_finding(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_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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] + assert args[0].parent == 'parent_value' + assert args[0].finding_id == 'finding_id_value' + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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] + assert args[0].parent == 'parent_value' + assert args[0].finding_id == 'finding_id_value' + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_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 = SecurityCenterClient( + 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_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_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] + assert args[0].resource == 'resource_value' + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_from_dict(): + test_get_organization_settings(request_type=dict) + + +def test_get_organization_settings_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 = SecurityCenterClient( + 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_organization_settings), + '__call__') as call: + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_settings(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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_settings(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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_settings( + 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] + assert args[0].name == 'name_value' + + +def test_get_organization_settings_flattened_error(): + client = SecurityCenterClient( + 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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_settings( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_source(transport: str = 'grpc', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_get_source_from_dict(): + test_get_source(request_type=dict) + + +def test_get_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_source(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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_source(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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_source( + 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] + assert args[0].name == 'name_value' + + +def test_get_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_source( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_group_assets(transport: str = 'grpc', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_group_assets_from_dict(): + test_group_assets(request_type=dict) + + +def test_group_assets_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 = SecurityCenterClient( + 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.group_assets), + '__call__') as call: + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(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_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(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_group_assets_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + +def test_group_assets_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.group_assets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_group_findings(transport: str = 'grpc', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_group_findings_from_dict(): + test_group_findings(request_type=dict) + + +def test_group_findings_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 = SecurityCenterClient( + 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.group_findings), + '__call__') as call: + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_findings(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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_findings(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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_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] + assert args[0].parent == 'parent_value' + assert args[0].group_by == 'group_by_value' + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + 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.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].group_by == 'group_by_value' + + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_findings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + +def test_group_findings_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_findings(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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_findings(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, securitycenter_service.GroupResult) + for i in responses) + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.group_findings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_assets(transport: str = 'grpc', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_from_dict(): + test_list_assets(request_type=dict) + + +def test_list_assets_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 = SecurityCenterClient( + 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_assets), + '__call__') as call: + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(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_assets_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + +def test_list_assets_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_assets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_findings(transport: str = 'grpc', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_findings_from_dict(): + test_list_findings(request_type=dict) + + +def test_list_findings_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 = SecurityCenterClient( + 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_findings), + '__call__') as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + + +def test_list_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = securitycenter_service.ListFindingsResponse() + client.list_findings(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_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse()) + await client.list_findings(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_findings_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_findings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, finding.Finding) + for i in results) + +def test_list_findings_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_findings(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_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_findings(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, finding.Finding) + for i in responses) + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + findings=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_findings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_sources(transport: str = 'grpc', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_from_dict(): + test_list_sources(request_type=dict) + + +def test_list_sources_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 = SecurityCenterClient( + 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_sources), + '__call__') as call: + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_sources(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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_sources(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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sources( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_sources_flattened_error(): + client = SecurityCenterClient( + 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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sources( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_sources(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + +def test_list_sources_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sources(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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sources(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, source.Source) + for i in responses) + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_sources(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_run_asset_discovery(transport: str = 'grpc', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_from_dict(): + test_run_asset_discovery(request_type=dict) + + +def test_run_asset_discovery_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 = SecurityCenterClient( + 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.run_asset_discovery), + '__call__') as call: + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(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_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(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_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.run_asset_discovery( + 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] + assert args[0].parent == 'parent_value' + + +def test_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + 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.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.run_asset_discovery( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_set_finding_state(transport: str = 'grpc', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_set_finding_state_from_dict(): + test_set_finding_state(request_type=dict) + + +def test_set_finding_state_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 = SecurityCenterClient( + 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.set_finding_state), + '__call__') as call: + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_state(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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_state(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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].state == finding.Finding.State.ACTIVE + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + 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.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].state == finding.Finding.State.ACTIVE + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_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 = SecurityCenterClient( + 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.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_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] + assert args[0].resource == 'resource_value' + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_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 = SecurityCenterClient( + 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.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_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] + assert args[0].resource == 'resource_value' + assert args[0].permissions == ['permissions_value'] + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + assert args[0].permissions == ['permissions_value'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_update_finding(transport: str = 'grpc', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +def test_update_finding_from_dict(): + test_update_finding(request_type=dict) + + +def test_update_finding_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 = SecurityCenterClient( + 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_finding), + '__call__') as call: + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'finding.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_finding(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', + 'finding.name=finding.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'finding.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_finding(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', + 'finding.name=finding.name/value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.Finding(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] + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +def test_update_finding_flattened_error(): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.Finding(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] + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +@pytest.mark.asyncio +async def test_update_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_update_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_from_dict(): + test_update_organization_settings(request_type=dict) + + +def test_update_organization_settings_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 = SecurityCenterClient( + 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_organization_settings), + '__call__') as call: + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'organization_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_settings(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', + 'organization_settings.name=organization_settings.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'organization_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_settings(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', + 'organization_settings.name=organization_settings.name/value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(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] + assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + 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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(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] + assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') + + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_source(transport: str = 'grpc', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +def test_update_source_from_dict(): + test_update_source(request_type=dict) + + +def test_update_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'source.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_source(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', + 'source.name=source.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'source.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_source(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', + 'source.name=source.name/value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.Source(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] + assert args[0].source == gcs_source.Source(name='name_value') + + +def test_update_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.Source(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] + assert args[0].source == gcs_source.Source(name='name_value') + + +@pytest.mark.asyncio +async def test_update_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + ) + + +def test_update_security_marks(transport: str = 'grpc', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + + +def test_update_security_marks_from_dict(): + test_update_security_marks(request_type=dict) + + +def test_update_security_marks_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 = SecurityCenterClient( + 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_security_marks), + '__call__') as call: + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'security_marks.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(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', + 'security_marks.name=security_marks.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'security_marks.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(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', + 'security_marks.name=security_marks.name/value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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] + assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') + + +def test_update_security_marks_flattened_error(): + client = SecurityCenterClient( + 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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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] + assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, +]) +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_source', + 'create_finding', + 'get_iam_policy', + 'get_organization_settings', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_findings', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_iam_policy', + 'test_iam_permissions', + 'update_finding', + 'update_organization_settings', + 'update_source', + 'update_security_marks', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_security_center_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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_center_base_transport_with_credentials_file_old_google_auth(): + # 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_security_center_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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_security_center_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) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_center_auth_adc_old_google_auth(): + # 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) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_security_center_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',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_security_center_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_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( + "securitycenter.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_host_no_port(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + ) + assert client.transport._host == 'securitycenter.googleapis.com:443' + + +def test_security_center_host_with_port(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + ) + assert client.transport._host == 'securitycenter.googleapis.com:8000' + +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "scallop" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "abalone", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_source_path(): + organization = "oyster" + source = "nudibranch" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "cuttlefish", + "source": "mussel", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1p1beta1/.coveragerc b/owl-bot-staging/v1p1beta1/.coveragerc new file mode 100644 index 00000000..3655af7f --- /dev/null +++ b/owl-bot-staging/v1p1beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/securitycenter/__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/v1p1beta1/MANIFEST.in b/owl-bot-staging/v1p1beta1/MANIFEST.in new file mode 100644 index 00000000..57b563bd --- /dev/null +++ b/owl-bot-staging/v1p1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/securitycenter *.py +recursive-include google/cloud/securitycenter_v1p1beta1 *.py diff --git a/owl-bot-staging/v1p1beta1/README.rst b/owl-bot-staging/v1p1beta1/README.rst new file mode 100644 index 00000000..f8c63f4c --- /dev/null +++ b/owl-bot-staging/v1p1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Securitycenter 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 Securitycenter 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/v1p1beta1/docs/conf.py b/owl-bot-staging/v1p1beta1/docs/conf.py new file mode 100644 index 00000000..f4837604 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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-securitycenter documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.6.3" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-securitycenter" +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-securitycenter-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "google-cloud-securitycenter.tex", + u"google-cloud-securitycenter Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "google-cloud-securitycenter", + u"Google Cloud Securitycenter Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "google-cloud-securitycenter", + u"google-cloud-securitycenter Documentation", + author, + "google-cloud-securitycenter", + "GAPIC library for Google Cloud Securitycenter 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/v1p1beta1/docs/index.rst b/owl-bot-staging/v1p1beta1/docs/index.rst new file mode 100644 index 00000000..45263147 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + securitycenter_v1p1beta1/services + securitycenter_v1p1beta1/types diff --git a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst new file mode 100644 index 00000000..adab7f4a --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst @@ -0,0 +1,10 @@ +SecurityCenter +-------------------------------- + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center + :members: + :inherited-members: + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/services.rst b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/services.rst new file mode 100644 index 00000000..7f537e85 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1p1beta1 API +====================================================== +.. toctree:: + :maxdepth: 2 + + security_center diff --git a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/types.rst b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/types.rst new file mode 100644 index 00000000..1facc905 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Securitycenter v1p1beta1 API +=================================================== + +.. automodule:: google.cloud.securitycenter_v1p1beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/__init__.py new file mode 100644 index 00000000..4f397497 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/__init__.py @@ -0,0 +1,97 @@ +# -*- 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.securitycenter_v1p1beta1.services.security_center.client import SecurityCenterClient +from google.cloud.securitycenter_v1p1beta1.services.security_center.async_client import SecurityCenterAsyncClient + +from google.cloud.securitycenter_v1p1beta1.types.asset import Asset +from google.cloud.securitycenter_v1p1beta1.types.finding import Finding +from google.cloud.securitycenter_v1p1beta1.types.folder import Folder +from google.cloud.securitycenter_v1p1beta1.types.notification_config import NotificationConfig +from google.cloud.securitycenter_v1p1beta1.types.notification_message import NotificationMessage +from google.cloud.securitycenter_v1p1beta1.types.organization_settings import OrganizationSettings +from google.cloud.securitycenter_v1p1beta1.types.resource import Resource +from google.cloud.securitycenter_v1p1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse +from google.cloud.securitycenter_v1p1beta1.types.security_marks import SecurityMarks +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateFindingRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import DeleteNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetOrganizationSettingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupResult +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesResponse +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import RunAssetDiscoveryRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import SetFindingStateRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateFindingRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateNotificationConfigRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSecurityMarksRequest +from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSourceRequest +from google.cloud.securitycenter_v1p1beta1.types.source import Source + +__all__ = ('SecurityCenterClient', + 'SecurityCenterAsyncClient', + 'Asset', + 'Finding', + 'Folder', + 'NotificationConfig', + 'NotificationMessage', + 'OrganizationSettings', + 'Resource', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py new file mode 100644 index 00000000..ca8f63fd --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py @@ -0,0 +1,98 @@ +# -*- 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.security_center import SecurityCenterClient +from .services.security_center import SecurityCenterAsyncClient + +from .types.asset import Asset +from .types.finding import Finding +from .types.folder import Folder +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.organization_settings import OrganizationSettings +from .types.resource import Resource +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source + +__all__ = ( + 'SecurityCenterAsyncClient', +'Asset', +'CreateFindingRequest', +'CreateNotificationConfigRequest', +'CreateSourceRequest', +'DeleteNotificationConfigRequest', +'Finding', +'Folder', +'GetNotificationConfigRequest', +'GetOrganizationSettingsRequest', +'GetSourceRequest', +'GroupAssetsRequest', +'GroupAssetsResponse', +'GroupFindingsRequest', +'GroupFindingsResponse', +'GroupResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFindingsRequest', +'ListFindingsResponse', +'ListNotificationConfigsRequest', +'ListNotificationConfigsResponse', +'ListSourcesRequest', +'ListSourcesResponse', +'NotificationConfig', +'NotificationMessage', +'OrganizationSettings', +'Resource', +'RunAssetDiscoveryRequest', +'RunAssetDiscoveryResponse', +'SecurityCenterClient', +'SecurityMarks', +'SetFindingStateRequest', +'Source', +'UpdateFindingRequest', +'UpdateNotificationConfigRequest', +'UpdateOrganizationSettingsRequest', +'UpdateSecurityMarksRequest', +'UpdateSourceRequest', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json new file mode 100644 index 00000000..734457b5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json @@ -0,0 +1,253 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.securitycenter_v1p1beta1", + "protoPackage": "google.cloud.securitycenter.v1p1beta1", + "schema": "1.0", + "services": { + "SecurityCenter": { + "clients": { + "grpc": { + "libraryClient": "SecurityCenterClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecurityCenterAsyncClient", + "rpcs": { + "CreateFinding": { + "methods": [ + "create_finding" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "create_notification_config" + ] + }, + "CreateSource": { + "methods": [ + "create_source" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "delete_notification_config" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetNotificationConfig": { + "methods": [ + "get_notification_config" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "get_organization_settings" + ] + }, + "GetSource": { + "methods": [ + "get_source" + ] + }, + "GroupAssets": { + "methods": [ + "group_assets" + ] + }, + "GroupFindings": { + "methods": [ + "group_findings" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "list_notification_configs" + ] + }, + "ListSources": { + "methods": [ + "list_sources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "run_asset_discovery" + ] + }, + "SetFindingState": { + "methods": [ + "set_finding_state" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateFinding": { + "methods": [ + "update_finding" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "update_notification_config" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "update_organization_settings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "update_security_marks" + ] + }, + "UpdateSource": { + "methods": [ + "update_source" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py new file mode 100644 index 00000000..fce6b0c5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + 'SecurityCenterClient', + 'SecurityCenterAsyncClient', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py new file mode 100644 index 00000000..b6f01b07 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -0,0 +1,2432 @@ +# -*- 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1p1Beta1 APIs for Security Center service.""" + + _client: SecurityCenterClient + + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + + asset_path = staticmethod(SecurityCenterClient.asset_path) + parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) + notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) + parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) + organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) + parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) + parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) + topic_path = staticmethod(SecurityCenterClient.topic_path) + parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) + common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) + parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) + common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) + parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) + common_project_path = staticmethod(SecurityCenterClient.common_project_path) + parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) + common_location_path = staticmethod(SecurityCenterClient.common_location_path) + parse_common_location_path = staticmethod(SecurityCenterClient.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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: + SecurityCenterAsyncClient: The constructed client. + """ + return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) + + def __init__(self, *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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, ~.SecurityCenterTransport]): 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 = SecurityCenterClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_source(self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``source`` 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.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, source]) + 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 = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # 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_source, + 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_finding(self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + 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 = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # 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_finding, + 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_notification_config(self, + request: securitycenter_service.CreateNotificationConfigRequest = None, + *, + parent: str = None, + config_id: str = None, + notification_config: gcs_notification_config.NotificationConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest`): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be between 1 and 128 characters, + and contains alphanumeric characters, + underscores or hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` 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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_config]) + 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 = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # 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_notification_config, + 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 delete_notification_config(self, + request: securitycenter_service.DeleteNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a notification config. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest`): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.DeleteNotificationConfigRequest(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.delete_notification_config, + 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_iam_policy(self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) + + # 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_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(( + ("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_notification_config(self, + request: securitycenter_service.GetNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest`): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + + 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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.GetNotificationConfigRequest(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_notification_config, + 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_organization_settings(self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + 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.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings, + 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_source(self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + + 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.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.GetSourceRequest(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_source, + 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 group_assets(self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = securitycenter_service.GroupAssetsRequest(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.group_assets, + 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=480.0, + ), + default_timeout=480.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.GroupAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings(self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` 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.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + 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 = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_findings, + 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=480.0, + ), + default_timeout=480.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.GroupFindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: securitycenter_service.ListAssetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest`): + The request object. Request message for listing assets. + parent (:class:`str`): + Required. Name of the organization assets should belong + to. Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.ListAssetsRequest(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_assets, + 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=480.0, + ), + default_timeout=480.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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings(self, + request: securitycenter_service.ListFindingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest`): + The request object. Request message for listing + findings. + parent (:class:`str`): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.ListFindingsRequest(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_findings, + 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=480.0, + ), + default_timeout=480.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.ListFindingsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs(self, + request: securitycenter_service.ListNotificationConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest`): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs, + 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.ListNotificationConfigsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources(self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.ListSourcesRequest(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_sources, + 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.ListSourcesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery(self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state(self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp_pb2.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding.State`): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + 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 = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # 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_finding_state, + 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 set_iam_policy(self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) + + # 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=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(( + ("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, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + 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.") + + # 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) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) + + # 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_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(( + ("resource", request.resource), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_finding(self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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 = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding, + 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(( + ("finding.name", request.finding.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_notification_config(self, + request: securitycenter_service.UpdateNotificationConfigRequest = None, + *, + notification_config: gcs_notification_config.NotificationConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + + 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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([notification_config, 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 = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_config + 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_notification_config, + 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(( + ("notification_config.name", request.notification_config.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_organization_settings(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings`): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` 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.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + 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 = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # 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_organization_settings, + 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(( + ("organization_settings.name", request.organization_settings.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_source(self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating + the source resource. + If empty all mutable fields will be + updated. + + 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.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([source, 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 = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + 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_source, + 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(( + ("source.name", request.source.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_security_marks(self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`google.cloud.securitycenter_v1p1beta1.types.SecurityMarks`): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v1p1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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 = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks, + default_timeout=480.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(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # Send the request. + response = await 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-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecurityCenterAsyncClient", +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py new file mode 100644 index 00000000..a4cab349 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -0,0 +1,2600 @@ +# -*- 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + def get_transport_class(cls, + label: str = None, + ) -> Type[SecurityCenterTransport]: + """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1p1Beta1 APIs for Security Center service.""" + + @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 = "securitycenter.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: + SecurityCenterClient: 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: + SecurityCenterClient: 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) -> SecurityCenterTransport: + """Returns the transport used by the client instance. + + Returns: + SecurityCenterTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def asset_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified asset string.""" + return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def finding_path(organization: str,source: str,finding: str,) -> str: + """Returns a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str,str]: + """Parses a finding path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str,notification_config: str,) -> str: + """Returns a fully-qualified notification_config string.""" + return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str,str]: + """Parses a notification_config path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Returns a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format(organization=organization, ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str,str]: + """Parses a organization_settings path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str,asset: str,) -> str: + """Returns a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str,str]: + """Parses a security_marks path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str,source: str,) -> str: + """Returns a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str,str]: + """Parses a source path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def topic_path(project: str,topic: str,) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str,str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SecurityCenterTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the security center 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, SecurityCenterTransport]): 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # 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, SecurityCenterTransport): + # transport is a SecurityCenterTransport instance. + if credentials or client_options.credentials_file: + 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: + 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=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def create_source(self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest): + The request object. Request message for creating a + source. + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + + This corresponds to the ``source`` 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.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, source]) + 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 securitycenter_service.CreateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_source] + + # 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_finding(self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest): + The request object. Request message for creating a + finding. + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (str): + Required. Unique identifier provided + by the client within the parent scope. + + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + + This corresponds to the ``finding`` 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, finding_id, finding]) + 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 securitycenter_service.CreateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_finding] + + # 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_notification_config(self, + request: securitycenter_service.CreateNotificationConfigRequest = None, + *, + parent: str = None, + config_id: str = None, + notification_config: gcs_notification_config.NotificationConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest): + The request object. Request message for creating a + notification config. + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (str): + Required. Unique identifier provided + by the client within the parent scope. + It must be between 1 and 128 characters, + and contains alphanumeric characters, + underscores or hyphens only. + + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + + This corresponds to the ``notification_config`` 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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, config_id, notification_config]) + 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 securitycenter_service.CreateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateNotificationConfigRequest): + request = securitycenter_service.CreateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_notification_config] + + # 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 delete_notification_config(self, + request: securitycenter_service.DeleteNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a notification config. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest): + The request object. Request message for deleting a + notification config. + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + + 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. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.DeleteNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.DeleteNotificationConfigRequest): + request = securitycenter_service.DeleteNotificationConfigRequest(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.delete_notification_config] + + # 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_iam_policy(self, + request: iam_policy_pb2.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): + The request object. Request message for `GetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_notification_config(self, + request: securitycenter_service.GetNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest): + The request object. Request message for getting a + notification config. + name (str): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + + 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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(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_notification_config] + + # 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_organization_settings(self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest): + The request object. Request message for getting + organization settings. + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + + 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.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): + request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings] + + # 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_source(self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest): + The request object. Request message for getting a + source. + name (str): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + + 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.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(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_source] + + # 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 group_assets(self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest): + The request object. Request message for grouping by + assets. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_assets] + + # 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.GroupAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings(self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest): + The request object. Request message for grouping by + findings. + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (str): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration + is set: + + - state_change + + This corresponds to the ``group_by`` 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.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, group_by]) + 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 securitycenter_service.GroupFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.group_findings] + + # 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.GroupFindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: securitycenter_service.ListAssetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest): + The request object. Request message for listing assets. + parent (str): + Required. Name of the organization assets should belong + to. Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(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_assets] + + # 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.ListAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings(self, + request: securitycenter_service.ListFindingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest): + The request object. Request message for listing + findings. + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list + across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(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_findings] + + # 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.ListFindingsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs(self, + request: securitycenter_service.ListNotificationConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotificationConfigsPager: + r"""Lists notification configs. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): + The request object. Request message for listing + notification configs. + parent (str): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListNotificationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListNotificationConfigsRequest): + request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs] + + # 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.ListNotificationConfigsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources(self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest): + The request object. Request message for listing sources. + parent (str): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id], folders/[folder_id], + or projects/[project_id]". + + 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListSourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(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_sources] + + # 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.ListSourcesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery(self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest): + The request object. Request message for running asset + discovery for an organization. + parent (str): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.RunAssetDiscoveryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty_pb2.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state(self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp_pb2.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest): + The request object. Request message for updating a + finding's state. + name (str): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + Required. The desired State of the + finding. + + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the + updated state takes effect. + + This corresponds to the ``start_time`` 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, state, start_time]) + 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 securitycenter_service.SetFindingStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_finding_state] + + # 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 set_iam_policy(self, + request: iam_policy_pb2.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): + The request object. Request message for `SetIamPolicy` + method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # 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, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): + The request object. Request message for + `TestIamPermissions` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (Sequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + 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.') + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_finding(self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest): + The request object. Request message for updating or + creating a finding. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + + 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.securitycenter_v1p1beta1.types.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([finding, 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 securitycenter_service.UpdateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if finding is not None: + request.finding = finding + 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_finding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("finding.name", request.finding.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_notification_config(self, + request: securitycenter_service.UpdateNotificationConfigRequest = None, + *, + notification_config: gcs_notification_config.NotificationConfig = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest): + The request object. Request message for updating a + notification config. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config to + update. + + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + + 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.securitycenter_v1p1beta1.types.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([notification_config, 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 securitycenter_service.UpdateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateNotificationConfigRequest): + request = securitycenter_service.UpdateNotificationConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if notification_config is not None: + request.notification_config = notification_config + 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_notification_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("notification_config.name", request.notification_config.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_organization_settings(self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest): + The request object. Request message for updating an + organization's settings. + organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): + Required. The organization settings + resource to update. + + This corresponds to the ``organization_settings`` 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.securitycenter_v1p1beta1.types.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([organization_settings]) + 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 securitycenter_service.UpdateOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("organization_settings.name", request.organization_settings.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_source(self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest): + The request object. Request message for updating a + source. + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The source resource to + update. + + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating + the source resource. + If empty all mutable fields will be + updated. + + 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.securitycenter_v1p1beta1.types.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([source, 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 securitycenter_service.UpdateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if source is not None: + request.source = source + 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_source] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("source.name", request.source.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_security_marks(self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Required. The security marks resource + to update. + + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + + 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.securitycenter_v1p1beta1.types.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([security_marks, 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 securitycenter_service.UpdateSecurityMarksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if security_marks is not None: + request.security_marks = security_marks + 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_security_marks] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("security_marks.name", request.security_marks.name), + )), + ) + + # 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-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "SecurityCenterClient", +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py new file mode 100644 index 00000000..be794371 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py @@ -0,0 +1,752 @@ +# -*- 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` + 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[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: + 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) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` + 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[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): + 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 = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: + 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) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` + 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[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: + 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) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` + 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[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): + 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 = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: + 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) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` + 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[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: + 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) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` + 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[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): + 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 = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: + 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) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` + 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[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse): + 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 = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: + 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) -> Iterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` + 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[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListFindingsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse): + 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 = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: + 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) -> AsyncIterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` + 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[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListNotificationConfigsResponse]: + 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) -> Iterable[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` + 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[securitycenter_service.ListNotificationConfigsResponse]], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): + 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 = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListNotificationConfigsResponse]: + 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) -> AsyncIterable[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` + 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[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1p1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: + 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) -> Iterable[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` + 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[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + 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.securitycenter_v1p1beta1.types.ListSourcesRequest): + The initial request object. + response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): + 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 = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: + 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) -> AsyncIterable[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + 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/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..8bdaf713 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/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 SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry['grpc'] = SecurityCenterGrpcTransport +_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport + +__all__ = ( + 'SecurityCenterTransport', + 'SecurityCenterGrpcTransport', + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py new file mode 100644 index 00000000..21af4750 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -0,0 +1,572 @@ +# -*- 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 packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-securitycenter', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'securitycenter.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 = self._get_scopes_kwargs(self._host, 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 is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_source: gapic_v1.method.wrap_method( + self.create_source, + default_timeout=60.0, + client_info=client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + 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_notification_config: gapic_v1.method.wrap_method( + self.get_notification_config, + 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_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + 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_source: gapic_v1.method.wrap_method( + self.get_source, + 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.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + 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=480.0, + ), + default_timeout=480.0, + client_info=client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_configs, + 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_sources: gapic_v1.method.wrap_method( + self.list_sources, + 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.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + 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_finding: gapic_v1.method.wrap_method( + self.update_finding, + default_timeout=60.0, + client_info=client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, + default_timeout=60.0, + client_info=client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + 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 get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Union[ + notification_config.NotificationConfig, + Awaitable[notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Union[ + organization_settings.OrganizationSettings, + Awaitable[organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Union[ + source.Source, + Awaitable[source.Source] + ]]: + raise NotImplementedError() + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Union[ + securitycenter_service.GroupAssetsResponse, + Awaitable[securitycenter_service.GroupAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Union[ + securitycenter_service.GroupFindingsResponse, + Awaitable[securitycenter_service.GroupFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Union[ + securitycenter_service.ListAssetsResponse, + Awaitable[securitycenter_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Union[ + securitycenter_service.ListFindingsResponse, + Awaitable[securitycenter_service.ListFindingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Union[ + securitycenter_service.ListNotificationConfigsResponse, + Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Union[ + securitycenter_service.ListSourcesResponse, + Awaitable[securitycenter_service.ListSourcesResponse] + ]]: + raise NotImplementedError() + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Union[ + finding.Finding, + Awaitable[finding.Finding] + ]]: + 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 test_iam_permissions(self) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse] + ]]: + raise NotImplementedError() + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Union[ + gcs_finding.Finding, + Awaitable[gcs_finding.Finding] + ]]: + raise NotImplementedError() + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Union[ + gcs_notification_config.NotificationConfig, + Awaitable[gcs_notification_config.NotificationConfig] + ]]: + raise NotImplementedError() + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Union[ + gcs_organization_settings.OrganizationSettings, + Awaitable[gcs_organization_settings.OrganizationSettings] + ]]: + raise NotImplementedError() + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Union[ + gcs_source.Source, + Awaitable[gcs_source.Source] + ]]: + raise NotImplementedError() + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Union[ + gcs_security_marks.SecurityMarks, + Awaitable[gcs_security_marks.SecurityMarks] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'SecurityCenterTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..1f374822 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py @@ -0,0 +1,877 @@ +# -*- 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 # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # 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 + +import grpc # type: ignore + +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center service. + + 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 = 'securitycenter.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 applicatin 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 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 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'securitycenter.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 operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_notification_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + operations_pb2.Operation]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.Finding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + +__all__ = ( + 'SecurityCenterGrpcTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..f7337a74 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,881 @@ +# -*- 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center service. + + 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 = 'securitycenter.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 = 'securitycenter.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 applicatin 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 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 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] = {} + self._operations_client = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_source(self) -> Callable[ + [securitycenter_service.CreateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['create_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['create_source'] + + @property + def create_finding(self) -> Callable[ + [securitycenter_service.CreateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['create_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['create_finding'] + + @property + def create_notification_config(self) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['create_notification_config'] + + @property + def delete_notification_config(self) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_notification_config' not in self._stubs: + self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_notification_config'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['get_iam_policy'] + + @property + def get_notification_config(self) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig]]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs['get_notification_config'] + + @property + def get_organization_settings(self) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings]]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['get_organization_settings'] + + @property + def get_source(self) -> Callable[ + [securitycenter_service.GetSourceRequest], + Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['get_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs['get_source'] + + @property + def group_assets(self) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse]]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_assets' not in self._stubs: + self._stubs['group_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs['group_assets'] + + @property + def group_findings(self) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse]]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings, + /v1/folders/{folder_id}/sources/-/findings, + /v1/projects/{project_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'group_findings' not in self._stubs: + self._stubs['group_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs['group_findings'] + + @property + def list_assets(self) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def list_findings(self) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse]]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_findings' not in self._stubs: + self._stubs['list_findings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings', + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs['list_findings'] + + @property + def list_notification_configs(self) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_configs' not in self._stubs: + self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs['list_notification_configs'] + + @property + def list_sources(self) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse]]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sources' not in self._stubs: + self._stubs['list_sources'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs['list_sources'] + + @property + def run_asset_discovery(self) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_asset_discovery' not in self._stubs: + self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['run_asset_discovery'] + + @property + def set_finding_state(self) -> Callable[ + [securitycenter_service.SetFindingStateRequest], + Awaitable[finding.Finding]]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding_state' not in self._stubs: + self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs['set_finding_state'] + + @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 access control policy on the specified + Source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs['set_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. + + Returns the permissions that a caller has on the + specified source. + + 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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs['test_iam_permissions'] + + @property + def update_finding(self) -> Callable[ + [securitycenter_service.UpdateFindingRequest], + Awaitable[gcs_finding.Finding]]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + Awaitable[~.Finding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_finding' not in self._stubs: + self._stubs['update_finding'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs['update_finding'] + + @property + def update_notification_config(self) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig]]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_notification_config' not in self._stubs: + self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs['update_notification_config'] + + @property + def update_organization_settings(self) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings]]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: + self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs['update_organization_settings'] + + @property + def update_source(self) -> Callable[ + [securitycenter_service.UpdateSourceRequest], + Awaitable[gcs_source.Source]]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_source' not in self._stubs: + self._stubs['update_source'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs['update_source'] + + @property + def update_security_marks(self) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks]]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_security_marks' not in self._stubs: + self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( + '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs['update_security_marks'] + + +__all__ = ( + 'SecurityCenterGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py new file mode 100644 index 00000000..f490e7f6 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py @@ -0,0 +1,114 @@ +# -*- 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 .asset import ( + Asset, +) +from .finding import ( + Finding, +) +from .folder import ( + Folder, +) +from .notification_config import ( + NotificationConfig, +) +from .notification_message import ( + NotificationMessage, +) +from .organization_settings import ( + OrganizationSettings, +) +from .resource import ( + Resource, +) +from .run_asset_discovery_response import ( + RunAssetDiscoveryResponse, +) +from .security_marks import ( + SecurityMarks, +) +from .securitycenter_service import ( + CreateFindingRequest, + CreateNotificationConfigRequest, + CreateSourceRequest, + DeleteNotificationConfigRequest, + GetNotificationConfigRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + RunAssetDiscoveryRequest, + SetFindingStateRequest, + UpdateFindingRequest, + UpdateNotificationConfigRequest, + UpdateOrganizationSettingsRequest, + UpdateSecurityMarksRequest, + UpdateSourceRequest, +) +from .source import ( + Source, +) + +__all__ = ( + 'Asset', + 'Finding', + 'Folder', + 'NotificationConfig', + 'NotificationMessage', + 'OrganizationSettings', + 'Resource', + 'RunAssetDiscoveryResponse', + 'SecurityMarks', + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'RunAssetDiscoveryRequest', + 'SetFindingStateRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSecurityMarksRequest', + 'UpdateSourceRequest', + 'Source', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py new file mode 100644 index 00000000..8617389d --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py @@ -0,0 +1,223 @@ +# -*- 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.securitycenter_v1p1beta1.types import folder +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Asset', + }, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (google.cloud.securitycenter_v1p1beta1.types.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.Asset.ResourcePropertiesEntry]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the asset was last updated + or added in Cloud SCC. + iam_policy (google.cloud.securitycenter_v1p1beta1.types.Asset.IamPolicy): + Cloud IAM Policy information associated with + the Google Cloud resource described by the + Security Command Center asset. This information + is managed and defined by the Google Cloud + resource and cannot be modified by the user. + canonical_name (str): + The canonical name of the resource. It's either + "organizations/{organization_id}/assets/{asset_id}", + "folders/{folder_id}/assets/{asset_id}" or + "projects/{project_number}/assets/{asset_id}", depending on + the closest CRM ancestor of the resource. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + The full resource name of the Google Cloud resource this + asset represents. This field is immutable after create time. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (Sequence[str]): + Owners of the Google Cloud resource. + resource_display_name (str): + The user defined display name for this + resource. + resource_parent_display_name (str): + The user defined display name for the parent + of this resource. + resource_project_display_name (str): + The user defined display name for the project + of this resource. + folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + resource_name = proto.Field( + proto.STRING, + number=1, + ) + resource_type = proto.Field( + proto.STRING, + number=2, + ) + resource_parent = proto.Field( + proto.STRING, + number=3, + ) + resource_project = proto.Field( + proto.STRING, + number=4, + ) + resource_owners = proto.RepeatedField( + proto.STRING, + number=5, + ) + resource_display_name = proto.Field( + proto.STRING, + number=6, + ) + resource_parent_display_name = proto.Field( + proto.STRING, + number=7, + ) + resource_project_display_name = proto.Field( + proto.STRING, + number=8, + ) + folders = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + class IamPolicy(proto.Message): + r"""Cloud IAM Policy information associated with the Google Cloud + resource described by the Security Command Center asset. This + information is managed and defined by the Google Cloud resource + and cannot be modified by the user. + + Attributes: + policy_blob (str): + The JSON representation of the Policy + associated with the asset. See + https://cloud.google.com/iam/docs/reference/rest/v1/Policy + for format details. + """ + + policy_blob = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + security_center_properties = proto.Field( + proto.MESSAGE, + number=2, + message=SecurityCenterProperties, + ) + resource_properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + create_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + iam_policy = proto.Field( + proto.MESSAGE, + number=11, + message=IamPolicy, + ) + canonical_name = proto.Field( + proto.STRING, + number=13, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py new file mode 100644 index 00000000..0c2b4ff0 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py @@ -0,0 +1,180 @@ +# -*- 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.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Finding', + }, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + A finding is a record of assessment data (security, risk, health + or privacy) ingested into Security Command Center for + presentation, notification, analysis, policy testing, and + enforcement. For example, an XSS vulnerability in an App Engine + application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + The relative resource name of the source the finding belongs + to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.Finding.SourcePropertiesEntry]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the event took place, or + when an update to the finding occurred. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. If the finding + were to be resolved afterward, this time would + reflect when the finding was resolved. Must not + be set to a value greater than the current + timestamp. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the finding was created in + Security Command Center. + severity (google.cloud.securitycenter_v1p1beta1.types.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes the finding. + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" + or + "projects/{project_number}/sources/{source_id}/findings/{finding_id}", + depending on the closest CRM ancestor of the resource + associated with the finding. + """ + class State(proto.Enum): + r"""The state of the finding.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + class Severity(proto.Enum): + r"""The severity of the finding. This field is managed by the + source that writes the finding. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + name = proto.Field( + proto.STRING, + number=1, + ) + parent = proto.Field( + proto.STRING, + number=2, + ) + resource_name = proto.Field( + proto.STRING, + number=3, + ) + state = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + category = proto.Field( + proto.STRING, + number=5, + ) + external_uri = proto.Field( + proto.STRING, + number=6, + ) + source_properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=struct_pb2.Value, + ) + security_marks = proto.Field( + proto.MESSAGE, + number=8, + message=gcs_security_marks.SecurityMarks, + ) + event_time = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + severity = proto.Field( + proto.ENUM, + number=13, + enum=Severity, + ) + canonical_name = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py new file mode 100644 index 00000000..90b8f72c --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py @@ -0,0 +1,50 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Folder', + }, +) + + +class Folder(proto.Message): + r"""Message that contains the resource name and display name of a + folder resource. + + Attributes: + resource_folder (str): + Full resource name of this folder. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_folder_display_name (str): + The user defined display name for this + folder. + """ + + resource_folder = proto.Field( + proto.STRING, + number=1, + ) + resource_folder_display_name = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py new file mode 100644 index 00000000..e314b944 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py @@ -0,0 +1,126 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'NotificationConfig', + }, +) + + +class NotificationConfig(proto.Message): + r"""Security Command Center notification configs. + A notification config is a Security Command Center resource that + contains the configuration to send notifications for + create/update events of findings, assets and etc. + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/notificationConfigs/notify_public_bucket". + description (str): + The description of the notification config + (max of 1024 characters). + event_type (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.EventType): + The type of events the config is for, e.g. + FINDING. + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + """ + class EventType(proto.Enum): + r"""The type of events.""" + EVENT_TYPE_UNSPECIFIED = 0 + FINDING = 1 + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter = proto.Field( + proto.STRING, + number=1, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + description = proto.Field( + proto.STRING, + number=2, + ) + event_type = proto.Field( + proto.ENUM, + number=3, + enum=EventType, + ) + pubsub_topic = proto.Field( + proto.STRING, + number=4, + ) + service_account = proto.Field( + proto.STRING, + number=5, + ) + streaming_config = proto.Field( + proto.MESSAGE, + number=6, + oneof='notify_config', + message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py new file mode 100644 index 00000000..ad874607 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py @@ -0,0 +1,60 @@ +# -*- 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.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'NotificationMessage', + }, +) + + +class NotificationMessage(proto.Message): + r"""Security Command Center's Notification + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + If it's a Finding based notification config, + this field will be populated. + resource (google.cloud.securitycenter_v1p1beta1.types.Resource): + The Cloud resource tied to the notification. + """ + + notification_config_name = proto.Field( + proto.STRING, + number=1, + ) + finding = proto.Field( + proto.MESSAGE, + number=2, + oneof='event', + message=gcs_finding.Finding, + ) + resource = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_resource.Resource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py new file mode 100644 index 00000000..0626dfa8 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py @@ -0,0 +1,104 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'OrganizationSettings', + }, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + Attributes: + project_ids (Sequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + folder_ids (Sequence[str]): + The folder ids to use for filtering asset + discovery. It consists of only digits, e.g., + 756619654966. + """ + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids = proto.RepeatedField( + proto.STRING, + number=1, + ) + inclusion_mode = proto.Field( + proto.ENUM, + number=2, + enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', + ) + folder_ids = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name = proto.Field( + proto.STRING, + number=1, + ) + enable_asset_discovery = proto.Field( + proto.BOOL, + number=2, + ) + asset_discovery_config = proto.Field( + proto.MESSAGE, + number=3, + message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py new file mode 100644 index 00000000..eb56efe2 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py @@ -0,0 +1,80 @@ +# -*- 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.securitycenter_v1p1beta1.types import folder + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Resource', + }, +) + + +class Resource(proto.Message): + r"""Information related to the Google Cloud resource. + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Output only. Contains a Folder message for + each folder in the assets ancestry. The first + folder is the deepest nested folder, and the + last folder is the folder directly under the + Organization. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + project = proto.Field( + proto.STRING, + number=2, + ) + project_display_name = proto.Field( + proto.STRING, + number=3, + ) + parent = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name = proto.Field( + proto.STRING, + number=5, + ) + folders = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=folder.Folder, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..a8f0d526 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py @@ -0,0 +1,57 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'RunAssetDiscoveryResponse', + }, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + Attributes: + state (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (google.protobuf.duration_pb2.Duration): + The duration between asset discovery run + start and end + """ + class State(proto.Enum): + r"""The state of an asset discovery run.""" + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py new file mode 100644 index 00000000..bb9b46e5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py @@ -0,0 +1,76 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'SecurityMarks', + }, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (Sequence[google.cloud.securitycenter_v1p1beta1.types.SecurityMarks.MarksEntry]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + canonical_name (str): + The canonical name of the marks. Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "folders/{folder_id}/assets/{asset_id}/securityMarks" + "projects/{project_number}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" + "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + marks = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + canonical_name = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py new file mode 100644 index 00000000..b32dabc4 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py @@ -0,0 +1,1581 @@ +# -*- 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.securitycenter_v1p1beta1.types import asset as gcs_asset +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import folder +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'CreateFindingRequest', + 'CreateNotificationConfigRequest', + 'CreateSourceRequest', + 'DeleteNotificationConfigRequest', + 'GetNotificationConfigRequest', + 'GetOrganizationSettingsRequest', + 'GetSourceRequest', + 'GroupAssetsRequest', + 'GroupAssetsResponse', + 'GroupFindingsRequest', + 'GroupFindingsResponse', + 'GroupResult', + 'ListNotificationConfigsRequest', + 'ListNotificationConfigsResponse', + 'ListSourcesRequest', + 'ListSourcesResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFindingsRequest', + 'ListFindingsResponse', + 'SetFindingStateRequest', + 'RunAssetDiscoveryRequest', + 'UpdateFindingRequest', + 'UpdateNotificationConfigRequest', + 'UpdateOrganizationSettingsRequest', + 'UpdateSourceRequest', + 'UpdateSecurityMarksRequest', + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + finding_id = proto.Field( + proto.STRING, + number=2, + ) + finding = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_finding.Finding, + ) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + config_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + between 1 and 128 characters, and contains + alphanumeric characters, underscores or hyphens + only. + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + config_id = proto.Field( + proto.STRING, + number=2, + ) + notification_config = proto.Field( + proto.MESSAGE, + number=3, + message=gcs_notification_config.NotificationConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + source = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_source.Source, + ) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + Attributes: + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + Attributes: + name (str): + Required. Name of the notification config to get. Its format + is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id], folders/[folder_id], or + projects/[project_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_name_display_name: + ``=``, ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" property is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + group_by = proto.Field( + proto.STRING, + number=3, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + read_time = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + page_token = proto.Field( + proto.STRING, + number=7, + ) + page_size = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + Attributes: + group_by_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]", + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]. To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/-, or + projects/{project_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + - severity: ``=``, ``:`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state_change``). The string value + should follow SQL syntax: comma separated list of fields. + For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + - severity + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the GroupResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + group_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + page_token = proto.Field( + proto.STRING, + number=7, + ) + page_size = proto.Field( + proto.INT32, + number=8, + ) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + Attributes: + group_by_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GroupResult', + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult.PropertiesEntry]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=struct_pb2.Value, + ) + count = proto.Field( + proto.INT64, + number=2, + ) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + Attributes: + parent (str): + Required. Name of the organization to list notification + configs. Its format is "organizations/[organization_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + + +class ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + Attributes: + notification_configs (Sequence[google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + page_token = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=7, + ) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + Attributes: + sources (Sequence[google.cloud.securitycenter_v1p1beta1.types.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + next_page_token = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id], + folders/[folder_id], or projects/[project_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following are the allowed field and operator + combinations: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + + The following fields are supported: name update_time + resource_properties security_marks.marks + security_center_properties.resource_name + security_center_properties.resource_display_name + security_center_properties.resource_parent + security_center_properties.resource_parent_display_name + security_center_properties.resource_project + security_center_properties.resource_project_display_name + security_center_properties.resource_type + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListAssetsResult's + "state_change" attribute is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the ListAssetsResult + fields to be listed in the response. + An empty field mask will list all fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + order_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + page_size = proto.Field( + proto.INT32, + number=9, + ) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + Attributes: + list_assets_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + Attributes: + asset (google.cloud.securitycenter_v1p1beta1.types.Asset): + Asset matching the search request. + state_change (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult.StateChange): + State change of the asset between the points + in time. + """ + class StateChange(proto.Enum): + r"""The change in state of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state change will be: + UNUSED + """ + UNUSED = 0 + ADDED = 1 + REMOVED = 2 + ACTIVE = 3 + + asset = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_asset.Asset, + ) + state_change = proto.Field( + proto.ENUM, + number=2, + enum='ListAssetsResponse.ListAssetsResult.StateChange', + ) + + @property + def raw_page(self): + return self + + list_assets_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListAssetsResult, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id], + folders/[folder_id]/sources/[source_id], or + projects/[project_id]/sources/[source_id]". To list across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/-, + folders/{folder_id}/sources/- or + projects/{projects_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + - severity: ``=``, ``:`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + security_marks.marks: ``=``, ``:`` source_properties: ``=``, + ``:``, ``>``, ``<``, ``>=``, ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time source_properties + security_marks.marks + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (google.protobuf.duration_pb2.Duration): + When compare_duration is set, the ListFindingsResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added in any state during + the compare_duration period of time that precedes the + read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + field_mask (google.protobuf.field_mask_pb2.FieldMask): + A field mask to specify the Finding fields to + be listed in the response. An empty field mask + will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + filter = proto.Field( + proto.STRING, + number=2, + ) + order_by = proto.Field( + proto.STRING, + number=3, + ) + read_time = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + compare_duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + field_mask = proto.Field( + proto.MESSAGE, + number=7, + message=field_mask_pb2.FieldMask, + ) + page_token = proto.Field( + proto.STRING, + number=8, + ) + page_size = proto.Field( + proto.INT32, + number=9, + ) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + Attributes: + list_findings_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding and its StateChange. + Attributes: + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Finding matching the search request. + state_change (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + class StateChange(proto.Enum): + r"""The change in state of the finding. + + When querying across two points in time this describes the change in + the finding between the two points: CHANGED, UNCHANGED, ADDED, or + REMOVED. Findings can not be deleted, so REMOVED implies that the + finding at timestamp does not match the filter specified, but it did + at timestamp - compare_duration. If there was no compare_duration + supplied in the request the state change will be: UNUSED + """ + UNUSED = 0 + CHANGED = 1 + UNCHANGED = 2 + ADDED = 3 + REMOVED = 4 + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project_name (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent_name (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): + Contains a Folder message for each folder in + the assets ancestry. The first folder is the + deepest nested folder, and the last folder is + the folder directly under the Organization. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + project_name = proto.Field( + proto.STRING, + number=2, + ) + project_display_name = proto.Field( + proto.STRING, + number=3, + ) + parent_name = proto.Field( + proto.STRING, + number=4, + ) + parent_display_name = proto.Field( + proto.STRING, + number=5, + ) + folders = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=folder.Folder, + ) + + finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + state_change = proto.Field( + proto.ENUM, + number=2, + enum='ListFindingsResponse.ListFindingsResult.StateChange', + ) + resource = proto.Field( + proto.MESSAGE, + number=3, + message='ListFindingsResponse.ListFindingsResult.Resource', + ) + + @property + def raw_page(self): + return self + + list_findings_results = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ListFindingsResult, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + next_page_token = proto.Field( + proto.STRING, + number=3, + ) + total_size = proto.Field( + proto.INT32, + number=4, + ) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): + Required. The desired State of the finding. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + state = proto.Field( + proto.ENUM, + number=2, + enum=gcs_finding.Finding.State, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + Attributes: + finding (google.cloud.securitycenter_v1p1beta1.types.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_finding.Finding, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + Attributes: + notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): + Required. The notification config to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_notification_config.NotificationConfig, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + Attributes: + organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the + settings resource. + If empty all mutable fields will be updated. + """ + + organization_settings = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_organization_settings.OrganizationSettings, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + Attributes: + source (google.cloud.securitycenter_v1p1beta1.types.Source): + Required. The source resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_source.Source, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + Attributes: + security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): + Required. The security marks resource to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the updated SecurityMarks + take effect. If not set uses current server + time. Updates will be applied to the + SecurityMarks that are active immediately + preceding this time. + """ + + security_marks = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_security_marks.SecurityMarks, + ) + update_mask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + start_time = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py new file mode 100644 index 00000000..d8885041 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py @@ -0,0 +1,83 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.cloud.securitycenter.v1p1beta1', + manifest={ + 'Source', + }, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, etc. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and + outdated/insecure libraries.". + canonical_name (str): + The canonical name of the finding. It's either + "organizations/{organization_id}/sources/{source_id}", + "folders/{folder_id}/sources/{source_id}" or + "projects/{project_number}/sources/{source_id}", depending + on the closest CRM ancestor of the resource associated with + the finding. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + display_name = proto.Field( + proto.STRING, + number=2, + ) + description = proto.Field( + proto.STRING, + number=3, + ) + canonical_name = proto.Field( + proto.STRING, + number=14, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/mypy.ini b/owl-bot-staging/v1p1beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1p1beta1/noxfile.py b/owl-bot-staging/v1p1beta1/noxfile.py new file mode 100644 index 00000000..29b101a6 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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']) +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/securitycenter_v1p1beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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']) +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.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/owl-bot-staging/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py b/owl-bot-staging/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py new file mode 100644 index 00000000..43acd75e --- /dev/null +++ b/owl-bot-staging/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py @@ -0,0 +1,198 @@ +#! /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 securitycenterCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_finding': ('parent', 'finding_id', 'finding', ), + 'create_notification_config': ('parent', 'config_id', 'notification_config', ), + 'create_source': ('parent', 'source', ), + 'delete_notification_config': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_notification_config': ('name', ), + 'get_organization_settings': ('name', ), + 'get_source': ('name', ), + 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), + 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), + 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), + 'list_notification_configs': ('parent', 'page_token', 'page_size', ), + 'list_sources': ('parent', 'page_token', 'page_size', ), + 'run_asset_discovery': ('parent', ), + 'set_finding_state': ('name', 'state', 'start_time', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'update_finding': ('finding', 'update_mask', ), + 'update_notification_config': ('notification_config', 'update_mask', ), + 'update_organization_settings': ('organization_settings', 'update_mask', ), + 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), + 'update_source': ('source', 'update_mask', ), + } + + 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: not a.keyword.value 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=securitycenterCallTransformer(), +): + """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 securitycenter 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/v1p1beta1/setup.py b/owl-bot-staging/v1p1beta1/setup.py new file mode 100644 index 00000000..0653f115 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/setup.py @@ -0,0 +1,54 @@ +# -*- 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-securitycenter', + 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.27.0, < 3.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', '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/v1p1beta1/tests/__init__.py b/owl-bot-staging/v1p1beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__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/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py new file mode 100644 index 00000000..18b18e7a --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py @@ -0,0 +1,7809 @@ +# -*- 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 packaging.version + +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 future +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 operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.securitycenter_v1p1beta1.services.security_center import SecurityCenterAsyncClient +from google.cloud.securitycenter_v1p1beta1.services.security_center import SecurityCenterClient +from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.services.security_center import transports +from google.cloud.securitycenter_v1p1beta1.services.security_center.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +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.longrunning import operations_pb2 +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 struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +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 SecurityCenterClient._get_default_mtls_endpoint(None) is None + assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [ + SecurityCenterClient, + SecurityCenterAsyncClient, +]) +def test_security_center_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 == 'securitycenter.googleapis.com:443' + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SecurityCenterGrpcTransport, "grpc"), + (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_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", [ + SecurityCenterClient, + SecurityCenterAsyncClient, +]) +def test_security_center_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 == 'securitycenter.googleapis.com:443' + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + available_transports = [ + transports.SecurityCenterGrpcTransport, + ] + assert transport in available_transports + + transport = SecurityCenterClient.get_transport_class("grpc") + assert transport == transports.SecurityCenterGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +def test_security_center_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(SecurityCenterClient, '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(SecurityCenterClient, '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(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() + 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() + 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() + + # 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() + + # 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) + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), +]) +@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) +@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_security_center_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) + + 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() + 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() + 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,transport_class,transport_name", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_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) + 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", [ + (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), + (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options) + 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_security_center_client_client_options_from_dict(): + with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SecurityCenterClient( + 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, + ) + + +def test_create_source(transport: str = 'grpc', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_create_source_from_dict(): + test_create_source(request_type=dict) + + +def test_create_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.create_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.create_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_source_async_from_dict(): + await test_create_source_async(request_type=dict) + + +def test_create_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.create_source(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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateSourceRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.create_source(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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_source( + parent='parent_value', + source=gcs_source.Source(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] + assert args[0].parent == 'parent_value' + assert args[0].source == gcs_source.Source(name='name_value') + + +def test_create_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_source( + parent='parent_value', + source=gcs_source.Source(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] + assert args[0].parent == 'parent_value' + assert args[0].source == gcs_source.Source(name='name_value') + + +@pytest.mark.asyncio +async def test_create_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.CreateSourceRequest(), + parent='parent_value', + source=gcs_source.Source(name='name_value'), + ) + + +def test_create_finding(transport: str = 'grpc', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_create_finding_from_dict(): + test_create_finding(request_type=dict) + + +def test_create_finding_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 = SecurityCenterClient( + 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_finding), + '__call__') as call: + client.create_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.create_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_create_finding_async_from_dict(): + await test_create_finding_async(request_type=dict) + + +def test_create_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.create_finding(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_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateFindingRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.create_finding(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_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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] + assert args[0].parent == 'parent_value' + assert args[0].finding_id == 'finding_id_value' + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +def test_create_finding_flattened_error(): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_finding( + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(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] + assert args[0].parent == 'parent_value' + assert args[0].finding_id == 'finding_id_value' + assert args[0].finding == gcs_finding.Finding(name='name_value') + + +@pytest.mark.asyncio +async def test_create_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_finding( + securitycenter_service.CreateFindingRequest(), + parent='parent_value', + finding_id='finding_id_value', + finding=gcs_finding.Finding(name='name_value'), + ) + + +def test_create_notification_config(transport: str = 'grpc', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + streaming_config=gcs_notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), + ) + response = client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_create_notification_config_from_dict(): + test_create_notification_config(request_type=dict) + + +def test_create_notification_config_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 = SecurityCenterClient( + 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_notification_config), + '__call__') as call: + client.create_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.create_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.CreateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_create_notification_config_async_from_dict(): + await test_create_notification_config_async(request_type=dict) + + +def test_create_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.create_notification_config(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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.CreateNotificationConfigRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.create_notification_config(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_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(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] + assert args[0].parent == 'parent_value' + assert args[0].config_id == 'config_id_value' + assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') + + +def test_create_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_notification_config( + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(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] + assert args[0].parent == 'parent_value' + assert args[0].config_id == 'config_id_value' + assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') + + +@pytest.mark.asyncio +async def test_create_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_notification_config( + securitycenter_service.CreateNotificationConfigRequest(), + parent='parent_value', + config_id='config_id_value', + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + ) + + +def test_delete_notification_config(transport: str = 'grpc', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_from_dict(): + test_delete_notification_config(request_type=dict) + + +def test_delete_notification_config_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 = SecurityCenterClient( + 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.delete_notification_config), + '__call__') as call: + client.delete_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_notification_config_async_from_dict(): + await test_delete_notification_config_async(request_type=dict) + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value = None + client.delete_notification_config(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_delete_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.DeleteNotificationConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_notification_config(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_delete_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_notification_config( + 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] + assert args[0].name == 'name_value' + + +def test_delete_notification_config_flattened_error(): + client = SecurityCenterClient( + 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.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_notification_config( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_delete_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.delete_notification_config( + securitycenter_service.DeleteNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + test_get_iam_policy(request_type=dict) + + +def test_get_iam_policy_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 = SecurityCenterClient( + 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_iam_policy), + '__call__') as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() + + # 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_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource='resource_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] + assert args[0].resource == 'resource_value' + + +def test_get_iam_policy_flattened_error(): + client = SecurityCenterClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_get_notification_config(transport: str = 'grpc', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + streaming_config=notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), + ) + response = client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_get_notification_config_from_dict(): + test_get_notification_config(request_type=dict) + + +def test_get_notification_config_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 = SecurityCenterClient( + 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_notification_config), + '__call__') as call: + client.get_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.get_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_async_from_dict(): + await test_get_notification_config_async(request_type=dict) + + +def test_get_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value = notification_config.NotificationConfig() + client.get_notification_config(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_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetNotificationConfigRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + await client.get_notification_config(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_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_notification_config( + 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] + assert args[0].name == 'name_value' + + +def test_get_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_notification_config( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_notification_config( + securitycenter_service.GetNotificationConfigRequest(), + name='name_value', + ) + + +def test_get_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_get_organization_settings_from_dict(): + test_get_organization_settings(request_type=dict) + + +def test_get_organization_settings_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 = SecurityCenterClient( + 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_organization_settings), + '__call__') as call: + client.get_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.get_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_get_organization_settings_async_from_dict(): + await test_get_organization_settings_async(request_type=dict) + + +def test_get_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = organization_settings.OrganizationSettings() + client.get_organization_settings(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_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetOrganizationSettingsRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + await client.get_organization_settings(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_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_organization_settings( + 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] + assert args[0].name == 'name_value' + + +def test_get_organization_settings_flattened_error(): + client = SecurityCenterClient( + 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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_organization_settings( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_organization_settings( + securitycenter_service.GetOrganizationSettingsRequest(), + name='name_value', + ) + + +def test_get_source(transport: str = 'grpc', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_get_source_from_dict(): + test_get_source(request_type=dict) + + +def test_get_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.get_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.get_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GetSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_get_source_async_from_dict(): + await test_get_source_async(request_type=dict) + + +def test_get_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = source.Source() + client.get_source(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_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GetSourceRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + await client.get_source(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_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_source( + 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] + assert args[0].name == 'name_value' + + +def test_get_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +@pytest.mark.asyncio +async def test_get_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_source( + 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] + assert args[0].name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.GetSourceRequest(), + name='name_value', + ) + + +def test_group_assets(transport: str = 'grpc', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_assets_from_dict(): + test_group_assets(request_type=dict) + + +def test_group_assets_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 = SecurityCenterClient( + 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.group_assets), + '__call__') as call: + client.group_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_assets_async_from_dict(): + await test_group_assets_async(request_type=dict) + + +def test_group_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = securitycenter_service.GroupAssetsResponse() + client.group_assets(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_group_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) + await client.group_assets(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_group_assets_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_assets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + +def test_group_assets_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_assets(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_group_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_assets(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, securitycenter_service.GroupResult) + for i in responses) + +@pytest.mark.asyncio +async def test_group_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupAssetsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.group_assets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_group_findings(transport: str = 'grpc', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_group_findings_from_dict(): + test_group_findings(request_type=dict) + + +def test_group_findings_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 = SecurityCenterClient( + 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.group_findings), + '__call__') as call: + client.group_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.group_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.GroupFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_group_findings_async_from_dict(): + await test_group_findings_async(request_type=dict) + + +def test_group_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = securitycenter_service.GroupFindingsResponse() + client.group_findings(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_group_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.GroupFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + await client.group_findings(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_group_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.group_findings( + parent='parent_value', + group_by='group_by_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] + assert args[0].parent == 'parent_value' + assert args[0].group_by == 'group_by_value' + + +def test_group_findings_flattened_error(): + client = SecurityCenterClient( + 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.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +@pytest.mark.asyncio +async def test_group_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.GroupFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.group_findings( + parent='parent_value', + group_by='group_by_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == 'parent_value' + assert args[0].group_by == 'group_by_value' + + +@pytest.mark.asyncio +async def test_group_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.group_findings( + securitycenter_service.GroupFindingsRequest(), + parent='parent_value', + group_by='group_by_value', + ) + + +def test_group_findings_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.group_findings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.GroupResult) + for i in results) + +def test_group_findings_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = list(client.group_findings(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_group_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.group_findings(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, securitycenter_service.GroupResult) + for i in responses) + +@pytest.mark.asyncio +async def test_group_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.group_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + next_page_token='abc', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[], + next_page_token='def', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.GroupFindingsResponse( + group_by_results=[ + securitycenter_service.GroupResult(), + securitycenter_service.GroupResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.group_findings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_assets(transport: str = 'grpc', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_assets_from_dict(): + test_list_assets(request_type=dict) + + +def test_list_assets_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 = SecurityCenterClient( + 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_assets), + '__call__') as call: + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = securitycenter_service.ListAssetsResponse() + client.list_assets(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_assets_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListAssetsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + await client.list_assets(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_assets_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assets( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_assets_flattened_error(): + client = SecurityCenterClient( + 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_assets( + securitycenter_service.ListAssetsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_assets_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assets( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_assets_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_assets( + securitycenter_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in results) + +def test_list_assets_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) + for i in responses) + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[], + next_page_token='def', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListAssetsResponse( + list_assets_results=[ + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + securitycenter_service.ListAssetsResponse.ListAssetsResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_assets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_findings(transport: str = 'grpc', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_findings_from_dict(): + test_list_findings(request_type=dict) + + +def test_list_findings_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 = SecurityCenterClient( + 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_findings), + '__call__') as call: + client.list_findings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_findings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListFindingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_findings_async_from_dict(): + await test_list_findings_async(request_type=dict) + + +def test_list_findings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = securitycenter_service.ListFindingsResponse() + client.list_findings(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_findings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListFindingsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse()) + await client.list_findings(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_findings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListFindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_findings( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_findings_flattened_error(): + client = SecurityCenterClient( + 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_findings( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_findings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListFindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_findings( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_findings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_findings( + securitycenter_service.ListFindingsRequest(), + parent='parent_value', + ) + + +def test_list_findings_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_findings(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in results) + +def test_list_findings_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_findings(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_findings_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_findings(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, securitycenter_service.ListFindingsResponse.ListFindingsResult) + for i in responses) + +@pytest.mark.asyncio +async def test_list_findings_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='abc', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[], + next_page_token='def', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListFindingsResponse( + list_findings_results=[ + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + securitycenter_service.ListFindingsResponse.ListFindingsResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_findings(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_notification_configs(transport: str = 'grpc', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_notification_configs_from_dict(): + test_list_notification_configs(request_type=dict) + + +def test_list_notification_configs_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 = SecurityCenterClient( + 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_notification_configs), + '__call__') as call: + client.list_notification_configs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_notification_configs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListNotificationConfigsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_async_from_dict(): + await test_list_notification_configs_async(request_type=dict) + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + client.list_notification_configs(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_notification_configs_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListNotificationConfigsRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + await client.list_notification_configs(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_notification_configs_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_notification_configs( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_notification_configs_flattened_error(): + client = SecurityCenterClient( + 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_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListNotificationConfigsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_notification_configs( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_notification_configs_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_notification_configs( + securitycenter_service.ListNotificationConfigsRequest(), + parent='parent_value', + ) + + +def test_list_notification_configs_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_notification_configs(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, notification_config.NotificationConfig) + for i in results) + +def test_list_notification_configs_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = list(client.list_notification_configs(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_notification_configs_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_notification_configs(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, notification_config.NotificationConfig) + for i in responses) + +@pytest.mark.asyncio +async def test_list_notification_configs_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_notification_configs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + next_page_token='abc', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[], + next_page_token='def', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListNotificationConfigsResponse( + notification_configs=[ + notification_config.NotificationConfig(), + notification_config.NotificationConfig(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_notification_configs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_list_sources(transport: str = 'grpc', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sources_from_dict(): + test_list_sources(request_type=dict) + + +def test_list_sources_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 = SecurityCenterClient( + 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_sources), + '__call__') as call: + client.list_sources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.ListSourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sources_async_from_dict(): + await test_list_sources_async(request_type=dict) + + +def test_list_sources_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = securitycenter_service.ListSourcesResponse() + client.list_sources(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_sources_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.ListSourcesRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + await client.list_sources(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_sources_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sources( + 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] + assert args[0].parent == 'parent_value' + + +def test_list_sources_flattened_error(): + client = SecurityCenterClient( + 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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_list_sources_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = securitycenter_service.ListSourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sources( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_list_sources_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_sources( + securitycenter_service.ListSourcesRequest(), + parent='parent_value', + ) + + +def test_list_sources_pager(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_sources(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, source.Source) + for i in results) + +def test_list_sources_pages(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sources(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_sources_async_pager(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sources(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, source.Source) + for i in responses) + +@pytest.mark.asyncio +async def test_list_sources_async_pages(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + source.Source(), + ], + next_page_token='abc', + ), + securitycenter_service.ListSourcesResponse( + sources=[], + next_page_token='def', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + ], + next_page_token='ghi', + ), + securitycenter_service.ListSourcesResponse( + sources=[ + source.Source(), + source.Source(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_sources(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +def test_run_asset_discovery(transport: str = 'grpc', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_from_dict(): + test_run_asset_discovery(request_type=dict) + + +def test_run_asset_discovery_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 = SecurityCenterClient( + 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.run_asset_discovery), + '__call__') as call: + client.run_asset_discovery() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.run_asset_discovery(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async_from_dict(): + await test_run_asset_discovery_async(request_type=dict) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.run_asset_discovery(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_run_asset_discovery_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.RunAssetDiscoveryRequest() + + request.parent = 'parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.run_asset_discovery(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_run_asset_discovery_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.run_asset_discovery( + 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] + assert args[0].parent == 'parent_value' + + +def test_run_asset_discovery_flattened_error(): + client = SecurityCenterClient( + 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.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_asset_discovery), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.run_asset_discovery( + 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] + assert args[0].parent == 'parent_value' + + +@pytest.mark.asyncio +async def test_run_asset_discovery_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.run_asset_discovery( + securitycenter_service.RunAssetDiscoveryRequest(), + parent='parent_value', + ) + + +def test_set_finding_state(transport: str = 'grpc', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_set_finding_state_from_dict(): + test_set_finding_state(request_type=dict) + + +def test_set_finding_state_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 = SecurityCenterClient( + 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.set_finding_state), + '__call__') as call: + client.set_finding_state() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.set_finding_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.SetFindingStateRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_set_finding_state_async_from_dict(): + await test_set_finding_state_async(request_type=dict) + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = finding.Finding() + client.set_finding_state(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_set_finding_state_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.SetFindingStateRequest() + + request.name = 'name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + await client.set_finding_state(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_set_finding_state_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].state == finding.Finding.State.ACTIVE + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient( + 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.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_finding_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_finding_state( + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == 'name_value' + assert args[0].state == finding.Finding.State.ACTIVE + assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.set_finding_state( + securitycenter_service.SetFindingStateRequest(), + name='name_value', + state=finding.Finding.State.ACTIVE, + start_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + test_set_iam_policy(request_type=dict) + + +def test_set_iam_policy_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 = SecurityCenterClient( + 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.set_iam_policy), + '__call__') as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() + + # 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_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource='resource_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] + assert args[0].resource == 'resource_value' + + +def test_set_iam_policy_flattened_error(): + client = SecurityCenterClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource='resource_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource='resource_value', + ) + + +def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + test_test_iam_permissions(request_type=dict) + + +def test_test_iam_permissions_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 = SecurityCenterClient( + 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.test_iam_permissions), + '__call__') as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() + + # 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_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_foreign(): + client = SecurityCenterClient( + 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() + + +def test_test_iam_permissions_flattened(): + client = SecurityCenterClient( + 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_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] + assert args[0].resource == 'resource_value' + assert args[0].permissions == ['permissions_value'] + + +def test_test_iam_permissions_flattened_error(): + client = SecurityCenterClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient( + 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() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource='resource_value', + permissions=['permissions_value'], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].resource == 'resource_value' + assert args[0].permissions == ['permissions_value'] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource='resource_value', + permissions=['permissions_value'], + ) + + +def test_update_finding(transport: str = 'grpc', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + ) + response = client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +def test_update_finding_from_dict(): + test_update_finding(request_type=dict) + + +def test_update_finding_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 = SecurityCenterClient( + 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_finding), + '__call__') as call: + client.update_finding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( + name='name_value', + parent='parent_value', + resource_name='resource_name_value', + state=gcs_finding.Finding.State.ACTIVE, + category='category_value', + external_uri='external_uri_value', + severity=gcs_finding.Finding.Severity.CRITICAL, + canonical_name='canonical_name_value', + )) + response = await client.update_finding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateFindingRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_finding.Finding) + assert response.name == 'name_value' + assert response.parent == 'parent_value' + assert response.resource_name == 'resource_name_value' + assert response.state == gcs_finding.Finding.State.ACTIVE + assert response.category == 'category_value' + assert response.external_uri == 'external_uri_value' + assert response.severity == gcs_finding.Finding.Severity.CRITICAL + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_finding_async_from_dict(): + await test_update_finding_async(request_type=dict) + + +def test_update_finding_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'finding.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = gcs_finding.Finding() + client.update_finding(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', + 'finding.name=finding.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_finding_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateFindingRequest() + + request.finding.name = 'finding.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + await client.update_finding(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', + 'finding.name=finding.name/value', + ) in kw['metadata'] + + +def test_update_finding_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_finding( + finding=gcs_finding.Finding(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] + assert args[0].finding == gcs_finding.Finding(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_finding_flattened_error(): + client = SecurityCenterClient( + 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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_finding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_finding.Finding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_finding( + finding=gcs_finding.Finding(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] + assert args[0].finding == gcs_finding.Finding(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_finding_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_finding( + securitycenter_service.UpdateFindingRequest(), + finding=gcs_finding.Finding(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_notification_config(transport: str = 'grpc', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + streaming_config=gcs_notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), + ) + response = client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +def test_update_notification_config_from_dict(): + test_update_notification_config(request_type=dict) + + +def test_update_notification_config_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 = SecurityCenterClient( + 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_notification_config), + '__call__') as call: + client.update_notification_config() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( + name='name_value', + description='description_value', + event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, + pubsub_topic='pubsub_topic_value', + service_account='service_account_value', + )) + response = await client.update_notification_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_notification_config.NotificationConfig) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING + assert response.pubsub_topic == 'pubsub_topic_value' + assert response.service_account == 'service_account_value' + + +@pytest.mark.asyncio +async def test_update_notification_config_async_from_dict(): + await test_update_notification_config_async(request_type=dict) + + +def test_update_notification_config_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'notification_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = gcs_notification_config.NotificationConfig() + client.update_notification_config(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', + 'notification_config.name=notification_config.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_notification_config_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateNotificationConfigRequest() + + request.notification_config.name = 'notification_config.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + await client.update_notification_config(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', + 'notification_config.name=notification_config.name/value', + ) in kw['metadata'] + + +def test_update_notification_config_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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] + assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_notification_config_flattened_error(): + client = SecurityCenterClient( + 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_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_notification_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_notification_config.NotificationConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_notification_config( + notification_config=gcs_notification_config.NotificationConfig(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] + assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_notification_config( + securitycenter_service.UpdateNotificationConfigRequest(), + notification_config=gcs_notification_config.NotificationConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + ) + response = client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +def test_update_organization_settings_from_dict(): + test_update_organization_settings(request_type=dict) + + +def test_update_organization_settings_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 = SecurityCenterClient( + 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_organization_settings), + '__call__') as call: + client.update_organization_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( + name='name_value', + enable_asset_discovery=True, + )) + response = await client.update_organization_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_organization_settings.OrganizationSettings) + assert response.name == 'name_value' + assert response.enable_asset_discovery is True + + +@pytest.mark.asyncio +async def test_update_organization_settings_async_from_dict(): + await test_update_organization_settings_async(request_type=dict) + + +def test_update_organization_settings_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'organization_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = gcs_organization_settings.OrganizationSettings() + client.update_organization_settings(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', + 'organization_settings.name=organization_settings.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_organization_settings_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + request.organization_settings.name = 'organization_settings.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + await client.update_organization_settings(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', + 'organization_settings.name=organization_settings.name/value', + ) in kw['metadata'] + + +def test_update_organization_settings_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(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] + assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') + + +def test_update_organization_settings_flattened_error(): + client = SecurityCenterClient( + 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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_organization_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_organization_settings.OrganizationSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_organization_settings( + organization_settings=gcs_organization_settings.OrganizationSettings(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] + assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') + + +@pytest.mark.asyncio +async def test_update_organization_settings_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_organization_settings( + securitycenter_service.UpdateOrganizationSettingsRequest(), + organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), + ) + + +def test_update_source(transport: str = 'grpc', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + ) + response = client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_source_from_dict(): + test_update_source(request_type=dict) + + +def test_update_source_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 = SecurityCenterClient( + 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_source), + '__call__') as call: + client.update_source() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( + name='name_value', + display_name='display_name_value', + description='description_value', + canonical_name='canonical_name_value', + )) + response = await client.update_source(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSourceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_source.Source) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_source_async_from_dict(): + await test_update_source_async(request_type=dict) + + +def test_update_source_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'source.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = gcs_source.Source() + client.update_source(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', + 'source.name=source.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_source_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSourceRequest() + + request.source.name = 'source.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + await client.update_source(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', + 'source.name=source.name/value', + ) in kw['metadata'] + + +def test_update_source_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_source( + source=gcs_source.Source(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] + assert args[0].source == gcs_source.Source(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_source_flattened_error(): + client = SecurityCenterClient( + 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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_source), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_source.Source() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_source( + source=gcs_source.Source(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] + assert args[0].source == gcs_source.Source(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_source_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_source( + securitycenter_service.UpdateSourceRequest(), + source=gcs_source.Source(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_security_marks(transport: str = 'grpc', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + ) + response = client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +def test_update_security_marks_from_dict(): + test_update_security_marks(request_type=dict) + + +def test_update_security_marks_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 = SecurityCenterClient( + 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_security_marks), + '__call__') as call: + client.update_security_marks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( + name='name_value', + canonical_name='canonical_name_value', + )) + response = await client.update_security_marks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_security_marks.SecurityMarks) + assert response.name == 'name_value' + assert response.canonical_name == 'canonical_name_value' + + +@pytest.mark.asyncio +async def test_update_security_marks_async_from_dict(): + await test_update_security_marks_async(request_type=dict) + + +def test_update_security_marks_field_headers(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'security_marks.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = gcs_security_marks.SecurityMarks() + client.update_security_marks(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', + 'security_marks.name=security_marks.name/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_security_marks_field_headers_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = securitycenter_service.UpdateSecurityMarksRequest() + + request.security_marks.name = 'security_marks.name/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + await client.update_security_marks(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', + 'security_marks.name=security_marks.name/value', + ) in kw['metadata'] + + +def test_update_security_marks_flattened(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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] + assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +def test_update_security_marks_flattened_error(): + client = SecurityCenterClient( + 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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_security_marks), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_security_marks.SecurityMarks() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_security_marks( + security_marks=gcs_security_marks.SecurityMarks(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] + assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient( + 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_security_marks( + securitycenter_service.UpdateSecurityMarksRequest(), + security_marks=gcs_security_marks.SecurityMarks(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.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SecurityCenterClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, +]) +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 = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SecurityCenterGrpcTransport, + ) + +def test_security_center_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_security_center_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SecurityCenterTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_source', + 'create_finding', + 'create_notification_config', + 'delete_notification_config', + 'get_iam_policy', + 'get_notification_config', + 'get_organization_settings', + 'get_source', + 'group_assets', + 'group_findings', + 'list_assets', + 'list_findings', + 'list_notification_configs', + 'list_sources', + 'run_asset_discovery', + 'set_finding_state', + 'set_iam_policy', + 'test_iam_permissions', + 'update_finding', + 'update_notification_config', + 'update_organization_settings', + 'update_source', + 'update_security_marks', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +def test_security_center_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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + 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', +), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_center_base_transport_with_credentials_file_old_google_auth(): + # 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with("credentials.json", scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + ), + quota_project_id="octopus", + ) + + +def test_security_center_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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_security_center_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) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_security_center_auth_adc_old_google_auth(): + # 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) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_security_center_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',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecurityCenterGrpcTransport, + transports.SecurityCenterGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_security_center_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecurityCenterGrpcTransport, grpc_helpers), + (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_security_center_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( + "securitycenter.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=["1", "2"], + default_host="securitycenter.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_host_no_port(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), + ) + assert client.transport._host == 'securitycenter.googleapis.com:443' + + +def test_security_center_host_with_port(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), + ) + assert client.transport._host == 'securitycenter.googleapis.com:8000' + +def test_security_center_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcTransport( + 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_security_center_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SecurityCenterGrpcAsyncIOTransport( + 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) +def test_security_center_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_security_center_grpc_lro_client(): + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_security_center_grpc_lro_async_client(): + client = SecurityCenterAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_asset_path(): + organization = "squid" + asset = "clam" + expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.asset_path(organization, asset) + assert expected == actual + + +def test_parse_asset_path(): + expected = { + "organization": "whelk", + "asset": "octopus", + } + path = SecurityCenterClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_asset_path(path) + assert expected == actual + +def test_finding_path(): + organization = "oyster" + source = "nudibranch" + finding = "cuttlefish" + expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) + actual = SecurityCenterClient.finding_path(organization, source, finding) + assert expected == actual + + +def test_parse_finding_path(): + expected = { + "organization": "mussel", + "source": "winkle", + "finding": "nautilus", + } + path = SecurityCenterClient.finding_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_finding_path(path) + assert expected == actual + +def test_notification_config_path(): + organization = "scallop" + notification_config = "abalone" + expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) + actual = SecurityCenterClient.notification_config_path(organization, notification_config) + assert expected == actual + + +def test_parse_notification_config_path(): + expected = { + "organization": "squid", + "notification_config": "clam", + } + path = SecurityCenterClient.notification_config_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_notification_config_path(path) + assert expected == actual + +def test_organization_settings_path(): + organization = "whelk" + expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "octopus", + } + path = SecurityCenterClient.organization_settings_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_organization_settings_path(path) + assert expected == actual + +def test_security_marks_path(): + organization = "oyster" + asset = "nudibranch" + expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) + actual = SecurityCenterClient.security_marks_path(organization, asset) + assert expected == actual + + +def test_parse_security_marks_path(): + expected = { + "organization": "cuttlefish", + "asset": "mussel", + } + path = SecurityCenterClient.security_marks_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_security_marks_path(path) + assert expected == actual + +def test_source_path(): + organization = "winkle" + source = "nautilus" + expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) + actual = SecurityCenterClient.source_path(organization, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "organization": "scallop", + "source": "abalone", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_path(path) + assert expected == actual + +def test_topic_path(): + project = "squid" + topic = "clam" + expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) + actual = SecurityCenterClient.topic_path(project, topic) + assert expected == actual + + +def test_parse_topic_path(): + expected = { + "project": "whelk", + "topic": "octopus", + } + path = SecurityCenterClient.topic_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_topic_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SecurityCenterClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SecurityCenterClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = SecurityCenterClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SecurityCenterClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SecurityCenterClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SecurityCenterClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = SecurityCenterClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SecurityCenterClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SecurityCenterClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SecurityCenterClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + client = SecurityCenterClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: + transport_class = SecurityCenterClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) From 3c2abc1ebfa6c4c829489a4a6ebfd4ee0704243d Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 23 Jul 2021 21:00:12 +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/master/packages/owl-bot/README.md --- .../services/security_center/client.py | 4 + .../services/security_center/client.py | 4 + .../services/security_center/client.py | 4 + 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 - .../securitycenter_v1/security_center.rst | 10 - .../v1/docs/securitycenter_v1/services.rst | 6 - .../v1/docs/securitycenter_v1/types.rst | 7 - .../google/cloud/securitycenter/__init__.py | 97 - .../v1/google/cloud/securitycenter/py.typed | 2 - .../cloud/securitycenter_v1/__init__.py | 98 - .../securitycenter_v1/gapic_metadata.json | 253 - .../google/cloud/securitycenter_v1/py.typed | 2 - .../securitycenter_v1/services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 2340 ----- .../services/security_center/client.py | 2510 ------ .../services/security_center/pagers.py | 752 -- .../security_center/transports/__init__.py | 33 - .../security_center/transports/base.py | 572 -- .../security_center/transports/grpc.py | 876 -- .../transports/grpc_asyncio.py | 880 -- .../cloud/securitycenter_v1/types/__init__.py | 114 - .../cloud/securitycenter_v1/types/asset.py | 223 - .../cloud/securitycenter_v1/types/finding.py | 178 - .../cloud/securitycenter_v1/types/folder.py | 50 - .../types/notification_config.py | 115 - .../types/notification_message.py | 61 - .../types/organization_settings.py | 104 - .../cloud/securitycenter_v1/types/resource.py | 80 - .../types/run_asset_discovery_response.py | 57 - .../securitycenter_v1/types/security_marks.py | 76 - .../types/securitycenter_service.py | 1611 ---- .../cloud/securitycenter_v1/types/source.py | 83 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../fixup_securitycenter_v1_keywords.py | 198 - owl-bot-staging/v1/setup.py | 54 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/securitycenter_v1/__init__.py | 16 - .../securitycenter_v1/test_security_center.py | 7619 ---------------- owl-bot-staging/v1beta1/.coveragerc | 17 - owl-bot-staging/v1beta1/MANIFEST.in | 2 - owl-bot-staging/v1beta1/README.rst | 49 - owl-bot-staging/v1beta1/docs/conf.py | 376 - owl-bot-staging/v1beta1/docs/index.rst | 7 - .../security_center.rst | 10 - .../docs/securitycenter_v1beta1/services.rst | 6 - .../docs/securitycenter_v1beta1/types.rst | 7 - .../google/cloud/securitycenter/__init__.py | 77 - .../google/cloud/securitycenter/py.typed | 2 - .../cloud/securitycenter_v1beta1/__init__.py | 78 - .../gapic_metadata.json | 203 - .../cloud/securitycenter_v1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 1886 ---- .../services/security_center/client.py | 2052 ----- .../services/security_center/pagers.py | 630 -- .../security_center/transports/__init__.py | 33 - .../security_center/transports/base.py | 485 - .../security_center/transports/grpc.py | 742 -- .../transports/grpc_asyncio.py | 746 -- .../securitycenter_v1beta1/types/__init__.py | 86 - .../securitycenter_v1beta1/types/asset.py | 151 - .../securitycenter_v1beta1/types/finding.py | 148 - .../types/organization_settings.py | 96 - .../types/run_asset_discovery_response.py | 57 - .../types/security_marks.py | 64 - .../types/securitycenter_service.py | 1016 --- .../securitycenter_v1beta1/types/source.py | 72 - owl-bot-staging/v1beta1/mypy.ini | 3 - owl-bot-staging/v1beta1/noxfile.py | 132 - .../fixup_securitycenter_v1beta1_keywords.py | 193 - owl-bot-staging/v1beta1/setup.py | 54 - owl-bot-staging/v1beta1/tests/__init__.py | 16 - .../v1beta1/tests/unit/__init__.py | 16 - .../v1beta1/tests/unit/gapic/__init__.py | 16 - .../gapic/securitycenter_v1beta1/__init__.py | 16 - .../test_security_center.py | 6133 ------------- owl-bot-staging/v1p1beta1/.coveragerc | 17 - owl-bot-staging/v1p1beta1/MANIFEST.in | 2 - owl-bot-staging/v1p1beta1/README.rst | 49 - owl-bot-staging/v1p1beta1/docs/conf.py | 376 - owl-bot-staging/v1p1beta1/docs/index.rst | 7 - .../security_center.rst | 10 - .../securitycenter_v1p1beta1/services.rst | 6 - .../docs/securitycenter_v1p1beta1/types.rst | 7 - .../google/cloud/securitycenter/__init__.py | 97 - .../google/cloud/securitycenter/py.typed | 2 - .../securitycenter_v1p1beta1/__init__.py | 98 - .../gapic_metadata.json | 253 - .../cloud/securitycenter_v1p1beta1/py.typed | 2 - .../services/__init__.py | 15 - .../services/security_center/__init__.py | 22 - .../services/security_center/async_client.py | 2432 ----- .../services/security_center/client.py | 2600 ------ .../services/security_center/pagers.py | 752 -- .../security_center/transports/__init__.py | 33 - .../security_center/transports/base.py | 572 -- .../security_center/transports/grpc.py | 877 -- .../transports/grpc_asyncio.py | 881 -- .../types/__init__.py | 114 - .../securitycenter_v1p1beta1/types/asset.py | 223 - .../securitycenter_v1p1beta1/types/finding.py | 180 - .../securitycenter_v1p1beta1/types/folder.py | 50 - .../types/notification_config.py | 126 - .../types/notification_message.py | 60 - .../types/organization_settings.py | 104 - .../types/resource.py | 80 - .../types/run_asset_discovery_response.py | 57 - .../types/security_marks.py | 76 - .../types/securitycenter_service.py | 1581 ---- .../securitycenter_v1p1beta1/types/source.py | 83 - owl-bot-staging/v1p1beta1/mypy.ini | 3 - owl-bot-staging/v1p1beta1/noxfile.py | 132 - ...fixup_securitycenter_v1p1beta1_keywords.py | 198 - owl-bot-staging/v1p1beta1/setup.py | 54 - owl-bot-staging/v1p1beta1/tests/__init__.py | 16 - .../v1p1beta1/tests/unit/__init__.py | 16 - .../v1p1beta1/tests/unit/gapic/__init__.py | 16 - .../securitycenter_v1p1beta1/__init__.py | 16 - .../test_security_center.py | 7809 ----------------- .../securitycenter_v1/test_security_center.py | 31 +- .../test_security_center.py | 31 +- .../test_security_center.py | 31 +- 131 files changed, 66 insertions(+), 55607 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/docs/securitycenter_v1/security_center.rst delete mode 100644 owl-bot-staging/v1/docs/securitycenter_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/securitycenter_v1/types.rst delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/asset.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/finding.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/folder.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_config.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_message.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/organization_settings.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/resource.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/security_marks.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/v1/google/cloud/securitycenter_v1/types/source.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_securitycenter_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/securitycenter_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py delete mode 100644 owl-bot-staging/v1beta1/.coveragerc delete mode 100644 owl-bot-staging/v1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1beta1/README.rst delete mode 100644 owl-bot-staging/v1beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/security_center.rst delete mode 100644 owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/services.rst delete mode 100644 owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/types.rst delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/py.typed delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py delete mode 100644 owl-bot-staging/v1beta1/mypy.ini delete mode 100644 owl-bot-staging/v1beta1/noxfile.py delete mode 100644 owl-bot-staging/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py delete mode 100644 owl-bot-staging/v1beta1/setup.py delete mode 100644 owl-bot-staging/v1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py delete mode 100644 owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py delete mode 100644 owl-bot-staging/v1p1beta1/.coveragerc delete mode 100644 owl-bot-staging/v1p1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1p1beta1/README.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1p1beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/services.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/types.rst delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter/py.typed delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py delete mode 100644 owl-bot-staging/v1p1beta1/mypy.ini delete mode 100644 owl-bot-staging/v1p1beta1/noxfile.py delete mode 100644 owl-bot-staging/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py delete mode 100644 owl-bot-staging/v1p1beta1/setup.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py diff --git a/google/cloud/securitycenter_v1/services/security_center/client.py b/google/cloud/securitycenter_v1/services/security_center/client.py index 3288415e..c7546fa6 100644 --- a/google/cloud/securitycenter_v1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1/services/security_center/client.py @@ -454,6 +454,10 @@ def __init__( 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=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def create_source( diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1beta1/services/security_center/client.py index 2dca887d..312e0ecf 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -423,6 +423,10 @@ def __init__( 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=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def create_source( diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py index 9604557d..0aa897ac 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -456,6 +456,10 @@ def __init__( 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=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), ) def create_source( diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 3655af7f..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__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 a18e3d0b..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index f8c63f4c..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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 f4837604..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-securitycenter documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-securitycenter" -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-securitycenter-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-securitycenter.tex", - u"google-cloud-securitycenter Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-securitycenter", - u"Google Cloud Securitycenter Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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 47fc2db7..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1/services - securitycenter_v1/types diff --git a/owl-bot-staging/v1/docs/securitycenter_v1/security_center.rst b/owl-bot-staging/v1/docs/securitycenter_v1/security_center.rst deleted file mode 100644 index bc6175c8..00000000 --- a/owl-bot-staging/v1/docs/securitycenter_v1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/securitycenter_v1/services.rst b/owl-bot-staging/v1/docs/securitycenter_v1/services.rst deleted file mode 100644 index 295acede..00000000 --- a/owl-bot-staging/v1/docs/securitycenter_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1 API -=============================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/v1/docs/securitycenter_v1/types.rst b/owl-bot-staging/v1/docs/securitycenter_v1/types.rst deleted file mode 100644 index 460aec08..00000000 --- a/owl-bot-staging/v1/docs/securitycenter_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Securitycenter v1 API -============================================ - -.. automodule:: google.cloud.securitycenter_v1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index 2626e614..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter/__init__.py +++ /dev/null @@ -1,97 +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.securitycenter_v1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1.types.asset import Asset -from google.cloud.securitycenter_v1.types.finding import Finding -from google.cloud.securitycenter_v1.types.folder import Folder -from google.cloud.securitycenter_v1.types.notification_config import NotificationConfig -from google.cloud.securitycenter_v1.types.notification_message import NotificationMessage -from google.cloud.securitycenter_v1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1.types.resource import Resource -from google.cloud.securitycenter_v1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import DeleteNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListNotificationConfigsResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateNotificationConfigRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1.types.source import Source - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Asset', - 'Finding', - 'Folder', - 'NotificationConfig', - 'NotificationMessage', - 'OrganizationSettings', - 'Resource', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter/py.typed b/owl-bot-staging/v1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/__init__.py deleted file mode 100644 index ca8f63fd..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/__init__.py +++ /dev/null @@ -1,98 +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.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.asset import Asset -from .types.finding import Finding -from .types.folder import Folder -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.organization_settings import OrganizationSettings -from .types.resource import Resource -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source - -__all__ = ( - 'SecurityCenterAsyncClient', -'Asset', -'CreateFindingRequest', -'CreateNotificationConfigRequest', -'CreateSourceRequest', -'DeleteNotificationConfigRequest', -'Finding', -'Folder', -'GetNotificationConfigRequest', -'GetOrganizationSettingsRequest', -'GetSourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListNotificationConfigsRequest', -'ListNotificationConfigsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'NotificationConfig', -'NotificationMessage', -'OrganizationSettings', -'Resource', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityCenterClient', -'SecurityMarks', -'SetFindingStateRequest', -'Source', -'UpdateFindingRequest', -'UpdateNotificationConfigRequest', -'UpdateOrganizationSettingsRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/securitycenter_v1/gapic_metadata.json deleted file mode 100644 index e3afaeec..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/gapic_metadata.json +++ /dev/null @@ -1,253 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1", - "protoPackage": "google.cloud.securitycenter.v1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/py.typed b/owl-bot-staging/v1/google/cloud/securitycenter_v1/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_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/securitycenter_v1/services/security_center/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/__init__.py deleted file mode 100644 index fce6b0c5..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py deleted file mode 100644 index d5d056ed..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ /dev/null @@ -1,2340 +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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1 APIs for Security Center service.""" - - _client: SecurityCenterClient - - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) - parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - topic_path = staticmethod(SecurityCenterClient.topic_path) - parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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, ~.SecurityCenterTransport]): 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_source(self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``source`` 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.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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 = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # 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_source, - 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_finding(self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` 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.securitycenter_v1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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 = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # 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_finding, - 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_notification_config(self, - request: securitycenter_service.CreateNotificationConfigRequest = None, - *, - parent: str = None, - config_id: str = None, - notification_config: gcs_notification_config.NotificationConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest`): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters, and - contains alphanumeric characters, - underscores or hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_config`` 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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_config]) - 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 = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # 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_notification_config, - 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 delete_notification_config(self, - request: securitycenter_service.DeleteNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a notification config. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest`): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.DeleteNotificationConfigRequest(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.delete_notification_config, - 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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_iam_policy(self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # 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_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(( - ("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_notification_config(self, - request: securitycenter_service.GetNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.GetNotificationConfigRequest`): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - - 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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.GetNotificationConfigRequest(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_notification_config, - 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_organization_settings(self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - 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.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings, - 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_source(self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - - 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.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.GetSourceRequest(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_source, - 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 group_assets(self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(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.group_assets, - 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=480.0, - ), - default_timeout=480.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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Args: - request (:class:`google.cloud.securitycenter_v1.types.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` 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.securitycenter_v1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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 = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_findings, - 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=480.0, - ), - default_timeout=480.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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: securitycenter_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.ListAssetsRequest`): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = securitycenter_service.ListAssetsRequest(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.list_assets, - 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=480.0, - ), - default_timeout=480.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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: securitycenter_service.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`google.cloud.securitycenter_v1.types.ListFindingsRequest`): - The request object. Request message for listing - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = securitycenter_service.ListFindingsRequest(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.list_findings, - 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=480.0, - ), - default_timeout=480.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.ListFindingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notification_configs(self, - request: securitycenter_service.ListNotificationConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest`): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - - 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs, - 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.ListNotificationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id], folders/[folder_id], - or projects/[project_id]". - - 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.securitycenter_v1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.ListSourcesRequest(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_sources, - 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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp_pb2.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` 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.securitycenter_v1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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 = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # 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_finding_state, - 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 set_iam_policy(self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # 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=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(( - ("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, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # 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_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(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_finding(self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` 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.securitycenter_v1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - 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 = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # 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_finding, - 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(( - ("finding.name", request.finding.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_notification_config(self, - request: securitycenter_service.UpdateNotificationConfigRequest = None, - *, - notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Args: - request (:class:`google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest`): - The request object. Request message for updating a - notification config. - notification_config (:class:`google.cloud.securitycenter_v1.types.NotificationConfig`): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields will be - updated. - - 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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([notification_config, 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 = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_config - 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_notification_config, - 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(( - ("notification_config.name", request.notification_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_organization_settings(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` 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.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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 = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # 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_organization_settings, - 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(( - ("organization_settings.name", request.organization_settings.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_source(self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``source`` 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.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source]) - 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 = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # 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_source, - 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(( - ("source.name", request.source.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_security_marks(self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` 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.securitycenter_v1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - 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 = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # 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_security_marks, - default_timeout=480.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(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Send the request. - response = await 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-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/client.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/client.py deleted file mode 100644 index bdcd1cca..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/client.py +++ /dev/null @@ -1,2510 +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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1 APIs for Security Center service.""" - - @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 = "securitycenter.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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str,notification_config: str,) -> str: - """Returns a fully-qualified notification_config string.""" - return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str,str]: - """Parses a notification_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SecurityCenterTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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, SecurityCenterTransport]): 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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, SecurityCenterTransport): - # transport is a SecurityCenterTransport instance. - if credentials or client_options.credentials_file: - 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: - 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=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def create_source(self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (google.cloud.securitycenter_v1.types.CreateSourceRequest): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``source`` 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.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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 securitycenter_service.CreateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_source] - - # 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_finding(self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (google.cloud.securitycenter_v1.types.CreateFindingRequest): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` 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.securitycenter_v1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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 securitycenter_service.CreateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # 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_notification_config(self, - request: securitycenter_service.CreateNotificationConfigRequest = None, - *, - parent: str = None, - config_id: str = None, - notification_config: gcs_notification_config.NotificationConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - Args: - request (google.cloud.securitycenter_v1.types.CreateNotificationConfigRequest): - The request object. Request message for creating a - notification config. - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters, and - contains alphanumeric characters, - underscores or hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_config`` 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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_config]) - 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 securitycenter_service.CreateNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_config] - - # 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 delete_notification_config(self, - request: securitycenter_service.DeleteNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a notification config. - - Args: - request (google.cloud.securitycenter_v1.types.DeleteNotificationConfigRequest): - The request object. Request message for deleting a - notification config. - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.DeleteNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(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.delete_notification_config] - - # 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. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_iam_policy(self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): - The request object. Request message for `GetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_notification_config(self, - request: securitycenter_service.GetNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - Args: - request (google.cloud.securitycenter_v1.types.GetNotificationConfigRequest): - The request object. Request message for getting a - notification config. - name (str): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - - 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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(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_notification_config] - - # 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_organization_settings(self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (google.cloud.securitycenter_v1.types.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - 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.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings] - - # 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_source(self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (google.cloud.securitycenter_v1.types.GetSourceRequest): - The request object. Request message for getting a - source. - name (str): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - - 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.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(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_source] - - # 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 group_assets(self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (google.cloud.securitycenter_v1.types.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # 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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Args: - request (google.cloud.securitycenter_v1.types.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` 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.securitycenter_v1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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 securitycenter_service.GroupFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_findings] - - # 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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: securitycenter_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - Args: - request (google.cloud.securitycenter_v1.types.ListAssetsRequest): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # 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.ListAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: securitycenter_service.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Args: - request (google.cloud.securitycenter_v1.types.ListFindingsRequest): - The request object. Request message for listing - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_findings] - - # 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.ListFindingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notification_configs(self, - request: securitycenter_service.ListNotificationConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotificationConfigsPager: - r"""Lists notification configs. - - Args: - request (google.cloud.securitycenter_v1.types.ListNotificationConfigsRequest): - The request object. Request message for listing - notification configs. - parent (str): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - - 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.securitycenter_v1.services.security_center.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListNotificationConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs] - - # 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.ListNotificationConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - Args: - request (google.cloud.securitycenter_v1.types.ListSourcesRequest): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id], folders/[folder_id], - or projects/[project_id]". - - 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.securitycenter_v1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListSourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(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_sources] - - # 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.ListSourcesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (google.cloud.securitycenter_v1.types.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.RunAssetDiscoveryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp_pb2.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (google.cloud.securitycenter_v1.types.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - name (str): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` 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.securitycenter_v1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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 securitycenter_service.SetFindingStateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_state] - - # 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 set_iam_policy(self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): - The request object. Request message for `SetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # 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, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): - The request object. Request message for - `TestIamPermissions` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (Sequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_finding(self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (google.cloud.securitycenter_v1.types.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` 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.securitycenter_v1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - 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 securitycenter_service.UpdateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_notification_config(self, - request: securitycenter_service.UpdateNotificationConfigRequest = None, - *, - notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Args: - request (google.cloud.securitycenter_v1.types.UpdateNotificationConfigRequest): - The request object. Request message for updating a - notification config. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the notification config. - If empty all mutable fields will be - updated. - - 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.securitycenter_v1.types.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([notification_config, 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 securitycenter_service.UpdateNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_config - 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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_organization_settings(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (google.cloud.securitycenter_v1.types.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` 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.securitycenter_v1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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 securitycenter_service.UpdateOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_settings.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_source(self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (google.cloud.securitycenter_v1.types.UpdateSourceRequest): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``source`` 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.securitycenter_v1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source]) - 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 securitycenter_service.UpdateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.source.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_security_marks(self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (google.cloud.securitycenter_v1.types.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` 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.securitycenter_v1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - 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 securitycenter_service.UpdateSecurityMarksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # 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-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py deleted file mode 100644 index bef157b5..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/pagers.py +++ /dev/null @@ -1,752 +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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` - 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[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: - 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) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupAssetsResponse` - 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: - 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) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` - 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[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: - 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) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.GroupFindingsResponse` - 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: - 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) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` - 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[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: - 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) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListAssetsResponse` - 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: - 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) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` - 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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - 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.securitycenter_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListFindingsResponse): - 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 = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: - 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) -> Iterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListFindingsResponse` - 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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - 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.securitycenter_v1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListFindingsResponse): - 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 = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: - 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) -> AsyncIterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` - 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[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListNotificationConfigsResponse]: - 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) -> Iterable[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse` - 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[securitycenter_service.ListNotificationConfigsResponse]], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListNotificationConfigsResponse]: - 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) -> AsyncIterable[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` - 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[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: - 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) -> Iterable[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1.types.ListSourcesResponse` - 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: - 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) -> AsyncIterable[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - 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/securitycenter_v1/services/security_center/transports/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py deleted file mode 100644 index 8bdaf713..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py deleted file mode 100644 index 3e6da749..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ /dev/null @@ -1,572 +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 packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-securitycenter', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.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 = self._get_scopes_kwargs(self._host, 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 is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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_notification_config: gapic_v1.method.wrap_method( - self.get_notification_config, - 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_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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_source: gapic_v1.method.wrap_method( - self.get_source, - 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.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_findings, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_configs, - 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_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - 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 get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Union[ - notification_config.NotificationConfig, - Awaitable[notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Union[ - securitycenter_service.ListNotificationConfigsResponse, - Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py deleted file mode 100644 index fc23cf67..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,876 +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 # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # 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 - -import grpc # type: ignore - -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1 APIs for Security Center service. - - 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 = 'securitycenter.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 applicatin 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 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 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] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'securitycenter.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 operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_notification_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index b1461886..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,880 +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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1 APIs for Security Center service. - - 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 = 'securitycenter.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 = 'securitycenter.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 applicatin 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 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 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] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_notification_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig]]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/__init__.py deleted file mode 100644 index f490e7f6..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/__init__.py +++ /dev/null @@ -1,114 +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 .asset import ( - Asset, -) -from .finding import ( - Finding, -) -from .folder import ( - Folder, -) -from .notification_config import ( - NotificationConfig, -) -from .notification_message import ( - NotificationMessage, -) -from .organization_settings import ( - OrganizationSettings, -) -from .resource import ( - Resource, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_marks import ( - SecurityMarks, -) -from .securitycenter_service import ( - CreateFindingRequest, - CreateNotificationConfigRequest, - CreateSourceRequest, - DeleteNotificationConfigRequest, - GetNotificationConfigRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - UpdateFindingRequest, - UpdateNotificationConfigRequest, - UpdateOrganizationSettingsRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .source import ( - Source, -) - -__all__ = ( - 'Asset', - 'Finding', - 'Folder', - 'NotificationConfig', - 'NotificationMessage', - 'OrganizationSettings', - 'Resource', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/asset.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/asset.py deleted file mode 100644 index 2552d58f..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/asset.py +++ /dev/null @@ -1,223 +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.securitycenter_v1.types import folder -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (Sequence[google.cloud.securitycenter_v1.types.Asset.ResourcePropertiesEntry]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated - or added in Cloud SCC. - iam_policy (google.cloud.securitycenter_v1.types.Asset.IamPolicy): - Cloud IAM Policy information associated with - the Google Cloud resource described by the - Security Command Center asset. This information - is managed and defined by the Google Cloud - resource and cannot be modified by the user. - canonical_name (str): - The canonical name of the resource. It's either - "organizations/{organization_id}/assets/{asset_id}", - "folders/{folder_id}/assets/{asset_id}" or - "projects/{project_number}/assets/{asset_id}", depending on - the closest CRM ancestor of the resource. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - The full resource name of the Google Cloud resource this - asset represents. This field is immutable after create time. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (Sequence[str]): - Owners of the Google Cloud resource. - resource_display_name (str): - The user defined display name for this - resource. - resource_parent_display_name (str): - The user defined display name for the parent - of this resource. - resource_project_display_name (str): - The user defined display name for the project - of this resource. - folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - resource_name = proto.Field( - proto.STRING, - number=1, - ) - resource_type = proto.Field( - proto.STRING, - number=2, - ) - resource_parent = proto.Field( - proto.STRING, - number=3, - ) - resource_project = proto.Field( - proto.STRING, - number=4, - ) - resource_owners = proto.RepeatedField( - proto.STRING, - number=5, - ) - resource_display_name = proto.Field( - proto.STRING, - number=6, - ) - resource_parent_display_name = proto.Field( - proto.STRING, - number=7, - ) - resource_project_display_name = proto.Field( - proto.STRING, - number=8, - ) - folders = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - class IamPolicy(proto.Message): - r"""Cloud IAM Policy information associated with the Google Cloud - resource described by the Security Command Center asset. This - information is managed and defined by the Google Cloud resource - and cannot be modified by the user. - - Attributes: - policy_blob (str): - The JSON representation of the Policy - associated with the asset. See - https://cloud.google.com/iam/reference/rest/v1/Policy - for format details. - """ - - policy_blob = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - iam_policy = proto.Field( - proto.MESSAGE, - number=11, - message=IamPolicy, - ) - canonical_name = proto.Field( - proto.STRING, - number=13, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/finding.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/finding.py deleted file mode 100644 index 7d29c2f4..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/finding.py +++ /dev/null @@ -1,178 +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.securitycenter_v1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - A finding is a record of assessment data like security, risk, - health, or privacy, that is ingested into Security Command - Center for presentation, notification, analysis, policy testing, - and enforcement. For example, a cross-site scripting (XSS) - vulnerability in an App Engine application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (Sequence[google.cloud.securitycenter_v1.types.Finding.SourcePropertiesEntry]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the event took place, or - when an update to the finding occurred. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. If the finding - were to be resolved afterward, this time would - reflect when the finding was resolved. Must not - be set to a value greater than the current - timestamp. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - severity (google.cloud.securitycenter_v1.types.Finding.Severity): - The severity of the finding. This field is - managed by the source that writes the finding. - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" - or - "projects/{project_number}/sources/{source_id}/findings/{finding_id}", - depending on the closest CRM ancestor of the resource - associated with the finding. - """ - class State(proto.Enum): - r"""The state of the finding.""" - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class Severity(proto.Enum): - r"""The severity of the finding.""" - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - name = proto.Field( - proto.STRING, - number=1, - ) - parent = proto.Field( - proto.STRING, - number=2, - ) - resource_name = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category = proto.Field( - proto.STRING, - number=5, - ) - external_uri = proto.Field( - proto.STRING, - number=6, - ) - source_properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - severity = proto.Field( - proto.ENUM, - number=12, - enum=Severity, - ) - canonical_name = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/folder.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/folder.py deleted file mode 100644 index bca1c34f..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/folder.py +++ /dev/null @@ -1,50 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Folder', - }, -) - - -class Folder(proto.Message): - r"""Message that contains the resource name and display name of a - folder resource. - - Attributes: - resource_folder (str): - Full resource name of this folder. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_folder_display_name (str): - The user defined display name for this - folder. - """ - - resource_folder = proto.Field( - proto.STRING, - number=1, - ) - resource_folder_display_name = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_config.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_config.py deleted file mode 100644 index c4d0175f..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_config.py +++ /dev/null @@ -1,115 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'NotificationConfig', - }, -) - - -class NotificationConfig(proto.Message): - r"""Cloud Security Command Center (Cloud SCC) notification - configs. - A notification config is a Cloud SCC resource that contains the - configuration to send notifications for create/update events of - findings, assets and etc. - - Attributes: - name (str): - The relative resource name of this notification config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/notificationConfigs/notify_public_bucket". - description (str): - The description of the notification config - (max of 1024 characters). - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (google.cloud.securitycenter_v1.types.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - """ - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - pubsub_topic = proto.Field( - proto.STRING, - number=3, - ) - service_account = proto.Field( - proto.STRING, - number=4, - ) - streaming_config = proto.Field( - proto.MESSAGE, - number=5, - oneof='notify_config', - message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_message.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_message.py deleted file mode 100644 index b5b4b34e..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/notification_message.py +++ /dev/null @@ -1,61 +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.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'NotificationMessage', - }, -) - - -class NotificationMessage(proto.Message): - r"""Cloud SCC's Notification - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (google.cloud.securitycenter_v1.types.Finding): - If it's a Finding based notification config, - this field will be populated. - resource (google.cloud.securitycenter_v1.types.Resource): - The Cloud resource tied to this - notification's Finding. - """ - - notification_config_name = proto.Field( - proto.STRING, - number=1, - ) - finding = proto.Field( - proto.MESSAGE, - number=2, - oneof='event', - message=gcs_finding.Finding, - ) - resource = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_resource.Resource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/organization_settings.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/organization_settings.py deleted file mode 100644 index f9e655a0..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/organization_settings.py +++ /dev/null @@ -1,104 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - Attributes: - project_ids (Sequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - folder_ids (Sequence[str]): - The folder ids to use for filtering asset - discovery. It consists of only digits, e.g., - 756619654966. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - folder_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/resource.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/resource.py deleted file mode 100644 index 46aeddd8..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/resource.py +++ /dev/null @@ -1,80 +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.securitycenter_v1.types import folder - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Resource', - }, -) - - -class Resource(proto.Message): - r"""Information related to the Google Cloud resource. - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): - Output only. Contains a Folder message for - each folder in the assets ancestry. The first - folder is the deepest nested folder, and the - last folder is the folder directly under the - Organization. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - project = proto.Field( - proto.STRING, - number=2, - ) - project_display_name = proto.Field( - proto.STRING, - number=3, - ) - parent = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name = proto.Field( - proto.STRING, - number=5, - ) - folders = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py deleted file mode 100644 index 9abefa4d..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py +++ /dev/null @@ -1,57 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - Attributes: - state (google.cloud.securitycenter_v1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run.""" - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/security_marks.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/security_marks.py deleted file mode 100644 index 34b696c4..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/security_marks.py +++ /dev/null @@ -1,76 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[google.cloud.securitycenter_v1.types.SecurityMarks.MarksEntry]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - canonical_name (str): - The canonical name of the marks. Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "folders/{folder_id}/assets/{asset_id}/securityMarks" - "projects/{project_number}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - marks = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - canonical_name = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py deleted file mode 100644 index 6543ec9b..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/securitycenter_service.py +++ /dev/null @@ -1,1611 +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.securitycenter_v1.types import asset as gcs_asset -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import folder -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'RunAssetDiscoveryRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - finding_id = proto.Field( - proto.STRING, - number=2, - ) - finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - config_id (str): - Required. - Unique identifier provided by the client within - the parent scope. It must be between 1 and 128 - characters, and contains alphanumeric - characters, underscores or hyphens only. - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - config_id = proto.Field( - proto.STRING, - number=2, - ) - notification_config = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_notification_config.NotificationConfig, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (google.cloud.securitycenter_v1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - Attributes: - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - Attributes: - name (str): - Required. Name of the notification config to get. Its format - is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id], folders/[folder_id], or - projects/[project_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" property is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - group_by = proto.Field( - proto.STRING, - number=3, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token = proto.Field( - proto.STRING, - number=7, - ) - page_size = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - Attributes: - group_by_results (Sequence[google.cloud.securitycenter_v1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - workflow_state: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based - on a property existing: - ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state_change``). The string value - should follow SQL syntax: comma separated list of fields. - For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration is - set: - - - state_change - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - group_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - page_token = proto.Field( - proto.STRING, - number=7, - ) - page_size = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - Attributes: - group_by_results (Sequence[google.cloud.securitycenter_v1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (Sequence[google.cloud.securitycenter_v1.types.GroupResult.PropertiesEntry]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count = proto.Field( - proto.INT64, - number=2, - ) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - Attributes: - parent (str): - Required. Name of the organization to list notification - configs. Its format is "organizations/[organization_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - Attributes: - notification_configs (Sequence[google.cloud.securitycenter_v1.types.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - Attributes: - sources (Sequence[google.cloud.securitycenter_v1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following are the allowed field and operator - combinations: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - - The following fields are supported: name update_time - resource_properties security_marks.marks - security_center_properties.resource_name - security_center_properties.resource_display_name - security_center_properties.resource_parent - security_center_properties.resource_parent_display_name - security_center_properties.resource_project - security_center_properties.resource_project_display_name - security_center_properties.resource_type - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetsResult's - "state_change" attribute is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the ListAssetsResult - fields to be listed in the response. - An empty field mask will list all fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - order_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - page_size = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - Attributes: - list_assets_results (Sequence[google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - Attributes: - asset (google.cloud.securitycenter_v1.types.Asset): - Asset matching the search request. - state_change (google.cloud.securitycenter_v1.types.ListAssetsResponse.ListAssetsResult.StateChange): - State change of the asset between the points - in time. - """ - class StateChange(proto.Enum): - r"""The change in state of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state change will be: - UNUSED - """ - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state_change = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.StateChange', - ) - - @property - def raw_page(self): - return self - - list_assets_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - severity: ``=``, ``:`` - - - workflow_state: ``=``, ``:`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based - on a property existing: - ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - - - resource: - - - resource.name: ``=``, ``:`` - - resource.parent_name: ``=``, ``:`` - - resource.parent_display_name: ``=``, ``:`` - - resource.project_name: ``=``, ``:`` - - resource.project_display_name: ``=``, ``:`` - - resource.type: ``=``, ``:`` - - resource.folders.resource_folder: ``=``, ``:`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time source_properties - security_marks.marks - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListFindingsResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added in any state during - the compare_duration period of time that precedes the - read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the Finding fields to - be listed in the response. An empty field mask - will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - order_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - page_size = proto.Field( - proto.INT32, - number=9, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - Attributes: - list_findings_results (Sequence[google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding and its StateChange. - Attributes: - finding (google.cloud.securitycenter_v1.types.Finding): - Finding matching the search request. - state_change (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.StateChange): - State change of the finding between the - points in time. - resource (google.cloud.securitycenter_v1.types.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - class StateChange(proto.Enum): - r"""The change in state of the finding. - - When querying across two points in time this describes the change in - the finding between the two points: CHANGED, UNCHANGED, ADDED, or - REMOVED. Findings can not be deleted, so REMOVED implies that the - finding at timestamp does not match the filter specified, but it did - at timestamp - compare_duration. If there was no compare_duration - supplied in the request the state change will be: UNUSED - """ - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project_name (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent_name (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (Sequence[google.cloud.securitycenter_v1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - project_name = proto.Field( - proto.STRING, - number=2, - ) - project_display_name = proto.Field( - proto.STRING, - number=3, - ) - parent_name = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name = proto.Field( - proto.STRING, - number=5, - ) - folders = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - - finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - state_change = proto.Field( - proto.ENUM, - number=2, - enum='ListFindingsResponse.ListFindingsResult.StateChange', - ) - resource = proto.Field( - proto.MESSAGE, - number=3, - message='ListFindingsResponse.ListFindingsResult.Resource', - ) - - @property - def raw_page(self): - return self - - list_findings_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListFindingsResult, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (google.cloud.securitycenter_v1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - state = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - Attributes: - finding (google.cloud.securitycenter_v1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - Attributes: - notification_config (google.cloud.securitycenter_v1.types.NotificationConfig): - Required. The notification config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - Attributes: - organization_settings (google.cloud.securitycenter_v1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - If empty all mutable fields will be updated. - """ - - organization_settings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - Attributes: - source (google.cloud.securitycenter_v1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - Attributes: - security_marks (google.cloud.securitycenter_v1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. If not set uses current server - time. Updates will be applied to the - SecurityMarks that are active immediately - preceding this time. - """ - - security_marks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/source.py b/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/source.py deleted file mode 100644 index f738daab..00000000 --- a/owl-bot-staging/v1/google/cloud/securitycenter_v1/types/source.py +++ /dev/null @@ -1,83 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, and other tools. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and outdated or - insecure libraries.". - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}" or - "projects/{project_number}/sources/{source_id}", depending - on the closest CRM ancestor of the resource associated with - the finding. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - canonical_name = proto.Field( - proto.STRING, - number=14, - ) - - -__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 07aa30ac..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']) -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/securitycenter_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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']) -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.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1/scripts/fixup_securitycenter_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_securitycenter_v1_keywords.py deleted file mode 100644 index 43acd75e..00000000 --- a/owl-bot-staging/v1/scripts/fixup_securitycenter_v1_keywords.py +++ /dev/null @@ -1,198 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_source': ('parent', 'source', ), - 'delete_notification_config': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_notification_config': ('name', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('source', 'update_mask', ), - } - - 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: not a.keyword.value 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=securitycenterCallTransformer(), -): - """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 securitycenter 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 0653f115..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,54 +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-securitycenter', - 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.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', '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/securitycenter_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/securitycenter_v1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/securitycenter_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/securitycenter_v1/test_security_center.py b/owl-bot-staging/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py deleted file mode 100644 index e397902d..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ /dev/null @@ -1,7619 +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 packaging.version - -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 future -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 operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.securitycenter_v1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.services.security_center import transports -from google.cloud.securitycenter_v1.services.security_center.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -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.longrunning import operations_pb2 -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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - SecurityCenterClient, - SecurityCenterAsyncClient, -]) -def test_security_center_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 == 'securitycenter.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_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", [ - SecurityCenterClient, - SecurityCenterAsyncClient, -]) -def test_security_center_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 == 'securitycenter.googleapis.com:443' - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_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(SecurityCenterClient, '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(SecurityCenterClient, '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(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() - 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() - 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() - - # 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() - - # 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) - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_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) - - 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() - 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() - 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,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_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) - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - 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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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, - ) - - -def test_create_source(transport: str = 'grpc', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_create_source_from_dict(): - test_create_source(request_type=dict) - - -def test_create_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_source(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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_source(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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.Source(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] - assert args[0].parent == 'parent_value' - assert args[0].source == gcs_source.Source(name='name_value') - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.Source(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] - assert args[0].parent == 'parent_value' - assert args[0].source == gcs_source.Source(name='name_value') - - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_finding(transport: str = 'grpc', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_create_finding_from_dict(): - test_create_finding(request_type=dict) - - -def test_create_finding_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 = SecurityCenterClient( - 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_finding), - '__call__') as call: - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_finding(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_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_finding(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_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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] - assert args[0].parent == 'parent_value' - assert args[0].finding_id == 'finding_id_value' - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - 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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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] - assert args[0].parent == 'parent_value' - assert args[0].finding_id == 'finding_id_value' - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_create_notification_config(transport: str = 'grpc', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - streaming_config=gcs_notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), - ) - response = client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_create_notification_config_from_dict(): - test_create_notification_config(request_type=dict) - - -def test_create_notification_config_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 = SecurityCenterClient( - 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_notification_config), - '__call__') as call: - client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - -@pytest.mark.asyncio -async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_create_notification_config_async_from_dict(): - await test_create_notification_config_async(request_type=dict) - - -def test_create_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_config(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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.create_notification_config(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_notification_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(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] - assert args[0].parent == 'parent_value' - assert args[0].config_id == 'config_id_value' - assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') - - -def test_create_notification_config_flattened_error(): - client = SecurityCenterClient( - 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_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(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] - assert args[0].parent == 'parent_value' - assert args[0].config_id == 'config_id_value' - assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') - - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -def test_delete_notification_config(transport: str = 'grpc', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_config_from_dict(): - test_delete_notification_config(request_type=dict) - - -def test_delete_notification_config_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 = SecurityCenterClient( - 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.delete_notification_config), - '__call__') as call: - client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - -@pytest.mark.asyncio -async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_notification_config_async_from_dict(): - await test_delete_notification_config_async(request_type=dict) - - -def test_delete_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value = None - client.delete_notification_config(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_delete_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_config(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_delete_notification_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_notification_config( - 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] - assert args[0].name == 'name_value' - - -def test_delete_notification_config_flattened_error(): - client = SecurityCenterClient( - 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.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_notification_config( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_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 = SecurityCenterClient( - 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_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_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] - assert args[0].resource == 'resource_value' - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_notification_config(transport: str = 'grpc', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - streaming_config=notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), - ) - response = client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_get_notification_config_from_dict(): - test_get_notification_config(request_type=dict) - - -def test_get_notification_config_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 = SecurityCenterClient( - 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_notification_config), - '__call__') as call: - client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - -@pytest.mark.asyncio -async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_async_from_dict(): - await test_get_notification_config_async(request_type=dict) - - -def test_get_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value = notification_config.NotificationConfig() - client.get_notification_config(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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - await client.get_notification_config(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_notification_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_config( - 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] - assert args[0].name == 'name_value' - - -def test_get_notification_config_flattened_error(): - client = SecurityCenterClient( - 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_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_config( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_from_dict(): - test_get_organization_settings(request_type=dict) - - -def test_get_organization_settings_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 = SecurityCenterClient( - 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_organization_settings), - '__call__') as call: - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_settings(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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_settings(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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_settings( - 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] - assert args[0].name == 'name_value' - - -def test_get_organization_settings_flattened_error(): - client = SecurityCenterClient( - 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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_settings( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_source(transport: str = 'grpc', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_get_source_from_dict(): - test_get_source(request_type=dict) - - -def test_get_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_source(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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_source(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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_source( - 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] - assert args[0].name == 'name_value' - - -def test_get_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_source( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_group_assets(transport: str = 'grpc', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_assets_from_dict(): - test_group_assets(request_type=dict) - - -def test_group_assets_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 = SecurityCenterClient( - 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.group_assets), - '__call__') as call: - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(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_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(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_group_assets_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - -def test_group_assets_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.group_assets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_group_findings(transport: str = 'grpc', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_findings_from_dict(): - test_group_findings(request_type=dict) - - -def test_group_findings_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 = SecurityCenterClient( - 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.group_findings), - '__call__') as call: - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_findings(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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_findings(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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_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] - assert args[0].parent == 'parent_value' - assert args[0].group_by == 'group_by_value' - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - 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.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].group_by == 'group_by_value' - - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_findings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - -def test_group_findings_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_findings(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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_findings(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, securitycenter_service.GroupResult) - for i in responses) - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.group_findings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_assets(transport: str = 'grpc', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_from_dict(): - test_list_assets(request_type=dict) - - -def test_list_assets_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 = SecurityCenterClient( - 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_assets), - '__call__') as call: - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(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_assets_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - -def test_list_assets_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_assets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_findings(transport: str = 'grpc', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_findings_from_dict(): - test_list_findings(request_type=dict) - - -def test_list_findings_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 = SecurityCenterClient( - 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_findings), - '__call__') as call: - client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - - -def test_list_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = securitycenter_service.ListFindingsResponse() - client.list_findings(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_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse()) - await client.list_findings(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_findings_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_findings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in results) - -def test_list_findings_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_findings(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_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_findings(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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in responses) - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_findings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_notification_configs(transport: str = 'grpc', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_configs_from_dict(): - test_list_notification_configs(request_type=dict) - - -def test_list_notification_configs_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 = SecurityCenterClient( - 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_notification_configs), - '__call__') as call: - client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - -@pytest.mark.asyncio -async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_from_dict(): - await test_list_notification_configs_async(request_type=dict) - - -def test_list_notification_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_configs(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_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - await client.list_notification_configs(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_notification_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_configs( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_notification_configs_flattened_error(): - client = SecurityCenterClient( - 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_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_configs( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_notification_configs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, notification_config.NotificationConfig) - for i in results) - -def test_list_notification_configs_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_configs(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_notification_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_configs(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, notification_config.NotificationConfig) - for i in responses) - -@pytest.mark.asyncio -async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_notification_configs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_sources(transport: str = 'grpc', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_from_dict(): - test_list_sources(request_type=dict) - - -def test_list_sources_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 = SecurityCenterClient( - 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_sources), - '__call__') as call: - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_sources(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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_sources(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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_sources( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_sources_flattened_error(): - client = SecurityCenterClient( - 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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_sources( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_sources(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - -def test_list_sources_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_sources(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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_sources(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, source.Source) - for i in responses) - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_sources(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_run_asset_discovery(transport: str = 'grpc', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_from_dict(): - test_run_asset_discovery(request_type=dict) - - -def test_run_asset_discovery_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 = SecurityCenterClient( - 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.run_asset_discovery), - '__call__') as call: - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(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_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(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_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.run_asset_discovery( - 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] - assert args[0].parent == 'parent_value' - - -def test_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - 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.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.run_asset_discovery( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_set_finding_state(transport: str = 'grpc', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_set_finding_state_from_dict(): - test_set_finding_state(request_type=dict) - - -def test_set_finding_state_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 = SecurityCenterClient( - 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.set_finding_state), - '__call__') as call: - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_state(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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_state(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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].state == finding.Finding.State.ACTIVE - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - 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.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].state == finding.Finding.State.ACTIVE - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_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 = SecurityCenterClient( - 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.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_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] - assert args[0].resource == 'resource_value' - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_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 = SecurityCenterClient( - 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.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_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] - assert args[0].resource == 'resource_value' - assert args[0].permissions == ['permissions_value'] - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - 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.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - assert args[0].permissions == ['permissions_value'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_update_finding(transport: str = 'grpc', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_update_finding_from_dict(): - test_update_finding(request_type=dict) - - -def test_update_finding_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 = SecurityCenterClient( - 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_finding), - '__call__') as call: - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'finding.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_finding(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', - 'finding.name=finding.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'finding.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_finding(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', - 'finding.name=finding.name/value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.Finding(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] - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -def test_update_finding_flattened_error(): - client = SecurityCenterClient( - 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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.Finding(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] - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -@pytest.mark.asyncio -async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_update_notification_config(transport: str = 'grpc', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - streaming_config=gcs_notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), - ) - response = client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_update_notification_config_from_dict(): - test_update_notification_config(request_type=dict) - - -def test_update_notification_config_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 = SecurityCenterClient( - 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_notification_config), - '__call__') as call: - client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - -@pytest.mark.asyncio -async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_update_notification_config_async_from_dict(): - await test_update_notification_config_async(request_type=dict) - - -def test_update_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'notification_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_config(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', - 'notification_config.name=notification_config.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'notification_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.update_notification_config(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', - 'notification_config.name=notification_config.name/value', - ) in kw['metadata'] - - -def test_update_notification_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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] - assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_notification_config_flattened_error(): - client = SecurityCenterClient( - 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_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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] - assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_from_dict(): - test_update_organization_settings(request_type=dict) - - -def test_update_organization_settings_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 = SecurityCenterClient( - 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_organization_settings), - '__call__') as call: - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'organization_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_settings(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', - 'organization_settings.name=organization_settings.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'organization_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_settings(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', - 'organization_settings.name=organization_settings.name/value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(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] - assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - 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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(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] - assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') - - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_source(transport: str = 'grpc', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_source_from_dict(): - test_update_source(request_type=dict) - - -def test_update_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'source.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_source(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', - 'source.name=source.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'source.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_source(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', - 'source.name=source.name/value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.Source(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] - assert args[0].source == gcs_source.Source(name='name_value') - - -def test_update_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.Source(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] - assert args[0].source == gcs_source.Source(name='name_value') - - -@pytest.mark.asyncio -async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -def test_update_security_marks(transport: str = 'grpc', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_security_marks_from_dict(): - test_update_security_marks(request_type=dict) - - -def test_update_security_marks_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 = SecurityCenterClient( - 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_security_marks), - '__call__') as call: - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'security_marks.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(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', - 'security_marks.name=security_marks.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'security_marks.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(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', - 'security_marks.name=security_marks.name/value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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] - assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') - - -def test_update_security_marks_flattened_error(): - client = SecurityCenterClient( - 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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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] - assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') - - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, -]) -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_source', - 'create_finding', - 'create_notification_config', - 'delete_notification_config', - 'get_iam_policy', - 'get_notification_config', - 'get_organization_settings', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_findings', - 'list_notification_configs', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_iam_policy', - 'test_iam_permissions', - 'update_finding', - 'update_notification_config', - 'update_organization_settings', - 'update_source', - 'update_security_marks', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_security_center_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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_center_base_transport_with_credentials_file_old_google_auth(): - # 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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_security_center_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.securitycenter_v1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_security_center_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) - SecurityCenterClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_center_auth_adc_old_google_auth(): - # 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) - SecurityCenterClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_security_center_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',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_security_center_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_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( - "securitycenter.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_host_no_port(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - ) - assert client.transport._host == 'securitycenter.googleapis.com:443' - - -def test_security_center_host_with_port(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - ) - assert client.transport._host == 'securitycenter.googleapis.com:8000' - -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_notification_config_path(): - organization = "scallop" - notification_config = "abalone" - expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - actual = SecurityCenterClient.notification_config_path(organization, notification_config) - assert expected == actual - - -def test_parse_notification_config_path(): - expected = { - "organization": "squid", - "notification_config": "clam", - } - path = SecurityCenterClient.notification_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_notification_config_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "whelk" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "octopus", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "oyster" - asset = "nudibranch" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "cuttlefish", - "asset": "mussel", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_source_path(): - organization = "winkle" - source = "nautilus" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "scallop", - "source": "abalone", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_topic_path(): - project = "squid" - topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SecurityCenterClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "whelk", - "topic": "octopus", - } - path = SecurityCenterClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_topic_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1beta1/.coveragerc b/owl-bot-staging/v1beta1/.coveragerc deleted file mode 100644 index 3655af7f..00000000 --- a/owl-bot-staging/v1beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__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/v1beta1/MANIFEST.in b/owl-bot-staging/v1beta1/MANIFEST.in deleted file mode 100644 index 328e3b89..00000000 --- a/owl-bot-staging/v1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1beta1 *.py diff --git a/owl-bot-staging/v1beta1/README.rst b/owl-bot-staging/v1beta1/README.rst deleted file mode 100644 index f8c63f4c..00000000 --- a/owl-bot-staging/v1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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/v1beta1/docs/conf.py b/owl-bot-staging/v1beta1/docs/conf.py deleted file mode 100644 index f4837604..00000000 --- a/owl-bot-staging/v1beta1/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-securitycenter documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-securitycenter" -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-securitycenter-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-securitycenter.tex", - u"google-cloud-securitycenter Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-securitycenter", - u"Google Cloud Securitycenter Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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/v1beta1/docs/index.rst b/owl-bot-staging/v1beta1/docs/index.rst deleted file mode 100644 index 88360626..00000000 --- a/owl-bot-staging/v1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1beta1/services - securitycenter_v1beta1/types diff --git a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/security_center.rst b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/security_center.rst deleted file mode 100644 index 304849ec..00000000 --- a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/services.rst b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/services.rst deleted file mode 100644 index a09a4b86..00000000 --- a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1beta1 API -==================================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/types.rst b/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/types.rst deleted file mode 100644 index 44bb4fec..00000000 --- a/owl-bot-staging/v1beta1/docs/securitycenter_v1beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Securitycenter v1beta1 API -================================================= - -.. automodule:: google.cloud.securitycenter_v1beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index c85455c8..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter/__init__.py +++ /dev/null @@ -1,77 +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.securitycenter_v1beta1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1beta1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1beta1.types.asset import Asset -from google.cloud.securitycenter_v1beta1.types.finding import Finding -from google.cloud.securitycenter_v1beta1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1beta1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1beta1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1beta1.types.source import Source - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Asset', - 'Finding', - 'OrganizationSettings', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/v1beta1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py deleted file mode 100644 index 2787c7bd..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/__init__.py +++ /dev/null @@ -1,78 +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.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.asset import Asset -from .types.finding import Finding -from .types.organization_settings import OrganizationSettings -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source - -__all__ = ( - 'SecurityCenterAsyncClient', -'Asset', -'CreateFindingRequest', -'CreateSourceRequest', -'Finding', -'GetOrganizationSettingsRequest', -'GetSourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'OrganizationSettings', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityCenterClient', -'SecurityMarks', -'SetFindingStateRequest', -'Source', -'UpdateFindingRequest', -'UpdateOrganizationSettingsRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json deleted file mode 100644 index 56b17ccf..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,203 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1beta1", - "protoPackage": "google.cloud.securitycenter.v1beta1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/py.typed b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/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/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py deleted file mode 100644 index fce6b0c5..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py deleted file mode 100644 index b00ba609..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ /dev/null @@ -1,1886 +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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1 Beta APIs for Security Center service.""" - - _client: SecurityCenterClient - - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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, ~.SecurityCenterTransport]): 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_source(self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``source`` 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.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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 = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # 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_source, - 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_finding(self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` 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.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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 = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # 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_finding, - 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 get_iam_policy(self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # 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_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(( - ("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_organization_settings(self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - 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.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings, - 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_source(self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - - 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.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.GetSourceRequest(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_source, - 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 group_assets(self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(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.group_assets, - 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=480.0, - ), - default_timeout=480.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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state``). The string value - should follow SQL syntax: comma separated list of - fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - This corresponds to the ``group_by`` 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.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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 = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_findings, - 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=480.0, - ), - default_timeout=480.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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: securitycenter_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.ListAssetsRequest`): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1beta1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = securitycenter_service.ListAssetsRequest(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.list_assets, - 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=480.0, - ), - default_timeout=480.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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: securitycenter_service.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.ListFindingsRequest`): - The request object. Request message for listing - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1beta1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = securitycenter_service.ListFindingsRequest(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.list_findings, - 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=480.0, - ), - default_timeout=480.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.ListFindingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - - 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.ListSourcesRequest(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_sources, - 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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp_pb2.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1beta1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` 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.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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 = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # 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_finding_state, - 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 set_iam_policy(self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # 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=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(( - ("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, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # 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_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(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_finding(self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1beta1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` 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.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - 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 = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # 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_finding, - 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(( - ("finding.name", request.finding.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_organization_settings(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1beta1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` 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.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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 = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # 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_organization_settings, - 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(( - ("organization_settings.name", request.organization_settings.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_source(self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1beta1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``source`` 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.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source]) - 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 = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # 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_source, - 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(( - ("source.name", request.source.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_security_marks(self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1beta1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` 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.securitycenter_v1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - 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 = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # 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_security_marks, - default_timeout=480.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(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Send the request. - response = await 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-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py deleted file mode 100644 index ac50243b..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ /dev/null @@ -1,2052 +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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1 Beta APIs for Security Center service.""" - - @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 = "securitycenter.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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SecurityCenterTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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, SecurityCenterTransport]): 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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, SecurityCenterTransport): - # transport is a SecurityCenterTransport instance. - if credentials or client_options.credentials_file: - 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: - 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=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def create_source(self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (google.cloud.securitycenter_v1beta1.types.CreateSourceRequest): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``source`` 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.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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 securitycenter_service.CreateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_source] - - # 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_finding(self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (google.cloud.securitycenter_v1beta1.types.CreateFindingRequest): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` 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.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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 securitycenter_service.CreateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # 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 get_iam_policy(self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): - The request object. Request message for `GetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_organization_settings(self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (google.cloud.securitycenter_v1beta1.types.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - 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.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings] - - # 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_source(self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (google.cloud.securitycenter_v1beta1.types.GetSourceRequest): - The request object. Request message for getting a - source. - name (str): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - - 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.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(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_source] - - # 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 group_assets(self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (google.cloud.securitycenter_v1beta1.types.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1beta1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # 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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (google.cloud.securitycenter_v1beta1.types.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state``). The string value - should follow SQL syntax: comma separated list of - fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - This corresponds to the ``group_by`` 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.securitycenter_v1beta1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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 securitycenter_service.GroupFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_findings] - - # 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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: securitycenter_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - Args: - request (google.cloud.securitycenter_v1beta1.types.ListAssetsRequest): - The request object. Request message for listing assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1beta1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # 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.ListAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: securitycenter_service.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (google.cloud.securitycenter_v1beta1.types.ListFindingsRequest): - The request object. Request message for listing - findings. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1beta1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_findings] - - # 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.ListFindingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - Args: - request (google.cloud.securitycenter_v1beta1.types.ListSourcesRequest): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - - 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.securitycenter_v1beta1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListSourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(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_sources] - - # 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.ListSourcesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - The JSON representation for Empty is empty JSON - object {}. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.RunAssetDiscoveryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp_pb2.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (google.cloud.securitycenter_v1beta1.types.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - name (str): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` 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.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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 securitycenter_service.SetFindingStateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_state] - - # 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 set_iam_policy(self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): - The request object. Request message for `SetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # 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, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): - The request object. Request message for - `TestIamPermissions` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (Sequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_finding(self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (google.cloud.securitycenter_v1beta1.types.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` 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.securitycenter_v1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - 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 securitycenter_service.UpdateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_organization_settings(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (google.cloud.securitycenter_v1beta1.types.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` 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.securitycenter_v1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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 securitycenter_service.UpdateOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_settings.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_source(self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (google.cloud.securitycenter_v1beta1.types.UpdateSourceRequest): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``source`` 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.securitycenter_v1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source]) - 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 securitycenter_service.UpdateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.source.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_security_marks(self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (google.cloud.securitycenter_v1beta1.types.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` 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.securitycenter_v1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - 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 securitycenter_service.UpdateSecurityMarksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # 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-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py deleted file mode 100644 index eef89b03..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py +++ /dev/null @@ -1,630 +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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` - 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[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: - 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) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse` - 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: - 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) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` - 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[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: - 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) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse` - 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: - 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) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` - 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[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: - 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) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListAssetsResponse` - 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: - 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) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` - 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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - 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.securitycenter_v1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListFindingsResponse): - 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 = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: - 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) -> Iterable[finding.Finding]: - for page in self.pages: - yield from page.findings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListFindingsResponse` - 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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - 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.securitycenter_v1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListFindingsResponse): - 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 = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: - 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) -> AsyncIterable[finding.Finding]: - async def async_generator(): - async for page in self.pages: - for response in page.findings: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` - 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[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: - 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) -> Iterable[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1beta1.types.ListSourcesResponse` - 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: - 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) -> AsyncIterable[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - 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/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py deleted file mode 100644 index 8bdaf713..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py deleted file mode 100644 index 0166afdc..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py +++ /dev/null @@ -1,485 +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 packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-securitycenter', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.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 = self._get_scopes_kwargs(self._host, 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 is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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_source: gapic_v1.method.wrap_method( - self.get_source, - 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.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_findings, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - 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 get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py deleted file mode 100644 index 10b4ae08..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,742 +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 # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # 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 - -import grpc # type: ignore - -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1 Beta APIs for Security Center service. - - 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 = 'securitycenter.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 applicatin 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 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 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] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'securitycenter.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 operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index 5d7fd656..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,746 +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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1 Beta APIs for Security Center service. - - 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 = 'securitycenter.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 = 'securitycenter.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 applicatin 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 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 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] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py deleted file mode 100644 index abeb0314..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/__init__.py +++ /dev/null @@ -1,86 +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 .asset import ( - Asset, -) -from .finding import ( - Finding, -) -from .organization_settings import ( - OrganizationSettings, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_marks import ( - SecurityMarks, -) -from .securitycenter_service import ( - CreateFindingRequest, - CreateSourceRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListSourcesRequest, - ListSourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - UpdateFindingRequest, - UpdateOrganizationSettingsRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .source import ( - Source, -) - -__all__ = ( - 'Asset', - 'Finding', - 'OrganizationSettings', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py deleted file mode 100644 index 692b5856..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/asset.py +++ /dev/null @@ -1,151 +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.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1beta1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (Sequence[google.cloud.securitycenter_v1beta1.types.Asset.ResourcePropertiesEntry]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated, - added, or deleted in Security Command Center. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - Immutable. The full resource name of the Google Cloud - resource this asset represents. This field is immutable - after create time. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (Sequence[str]): - Owners of the Google Cloud resource. - """ - - resource_name = proto.Field( - proto.STRING, - number=1, - ) - resource_type = proto.Field( - proto.STRING, - number=2, - ) - resource_parent = proto.Field( - proto.STRING, - number=3, - ) - resource_project = proto.Field( - proto.STRING, - number=4, - ) - resource_owners = proto.RepeatedField( - proto.STRING, - number=5, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py deleted file mode 100644 index 77e085cd..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/finding.py +++ /dev/null @@ -1,148 +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.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - A finding is a record of assessment data (security, risk, health - or privacy) ingested into Security Command Center for - presentation, notification, analysis, policy testing, and - enforcement. For example, an XSS vulnerability in an App Engine - application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - Immutable. The relative resource name of the source the - finding belongs to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (Sequence[google.cloud.securitycenter_v1beta1.types.Finding.SourcePropertiesEntry]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the event took place, or - when an update to the finding occurred. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. If the finding - were to be resolved afterward, this time would - reflect when the finding was resolved. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - """ - class State(proto.Enum): - r"""The state of the finding.""" - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - name = proto.Field( - proto.STRING, - number=1, - ) - parent = proto.Field( - proto.STRING, - number=2, - ) - resource_name = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category = proto.Field( - proto.STRING, - number=5, - ) - external_uri = proto.Field( - proto.STRING, - number=6, - ) - source_properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py deleted file mode 100644 index fe9c8e1d..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/organization_settings.py +++ /dev/null @@ -1,96 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - Attributes: - project_ids (Sequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py deleted file mode 100644 index 6b4a7a57..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py +++ /dev/null @@ -1,57 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - Attributes: - state (google.cloud.securitycenter_v1beta1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run.""" - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py deleted file mode 100644 index 7d0b12c2..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/security_marks.py +++ /dev/null @@ -1,64 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[google.cloud.securitycenter_v1beta1.types.SecurityMarks.MarksEntry]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - marks = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py deleted file mode 100644 index 020504b4..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py +++ /dev/null @@ -1,1016 +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.securitycenter_v1beta1.types import asset as gcs_asset -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'CreateFindingRequest', - 'CreateSourceRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'RunAssetDiscoveryRequest', - 'UpdateFindingRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - finding_id = proto.Field( - proto.STRING, - number=2, - ) - finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``resource_properties.size = 100`` is a valid - filter string. - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_type - - security_center_properties.resource_parent - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the Asset's "state" property - is updated to indicate whether the asset was added, removed, - or remained present during the compare_duration period of - time that precedes the read_time. This is the time between - (read_time - compare_duration) and read_time. - - The state value is derived based on the presence of the - asset at the two points in time. Intermediate state changes - between the two times don't affect the result. For example, - the results aren't affected if the asset is removed and - re-created again. - - Possible "state" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present before - compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - This field is ignored if ``state`` is not a field in - ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - group_by = proto.Field( - proto.STRING, - number=3, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token = proto.Field( - proto.STRING, - number=7, - ) - page_size = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - Attributes: - group_by_results (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To - groupBy across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``source_properties.size = 100`` is a valid - filter string. - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state``). The string value should - follow SQL syntax: comma separated list of fields. For - example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - group_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - page_token = proto.Field( - proto.STRING, - number=5, - ) - page_size = proto.Field( - proto.INT32, - number=6, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - Attributes: - group_by_results (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (Sequence[google.cloud.securitycenter_v1beta1.types.GroupResult.PropertiesEntry]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count = proto.Field( - proto.INT64, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - Attributes: - sources (Sequence[google.cloud.securitycenter_v1beta1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``resource_properties.size = 100`` is a valid - filter string. - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetResult's "state" - attribute is updated to indicate whether the asset was - added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state value is derived based on the presence of the - asset at the two points in time. Intermediate state changes - between the two times don't affect the result. For example, - the results aren't affected if the asset is removed and - re-created again. - - Possible "state" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present before - compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state is "UNUSED", which indicates that the asset is present - at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. A field mask to specify the - ListAssetsResult fields to be listed in the - response. An empty field mask will list all - fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - order_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - page_size = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - Attributes: - list_assets_results (Sequence[google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - Attributes: - asset (google.cloud.securitycenter_v1beta1.types.Asset): - Asset matching the search request. - state (google.cloud.securitycenter_v1beta1.types.ListAssetsResponse.ListAssetsResult.State): - State of the asset. - """ - class State(proto.Enum): - r"""State of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state should be: UNUSED - """ - STATE_UNSPECIFIED = 0 - UNUSED = 1 - ADDED = 2 - REMOVED = 3 - ACTIVE = 4 - - asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.State', - ) - - @property - def raw_page(self): - return self - - list_assets_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id]". To - list across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``source_properties.size = 100`` is a valid - filter string. - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. A field mask to specify the Finding - fields to be listed in the response. An empty - field mask will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - order_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - field_mask = proto.Field( - proto.MESSAGE, - number=5, - message=field_mask_pb2.FieldMask, - ) - page_token = proto.Field( - proto.STRING, - number=6, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - Attributes: - findings (Sequence[google.cloud.securitycenter_v1beta1.types.Finding]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - @property - def raw_page(self): - return self - - findings = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (google.cloud.securitycenter_v1beta1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - state = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - Attributes: - finding (google.cloud.securitycenter_v1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - finding resource. This field should not be - specified when creating a finding. - """ - - finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - Attributes: - organization_settings (google.cloud.securitycenter_v1beta1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - """ - - organization_settings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - Attributes: - source (google.cloud.securitycenter_v1beta1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - """ - - source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - Attributes: - security_marks (google.cloud.securitycenter_v1beta1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - security marks resource. - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. - """ - - security_marks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py b/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py deleted file mode 100644 index 140027f0..00000000 --- a/owl-bot-staging/v1beta1/google/cloud/securitycenter_v1beta1/types/source.py +++ /dev/null @@ -1,72 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1beta1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, etc. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and - outdated/insecure libraries.". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1beta1/mypy.ini b/owl-bot-staging/v1beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1beta1/noxfile.py b/owl-bot-staging/v1beta1/noxfile.py deleted file mode 100644 index 713b8907..00000000 --- a/owl-bot-staging/v1beta1/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']) -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/securitycenter_v1beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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']) -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.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py b/owl-bot-staging/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py deleted file mode 100644 index c85a7b83..00000000 --- a/owl-bot-staging/v1beta1/scripts/fixup_securitycenter_v1beta1_keywords.py +++ /dev/null @@ -1,193 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_source': ('parent', 'source', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('source', 'update_mask', ), - } - - 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: not a.keyword.value 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=securitycenterCallTransformer(), -): - """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 securitycenter 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/v1beta1/setup.py b/owl-bot-staging/v1beta1/setup.py deleted file mode 100644 index 0653f115..00000000 --- a/owl-bot-staging/v1beta1/setup.py +++ /dev/null @@ -1,54 +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-securitycenter', - 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.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', '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/v1beta1/tests/__init__.py b/owl-bot-staging/v1beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/__init__.py b/owl-bot-staging/v1beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/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/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/__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/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py deleted file mode 100644 index aa8d8dbe..00000000 --- a/owl-bot-staging/v1beta1/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py +++ /dev/null @@ -1,6133 +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 packaging.version - -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 future -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 operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.securitycenter_v1beta1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1beta1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.services.security_center import transports -from google.cloud.securitycenter_v1beta1.services.security_center.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -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.longrunning import operations_pb2 -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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - SecurityCenterClient, - SecurityCenterAsyncClient, -]) -def test_security_center_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 == 'securitycenter.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_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", [ - SecurityCenterClient, - SecurityCenterAsyncClient, -]) -def test_security_center_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 == 'securitycenter.googleapis.com:443' - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_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(SecurityCenterClient, '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(SecurityCenterClient, '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(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() - 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() - 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() - - # 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() - - # 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) - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_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) - - 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() - 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() - 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,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_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) - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - 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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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, - ) - - -def test_create_source(transport: str = 'grpc', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_create_source_from_dict(): - test_create_source(request_type=dict) - - -def test_create_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_source(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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_source(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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.Source(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] - assert args[0].parent == 'parent_value' - assert args[0].source == gcs_source.Source(name='name_value') - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.Source(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] - assert args[0].parent == 'parent_value' - assert args[0].source == gcs_source.Source(name='name_value') - - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_finding(transport: str = 'grpc', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_create_finding_from_dict(): - test_create_finding(request_type=dict) - - -def test_create_finding_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 = SecurityCenterClient( - 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_finding), - '__call__') as call: - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_finding(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_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_finding(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_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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] - assert args[0].parent == 'parent_value' - assert args[0].finding_id == 'finding_id_value' - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - 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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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] - assert args[0].parent == 'parent_value' - assert args[0].finding_id == 'finding_id_value' - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_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 = SecurityCenterClient( - 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_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_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] - assert args[0].resource == 'resource_value' - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_from_dict(): - test_get_organization_settings(request_type=dict) - - -def test_get_organization_settings_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 = SecurityCenterClient( - 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_organization_settings), - '__call__') as call: - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_settings(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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_settings(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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_settings( - 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] - assert args[0].name == 'name_value' - - -def test_get_organization_settings_flattened_error(): - client = SecurityCenterClient( - 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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_settings( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_source(transport: str = 'grpc', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_get_source_from_dict(): - test_get_source(request_type=dict) - - -def test_get_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_source(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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_source(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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_source( - 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] - assert args[0].name == 'name_value' - - -def test_get_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_source( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_group_assets(transport: str = 'grpc', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_group_assets_from_dict(): - test_group_assets(request_type=dict) - - -def test_group_assets_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 = SecurityCenterClient( - 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.group_assets), - '__call__') as call: - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(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_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(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_group_assets_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - -def test_group_assets_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.group_assets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_group_findings(transport: str = 'grpc', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_group_findings_from_dict(): - test_group_findings(request_type=dict) - - -def test_group_findings_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 = SecurityCenterClient( - 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.group_findings), - '__call__') as call: - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_findings(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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_findings(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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_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] - assert args[0].parent == 'parent_value' - assert args[0].group_by == 'group_by_value' - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - 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.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].group_by == 'group_by_value' - - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_findings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - -def test_group_findings_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_findings(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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_findings(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, securitycenter_service.GroupResult) - for i in responses) - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.group_findings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_assets(transport: str = 'grpc', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_from_dict(): - test_list_assets(request_type=dict) - - -def test_list_assets_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 = SecurityCenterClient( - 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_assets), - '__call__') as call: - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(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_assets_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - -def test_list_assets_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_assets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_findings(transport: str = 'grpc', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_findings_from_dict(): - test_list_findings(request_type=dict) - - -def test_list_findings_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 = SecurityCenterClient( - 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_findings), - '__call__') as call: - client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - - -def test_list_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = securitycenter_service.ListFindingsResponse() - client.list_findings(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_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse()) - await client.list_findings(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_findings_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_findings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, finding.Finding) - for i in results) - -def test_list_findings_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - pages = list(client.list_findings(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_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_findings(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, finding.Finding) - for i in responses) - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - finding.Finding(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - findings=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - findings=[ - finding.Finding(), - finding.Finding(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_findings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_sources(transport: str = 'grpc', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_from_dict(): - test_list_sources(request_type=dict) - - -def test_list_sources_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 = SecurityCenterClient( - 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_sources), - '__call__') as call: - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_sources(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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_sources(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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_sources( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_sources_flattened_error(): - client = SecurityCenterClient( - 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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_sources( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_sources(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - -def test_list_sources_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_sources(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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_sources(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, source.Source) - for i in responses) - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_sources(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_run_asset_discovery(transport: str = 'grpc', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_from_dict(): - test_run_asset_discovery(request_type=dict) - - -def test_run_asset_discovery_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 = SecurityCenterClient( - 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.run_asset_discovery), - '__call__') as call: - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(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_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(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_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.run_asset_discovery( - 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] - assert args[0].parent == 'parent_value' - - -def test_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - 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.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.run_asset_discovery( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_set_finding_state(transport: str = 'grpc', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_set_finding_state_from_dict(): - test_set_finding_state(request_type=dict) - - -def test_set_finding_state_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 = SecurityCenterClient( - 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.set_finding_state), - '__call__') as call: - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_state(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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_state(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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].state == finding.Finding.State.ACTIVE - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - 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.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].state == finding.Finding.State.ACTIVE - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_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 = SecurityCenterClient( - 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.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_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] - assert args[0].resource == 'resource_value' - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_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 = SecurityCenterClient( - 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.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_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] - assert args[0].resource == 'resource_value' - assert args[0].permissions == ['permissions_value'] - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - 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.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - assert args[0].permissions == ['permissions_value'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_update_finding(transport: str = 'grpc', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -def test_update_finding_from_dict(): - test_update_finding(request_type=dict) - - -def test_update_finding_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 = SecurityCenterClient( - 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_finding), - '__call__') as call: - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'finding.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_finding(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', - 'finding.name=finding.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'finding.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_finding(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', - 'finding.name=finding.name/value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.Finding(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] - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -def test_update_finding_flattened_error(): - client = SecurityCenterClient( - 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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.Finding(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] - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -@pytest.mark.asyncio -async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_update_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_from_dict(): - test_update_organization_settings(request_type=dict) - - -def test_update_organization_settings_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 = SecurityCenterClient( - 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_organization_settings), - '__call__') as call: - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'organization_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_settings(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', - 'organization_settings.name=organization_settings.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'organization_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_settings(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', - 'organization_settings.name=organization_settings.name/value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(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] - assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - 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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(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] - assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') - - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_source(transport: str = 'grpc', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -def test_update_source_from_dict(): - test_update_source(request_type=dict) - - -def test_update_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'source.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_source(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', - 'source.name=source.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'source.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_source(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', - 'source.name=source.name/value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.Source(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] - assert args[0].source == gcs_source.Source(name='name_value') - - -def test_update_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.Source(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] - assert args[0].source == gcs_source.Source(name='name_value') - - -@pytest.mark.asyncio -async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - ) - - -def test_update_security_marks(transport: str = 'grpc', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - - -def test_update_security_marks_from_dict(): - test_update_security_marks(request_type=dict) - - -def test_update_security_marks_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 = SecurityCenterClient( - 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_security_marks), - '__call__') as call: - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'security_marks.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(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', - 'security_marks.name=security_marks.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'security_marks.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(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', - 'security_marks.name=security_marks.name/value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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] - assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') - - -def test_update_security_marks_flattened_error(): - client = SecurityCenterClient( - 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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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] - assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') - - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, -]) -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_source', - 'create_finding', - 'get_iam_policy', - 'get_organization_settings', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_findings', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_iam_policy', - 'test_iam_permissions', - 'update_finding', - 'update_organization_settings', - 'update_source', - 'update_security_marks', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_security_center_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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_center_base_transport_with_credentials_file_old_google_auth(): - # 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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_security_center_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.securitycenter_v1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_security_center_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) - SecurityCenterClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_center_auth_adc_old_google_auth(): - # 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) - SecurityCenterClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_security_center_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',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_security_center_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_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( - "securitycenter.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_host_no_port(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - ) - assert client.transport._host == 'securitycenter.googleapis.com:443' - - -def test_security_center_host_with_port(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - ) - assert client.transport._host == 'securitycenter.googleapis.com:8000' - -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "scallop" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "abalone", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_source_path(): - organization = "oyster" - source = "nudibranch" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "cuttlefish", - "source": "mussel", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/owl-bot-staging/v1p1beta1/.coveragerc b/owl-bot-staging/v1p1beta1/.coveragerc deleted file mode 100644 index 3655af7f..00000000 --- a/owl-bot-staging/v1p1beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/securitycenter/__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/v1p1beta1/MANIFEST.in b/owl-bot-staging/v1p1beta1/MANIFEST.in deleted file mode 100644 index 57b563bd..00000000 --- a/owl-bot-staging/v1p1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/securitycenter *.py -recursive-include google/cloud/securitycenter_v1p1beta1 *.py diff --git a/owl-bot-staging/v1p1beta1/README.rst b/owl-bot-staging/v1p1beta1/README.rst deleted file mode 100644 index f8c63f4c..00000000 --- a/owl-bot-staging/v1p1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Securitycenter 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 Securitycenter 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/v1p1beta1/docs/conf.py b/owl-bot-staging/v1p1beta1/docs/conf.py deleted file mode 100644 index f4837604..00000000 --- a/owl-bot-staging/v1p1beta1/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-securitycenter documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-securitycenter" -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-securitycenter-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "google-cloud-securitycenter.tex", - u"google-cloud-securitycenter Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "google-cloud-securitycenter", - u"Google Cloud Securitycenter Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "google-cloud-securitycenter", - u"google-cloud-securitycenter Documentation", - author, - "google-cloud-securitycenter", - "GAPIC library for Google Cloud Securitycenter 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/v1p1beta1/docs/index.rst b/owl-bot-staging/v1p1beta1/docs/index.rst deleted file mode 100644 index 45263147..00000000 --- a/owl-bot-staging/v1p1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - securitycenter_v1p1beta1/services - securitycenter_v1p1beta1/types diff --git a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst deleted file mode 100644 index adab7f4a..00000000 --- a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/security_center.rst +++ /dev/null @@ -1,10 +0,0 @@ -SecurityCenter --------------------------------- - -.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center - :members: - :inherited-members: - -.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/services.rst b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/services.rst deleted file mode 100644 index 7f537e85..00000000 --- a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Securitycenter v1p1beta1 API -====================================================== -.. toctree:: - :maxdepth: 2 - - security_center diff --git a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/types.rst b/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/types.rst deleted file mode 100644 index 1facc905..00000000 --- a/owl-bot-staging/v1p1beta1/docs/securitycenter_v1p1beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Securitycenter v1p1beta1 API -=================================================== - -.. automodule:: google.cloud.securitycenter_v1p1beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/__init__.py deleted file mode 100644 index 4f397497..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/__init__.py +++ /dev/null @@ -1,97 +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.securitycenter_v1p1beta1.services.security_center.client import SecurityCenterClient -from google.cloud.securitycenter_v1p1beta1.services.security_center.async_client import SecurityCenterAsyncClient - -from google.cloud.securitycenter_v1p1beta1.types.asset import Asset -from google.cloud.securitycenter_v1p1beta1.types.finding import Finding -from google.cloud.securitycenter_v1p1beta1.types.folder import Folder -from google.cloud.securitycenter_v1p1beta1.types.notification_config import NotificationConfig -from google.cloud.securitycenter_v1p1beta1.types.notification_message import NotificationMessage -from google.cloud.securitycenter_v1p1beta1.types.organization_settings import OrganizationSettings -from google.cloud.securitycenter_v1p1beta1.types.resource import Resource -from google.cloud.securitycenter_v1p1beta1.types.run_asset_discovery_response import RunAssetDiscoveryResponse -from google.cloud.securitycenter_v1p1beta1.types.security_marks import SecurityMarks -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateFindingRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import CreateSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import DeleteNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetOrganizationSettingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GetSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupAssetsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupFindingsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import GroupResult -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListAssetsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListFindingsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListNotificationConfigsResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import ListSourcesResponse -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import RunAssetDiscoveryRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import SetFindingStateRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateFindingRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateNotificationConfigRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateOrganizationSettingsRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSecurityMarksRequest -from google.cloud.securitycenter_v1p1beta1.types.securitycenter_service import UpdateSourceRequest -from google.cloud.securitycenter_v1p1beta1.types.source import Source - -__all__ = ('SecurityCenterClient', - 'SecurityCenterAsyncClient', - 'Asset', - 'Finding', - 'Folder', - 'NotificationConfig', - 'NotificationMessage', - 'OrganizationSettings', - 'Resource', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py deleted file mode 100644 index ca8f63fd..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/__init__.py +++ /dev/null @@ -1,98 +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.security_center import SecurityCenterClient -from .services.security_center import SecurityCenterAsyncClient - -from .types.asset import Asset -from .types.finding import Finding -from .types.folder import Folder -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.organization_settings import OrganizationSettings -from .types.resource import Resource -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source - -__all__ = ( - 'SecurityCenterAsyncClient', -'Asset', -'CreateFindingRequest', -'CreateNotificationConfigRequest', -'CreateSourceRequest', -'DeleteNotificationConfigRequest', -'Finding', -'Folder', -'GetNotificationConfigRequest', -'GetOrganizationSettingsRequest', -'GetSourceRequest', -'GroupAssetsRequest', -'GroupAssetsResponse', -'GroupFindingsRequest', -'GroupFindingsResponse', -'GroupResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFindingsRequest', -'ListFindingsResponse', -'ListNotificationConfigsRequest', -'ListNotificationConfigsResponse', -'ListSourcesRequest', -'ListSourcesResponse', -'NotificationConfig', -'NotificationMessage', -'OrganizationSettings', -'Resource', -'RunAssetDiscoveryRequest', -'RunAssetDiscoveryResponse', -'SecurityCenterClient', -'SecurityMarks', -'SetFindingStateRequest', -'Source', -'UpdateFindingRequest', -'UpdateNotificationConfigRequest', -'UpdateOrganizationSettingsRequest', -'UpdateSecurityMarksRequest', -'UpdateSourceRequest', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json deleted file mode 100644 index 734457b5..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/gapic_metadata.json +++ /dev/null @@ -1,253 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.securitycenter_v1p1beta1", - "protoPackage": "google.cloud.securitycenter.v1p1beta1", - "schema": "1.0", - "services": { - "SecurityCenter": { - "clients": { - "grpc": { - "libraryClient": "SecurityCenterClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SecurityCenterAsyncClient", - "rpcs": { - "CreateFinding": { - "methods": [ - "create_finding" - ] - }, - "CreateNotificationConfig": { - "methods": [ - "create_notification_config" - ] - }, - "CreateSource": { - "methods": [ - "create_source" - ] - }, - "DeleteNotificationConfig": { - "methods": [ - "delete_notification_config" - ] - }, - "GetIamPolicy": { - "methods": [ - "get_iam_policy" - ] - }, - "GetNotificationConfig": { - "methods": [ - "get_notification_config" - ] - }, - "GetOrganizationSettings": { - "methods": [ - "get_organization_settings" - ] - }, - "GetSource": { - "methods": [ - "get_source" - ] - }, - "GroupAssets": { - "methods": [ - "group_assets" - ] - }, - "GroupFindings": { - "methods": [ - "group_findings" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFindings": { - "methods": [ - "list_findings" - ] - }, - "ListNotificationConfigs": { - "methods": [ - "list_notification_configs" - ] - }, - "ListSources": { - "methods": [ - "list_sources" - ] - }, - "RunAssetDiscovery": { - "methods": [ - "run_asset_discovery" - ] - }, - "SetFindingState": { - "methods": [ - "set_finding_state" - ] - }, - "SetIamPolicy": { - "methods": [ - "set_iam_policy" - ] - }, - "TestIamPermissions": { - "methods": [ - "test_iam_permissions" - ] - }, - "UpdateFinding": { - "methods": [ - "update_finding" - ] - }, - "UpdateNotificationConfig": { - "methods": [ - "update_notification_config" - ] - }, - "UpdateOrganizationSettings": { - "methods": [ - "update_organization_settings" - ] - }, - "UpdateSecurityMarks": { - "methods": [ - "update_security_marks" - ] - }, - "UpdateSource": { - "methods": [ - "update_source" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/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/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py deleted file mode 100644 index fce6b0c5..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/__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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - 'SecurityCenterClient', - 'SecurityCenterAsyncClient', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py deleted file mode 100644 index b6f01b07..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ /dev/null @@ -1,2432 +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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1p1Beta1 APIs for Security Center service.""" - - _client: SecurityCenterClient - - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - - asset_path = staticmethod(SecurityCenterClient.asset_path) - parse_asset_path = staticmethod(SecurityCenterClient.parse_asset_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - parse_finding_path = staticmethod(SecurityCenterClient.parse_finding_path) - notification_config_path = staticmethod(SecurityCenterClient.notification_config_path) - parse_notification_config_path = staticmethod(SecurityCenterClient.parse_notification_config_path) - organization_settings_path = staticmethod(SecurityCenterClient.organization_settings_path) - parse_organization_settings_path = staticmethod(SecurityCenterClient.parse_organization_settings_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - parse_security_marks_path = staticmethod(SecurityCenterClient.parse_security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) - parse_source_path = staticmethod(SecurityCenterClient.parse_source_path) - topic_path = staticmethod(SecurityCenterClient.topic_path) - parse_topic_path = staticmethod(SecurityCenterClient.parse_topic_path) - common_billing_account_path = staticmethod(SecurityCenterClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SecurityCenterClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SecurityCenterClient.common_folder_path) - parse_common_folder_path = staticmethod(SecurityCenterClient.parse_common_folder_path) - common_organization_path = staticmethod(SecurityCenterClient.common_organization_path) - parse_common_organization_path = staticmethod(SecurityCenterClient.parse_common_organization_path) - common_project_path = staticmethod(SecurityCenterClient.common_project_path) - parse_common_project_path = staticmethod(SecurityCenterClient.parse_common_project_path) - common_location_path = staticmethod(SecurityCenterClient.common_location_path) - parse_common_location_path = staticmethod(SecurityCenterClient.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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_info.__func__(SecurityCenterAsyncClient, 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: - SecurityCenterAsyncClient: The constructed client. - """ - return SecurityCenterClient.from_service_account_file.__func__(SecurityCenterAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient)) - - def __init__(self, *, - credentials: ga_credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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, ~.SecurityCenterTransport]): 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 = SecurityCenterClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_source(self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``source`` 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.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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 = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # 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_source, - 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_finding(self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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 = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # 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_finding, - 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_notification_config(self, - request: securitycenter_service.CreateNotificationConfigRequest = None, - *, - parent: str = None, - config_id: str = None, - notification_config: gcs_notification_config.NotificationConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest`): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be between 1 and 128 characters, - and contains alphanumeric characters, - underscores or hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_config`` 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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_config]) - 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 = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # 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_notification_config, - 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 delete_notification_config(self, - request: securitycenter_service.DeleteNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a notification config. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest`): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.DeleteNotificationConfigRequest(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.delete_notification_config, - 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. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def get_iam_policy(self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.GetIamPolicyRequest(resource=resource, ) - - # 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_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(( - ("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_notification_config(self, - request: securitycenter_service.GetNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest`): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - - 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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.GetNotificationConfigRequest(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_notification_config, - 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_organization_settings(self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - 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.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings, - 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_source(self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - - 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.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.GetSourceRequest(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_source, - 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 group_assets(self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(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.group_assets, - 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=480.0, - ), - default_timeout=480.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.GroupAssetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings(self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` 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.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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 = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_findings, - 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=480.0, - ), - default_timeout=480.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.GroupFindingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: securitycenter_service.ListAssetsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest`): - The request object. Request message for listing assets. - parent (:class:`str`): - Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsAsyncPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.ListAssetsRequest(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_assets, - 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=480.0, - ), - default_timeout=480.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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings(self, - request: securitycenter_service.ListFindingsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest`): - The request object. Request message for listing - findings. - parent (:class:`str`): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.ListFindingsRequest(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_findings, - 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=480.0, - ), - default_timeout=480.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.ListFindingsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notification_configs(self, - request: securitycenter_service.ListNotificationConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest`): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs, - 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.ListNotificationConfigsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources(self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id], folders/[folder_id], - or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesAsyncPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.ListSourcesRequest(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_sources, - 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.ListSourcesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery(self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state(self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp_pb2.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding.State`): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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 = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # 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_finding_state, - 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 set_iam_policy(self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, ) - - # 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=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(( - ("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, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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.") - - # 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) - elif not request: - request = iam_policy_pb2.TestIamPermissionsRequest(resource=resource, permissions=permissions, ) - - # 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_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(( - ("resource", request.resource), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_finding(self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`google.cloud.securitycenter_v1p1beta1.types.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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 = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding, - 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(( - ("finding.name", request.finding.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_notification_config(self, - request: securitycenter_service.UpdateNotificationConfigRequest = None, - *, - notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest`): - The request object. Request message for updating a - notification config. - notification_config (:class:`google.cloud.securitycenter_v1p1beta1.types.NotificationConfig`): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields will be - updated. - - 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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([notification_config, 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 = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_config - 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_notification_config, - 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(( - ("notification_config.name", request.notification_config.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_organization_settings(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings`): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` 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.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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 = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # 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_organization_settings, - 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(( - ("organization_settings.name", request.organization_settings.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_source(self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`google.cloud.securitycenter_v1p1beta1.types.Source`): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating - the source resource. - If empty all mutable fields will be - updated. - - 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.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source, 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 = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - 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_source, - 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(( - ("source.name", request.source.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_security_marks(self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`google.cloud.securitycenter_v1p1beta1.types.SecurityMarks`): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v1p1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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 = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks, - default_timeout=480.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(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # Send the request. - response = await 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-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecurityCenterAsyncClient", -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py deleted file mode 100644 index a4cab349..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ /dev/null @@ -1,2600 +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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - def get_transport_class(cls, - label: str = None, - ) -> Type[SecurityCenterTransport]: - """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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1p1Beta1 APIs for Security Center service.""" - - @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 = "securitycenter.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: - SecurityCenterClient: 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: - SecurityCenterClient: 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) -> SecurityCenterTransport: - """Returns the transport used by the client instance. - - Returns: - SecurityCenterTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def asset_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified asset string.""" - return "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def finding_path(organization: str,source: str,finding: str,) -> str: - """Returns a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str,str]: - """Parses a finding path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str,notification_config: str,) -> str: - """Returns a fully-qualified notification_config string.""" - return "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str,str]: - """Parses a notification_config path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Returns a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format(organization=organization, ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str,str]: - """Parses a organization_settings path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/organizationSettings$", path) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str,asset: str,) -> str: - """Returns a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str,str]: - """Parses a security_marks path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", path) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str,source: str,) -> str: - """Returns a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str,str]: - """Parses a source path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)/sources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def topic_path(project: str,topic: str,) -> str: - """Returns a fully-qualified topic string.""" - return "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - - @staticmethod - def parse_topic_path(path: str) -> Dict[str,str]: - """Parses a topic path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/topics/(?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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SecurityCenterTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the security center 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, SecurityCenterTransport]): 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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, SecurityCenterTransport): - # transport is a SecurityCenterTransport instance. - if credentials or client_options.credentials_file: - 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: - 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=( - Transport == type(self).get_transport_class("grpc") - or Transport == type(self).get_transport_class("grpc_asyncio") - ), - ) - - def create_source(self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.CreateSourceRequest): - The request object. Request message for creating a - source. - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - - This corresponds to the ``source`` 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.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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 securitycenter_service.CreateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_source] - - # 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_finding(self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.CreateFindingRequest): - The request object. Request message for creating a - finding. - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (str): - Required. Unique identifier provided - by the client within the parent scope. - - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - - This corresponds to the ``finding`` 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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 securitycenter_service.CreateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # 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_notification_config(self, - request: securitycenter_service.CreateNotificationConfigRequest = None, - *, - parent: str = None, - config_id: str = None, - notification_config: gcs_notification_config.NotificationConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.CreateNotificationConfigRequest): - The request object. Request message for creating a - notification config. - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. Unique identifier provided - by the client within the parent scope. - It must be between 1 and 128 characters, - and contains alphanumeric characters, - underscores or hyphens only. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - - This corresponds to the ``notification_config`` 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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_config]) - 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 securitycenter_service.CreateNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateNotificationConfigRequest): - request = securitycenter_service.CreateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_notification_config] - - # 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 delete_notification_config(self, - request: securitycenter_service.DeleteNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a notification config. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.DeleteNotificationConfigRequest): - The request object. Request message for deleting a - notification config. - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - - 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. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.DeleteNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.DeleteNotificationConfigRequest): - request = securitycenter_service.DeleteNotificationConfigRequest(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.delete_notification_config] - - # 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. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def get_iam_policy(self, - request: iam_policy_pb2.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest): - The request object. Request message for `GetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.GetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.GetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_notification_config(self, - request: securitycenter_service.GetNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.GetNotificationConfigRequest): - The request object. Request message for getting a - notification config. - name (str): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - - 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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(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_notification_config] - - # 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_organization_settings(self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.GetOrganizationSettingsRequest): - The request object. Request message for getting - organization settings. - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - - 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.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetOrganizationSettingsRequest): - request = securitycenter_service.GetOrganizationSettingsRequest(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_organization_settings] - - # 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_source(self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.GetSourceRequest): - The request object. Request message for getting a - source. - name (str): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - - 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.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(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_source] - - # 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 group_assets(self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsRequest): - The request object. Request message for grouping by - assets. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.securitycenter_v1p1beta1.services.security_center.pagers.GroupAssetsPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # 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.GroupAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings(self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsRequest): - The request object. Request message for grouping by - findings. - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (str): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration - is set: - - - state_change - - This corresponds to the ``group_by`` 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.securitycenter_v1p1beta1.services.security_center.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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 securitycenter_service.GroupFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_findings] - - # 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.GroupFindingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: securitycenter_service.ListAssetsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.ListAssetsRequest): - The request object. Request message for listing assets. - parent (str): - Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListAssetsPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(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_assets] - - # 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.ListAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings(self, - request: securitycenter_service.ListFindingsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.ListFindingsRequest): - The request object. Request message for listing - findings. - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list - across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(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_findings] - - # 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.ListFindingsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notification_configs(self, - request: securitycenter_service.ListNotificationConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotificationConfigsPager: - r"""Lists notification configs. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): - The request object. Request message for listing - notification configs. - parent (str): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListNotificationConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListNotificationConfigsRequest): - request = securitycenter_service.ListNotificationConfigsRequest(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_notification_configs] - - # 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.ListNotificationConfigsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources(self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.ListSourcesRequest): - The request object. Request message for listing sources. - parent (str): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id], folders/[folder_id], - or projects/[project_id]". - - 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.securitycenter_v1p1beta1.services.security_center.pagers.ListSourcesPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListSourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(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_sources] - - # 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.ListSourcesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery(self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryRequest): - The request object. Request message for running asset - discovery for an organization. - parent (str): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - - 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.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse` - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.RunAssetDiscoveryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(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.run_asset_discovery] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state(self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp_pb2.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.SetFindingStateRequest): - The request object. Request message for updating a - finding's state. - name (str): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - Required. The desired State of the - finding. - - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the - updated state takes effect. - - This corresponds to the ``start_time`` 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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 securitycenter_service.SetFindingStateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_state] - - # 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 set_iam_policy(self, - request: iam_policy_pb2.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest): - The request object. Request message for `SetIamPolicy` - method. - resource (str): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` 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.iam.v1.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](\ https://cloud.google.com/iam/docs). - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.SetIamPolicyRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.SetIamPolicyRequest() - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # 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, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest): - The request object. Request message for - `TestIamPermissions` method. - resource (str): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (Sequence[str]): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - - This corresponds to the ``permissions`` 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.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: - Response message for TestIamPermissions method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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.') - - if isinstance(request, dict): - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - elif not request: - # Null request, just make one. - request = iam_policy_pb2.TestIamPermissionsRequest() - if resource is not None: - request.resource = resource - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_finding(self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.UpdateFindingRequest): - The request object. Request message for updating or - creating a finding. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - - 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.securitycenter_v1p1beta1.types.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, 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 securitycenter_service.UpdateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("finding.name", request.finding.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_notification_config(self, - request: securitycenter_service.UpdateNotificationConfigRequest = None, - *, - notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.UpdateNotificationConfigRequest): - The request object. Request message for updating a - notification config. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config to - update. - - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the notification config. - If empty all mutable fields will be - updated. - - 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.securitycenter_v1p1beta1.types.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([notification_config, 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 securitycenter_service.UpdateNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateNotificationConfigRequest): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if notification_config is not None: - request.notification_config = notification_config - 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_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("notification_config.name", request.notification_config.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_organization_settings(self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.UpdateOrganizationSettingsRequest): - The request object. Request message for updating an - organization's settings. - organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): - Required. The organization settings - resource to update. - - This corresponds to the ``organization_settings`` 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.securitycenter_v1p1beta1.types.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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 securitycenter_service.UpdateOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateOrganizationSettingsRequest): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_organization_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("organization_settings.name", request.organization_settings.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_source(self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.UpdateSourceRequest): - The request object. Request message for updating a - source. - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The source resource to - update. - - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating - the source resource. - If empty all mutable fields will be - updated. - - 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.securitycenter_v1p1beta1.types.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source, 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 securitycenter_service.UpdateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if source is not None: - request.source = source - 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("source.name", request.source.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_security_marks(self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - update_mask: field_mask_pb2.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (google.cloud.securitycenter_v1p1beta1.types.UpdateSecurityMarksRequest): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Required. The security marks resource - to update. - - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - - 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.securitycenter_v1p1beta1.types.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, 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 securitycenter_service.UpdateSecurityMarksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("security_marks.name", request.security_marks.name), - )), - ) - - # 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-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "SecurityCenterClient", -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py deleted file mode 100644 index be794371..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py +++ /dev/null @@ -1,752 +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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` - 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[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: - 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) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse` - 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[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupAssetsResponse): - 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 = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: - 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) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` - 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[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: - 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) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse` - 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[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - 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.securitycenter_v1p1beta1.types.GroupFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.GroupFindingsResponse): - 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 = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: - 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) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` - 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[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: - 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) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse` - 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[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse): - 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 = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: - 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) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` - 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[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse): - 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 = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: - 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) -> Iterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse` - 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[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListFindingsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse): - 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 = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: - 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) -> AsyncIterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` - 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[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListNotificationConfigsResponse]: - 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) -> Iterable[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse` - 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[securitycenter_service.ListNotificationConfigsResponse]], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - 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.securitycenter_v1p1beta1.types.ListNotificationConfigsRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListNotificationConfigsResponse): - 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 = securitycenter_service.ListNotificationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListNotificationConfigsResponse]: - 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) -> AsyncIterable[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` - 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[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1p1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: - 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) -> Iterable[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse` - 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[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - 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.securitycenter_v1p1beta1.types.ListSourcesRequest): - The initial request object. - response (google.cloud.securitycenter_v1p1beta1.types.ListSourcesResponse): - 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 = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: - 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) -> AsyncIterable[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - 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/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py deleted file mode 100644 index 8bdaf713..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/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 SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry['grpc'] = SecurityCenterGrpcTransport -_transport_registry['grpc_asyncio'] = SecurityCenterGrpcAsyncIOTransport - -__all__ = ( - 'SecurityCenterTransport', - 'SecurityCenterGrpcTransport', - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py deleted file mode 100644 index 21af4750..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ /dev/null @@ -1,572 +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 packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-securitycenter', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'securitycenter.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 = self._get_scopes_kwargs(self._host, 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 is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_source: gapic_v1.method.wrap_method( - self.create_source, - default_timeout=60.0, - client_info=client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - 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_notification_config: gapic_v1.method.wrap_method( - self.get_notification_config, - 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_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - 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_source: gapic_v1.method.wrap_method( - self.get_source, - 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.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_findings, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - 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=480.0, - ), - default_timeout=480.0, - client_info=client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_configs, - 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_sources: gapic_v1.method.wrap_method( - self.list_sources, - 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.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, - default_timeout=60.0, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=60.0, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - 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_finding: gapic_v1.method.wrap_method( - self.update_finding, - default_timeout=60.0, - client_info=client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, - default_timeout=60.0, - client_info=client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - 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 get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Union[ - notification_config.NotificationConfig, - Awaitable[notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Union[ - organization_settings.OrganizationSettings, - Awaitable[organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Union[ - source.Source, - Awaitable[source.Source] - ]]: - raise NotImplementedError() - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Union[ - securitycenter_service.GroupAssetsResponse, - Awaitable[securitycenter_service.GroupAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Union[ - securitycenter_service.GroupFindingsResponse, - Awaitable[securitycenter_service.GroupFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Union[ - securitycenter_service.ListAssetsResponse, - Awaitable[securitycenter_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Union[ - securitycenter_service.ListFindingsResponse, - Awaitable[securitycenter_service.ListFindingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Union[ - securitycenter_service.ListNotificationConfigsResponse, - Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Union[ - securitycenter_service.ListSourcesResponse, - Awaitable[securitycenter_service.ListSourcesResponse] - ]]: - raise NotImplementedError() - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Union[ - finding.Finding, - Awaitable[finding.Finding] - ]]: - 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 test_iam_permissions(self) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse] - ]]: - raise NotImplementedError() - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Union[ - gcs_finding.Finding, - Awaitable[gcs_finding.Finding] - ]]: - raise NotImplementedError() - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Union[ - gcs_notification_config.NotificationConfig, - Awaitable[gcs_notification_config.NotificationConfig] - ]]: - raise NotImplementedError() - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Union[ - gcs_organization_settings.OrganizationSettings, - Awaitable[gcs_organization_settings.OrganizationSettings] - ]]: - raise NotImplementedError() - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Union[ - gcs_source.Source, - Awaitable[gcs_source.Source] - ]]: - raise NotImplementedError() - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Union[ - gcs_security_marks.SecurityMarks, - Awaitable[gcs_security_marks.SecurityMarks] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'SecurityCenterTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py deleted file mode 100644 index 1f374822..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,877 +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 # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # 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 - -import grpc # type: ignore - -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center service. - - 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 = 'securitycenter.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 applicatin 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 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 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] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'securitycenter.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 operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_notification_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - operations_pb2.Operation]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.Finding]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - -__all__ = ( - 'SecurityCenterGrpcTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index f7337a74..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,881 +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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import SecurityCenterTransport, DEFAULT_CLIENT_INFO -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center service. - - 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 = 'securitycenter.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 = 'securitycenter.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 applicatin 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 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 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] = {} - self._operations_client = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_source(self) -> Callable[ - [securitycenter_service.CreateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['create_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource', - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['create_source'] - - @property - def create_finding(self) -> Callable[ - [securitycenter_service.CreateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['create_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding', - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['create_finding'] - - @property - def create_notification_config(self) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['create_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig', - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['create_notification_config'] - - @property - def delete_notification_config(self) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_notification_config' not in self._stubs: - self._stubs['delete_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig', - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_notification_config'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy', - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['get_iam_policy'] - - @property - def get_notification_config(self) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig]]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['get_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig', - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs['get_notification_config'] - - @property - def get_organization_settings(self) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings]]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['get_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings', - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['get_organization_settings'] - - @property - def get_source(self) -> Callable[ - [securitycenter_service.GetSourceRequest], - Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['get_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource', - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs['get_source'] - - @property - def group_assets(self) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse]]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_assets' not in self._stubs: - self._stubs['group_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets', - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs['group_assets'] - - @property - def group_findings(self) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse]]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings, - /v1/folders/{folder_id}/sources/-/findings, - /v1/projects/{project_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'group_findings' not in self._stubs: - self._stubs['group_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings', - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs['group_findings'] - - @property - def list_assets(self) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets', - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def list_findings(self) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse]]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_findings' not in self._stubs: - self._stubs['list_findings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings', - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs['list_findings'] - - @property - def list_notification_configs(self) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse]]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_configs' not in self._stubs: - self._stubs['list_notification_configs'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs', - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs['list_notification_configs'] - - @property - def list_sources(self) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse]]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_sources' not in self._stubs: - self._stubs['list_sources'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources', - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs['list_sources'] - - @property - def run_asset_discovery(self) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'run_asset_discovery' not in self._stubs: - self._stubs['run_asset_discovery'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery', - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['run_asset_discovery'] - - @property - def set_finding_state(self) -> Callable[ - [securitycenter_service.SetFindingStateRequest], - Awaitable[finding.Finding]]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding_state' not in self._stubs: - self._stubs['set_finding_state'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState', - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs['set_finding_state'] - - @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 access control policy on the specified - Source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy', - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs['set_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. - - Returns the permissions that a caller has on the - specified source. - - 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.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions', - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs['test_iam_permissions'] - - @property - def update_finding(self) -> Callable[ - [securitycenter_service.UpdateFindingRequest], - Awaitable[gcs_finding.Finding]]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - Awaitable[~.Finding]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_finding' not in self._stubs: - self._stubs['update_finding'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding', - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs['update_finding'] - - @property - def update_notification_config(self) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig]]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_notification_config' not in self._stubs: - self._stubs['update_notification_config'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig', - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs['update_notification_config'] - - @property - def update_organization_settings(self) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings]]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_organization_settings' not in self._stubs: - self._stubs['update_organization_settings'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings', - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs['update_organization_settings'] - - @property - def update_source(self) -> Callable[ - [securitycenter_service.UpdateSourceRequest], - Awaitable[gcs_source.Source]]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_source' not in self._stubs: - self._stubs['update_source'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource', - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs['update_source'] - - @property - def update_security_marks(self) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks]]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_security_marks' not in self._stubs: - self._stubs['update_security_marks'] = self.grpc_channel.unary_unary( - '/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks', - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs['update_security_marks'] - - -__all__ = ( - 'SecurityCenterGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py deleted file mode 100644 index f490e7f6..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/__init__.py +++ /dev/null @@ -1,114 +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 .asset import ( - Asset, -) -from .finding import ( - Finding, -) -from .folder import ( - Folder, -) -from .notification_config import ( - NotificationConfig, -) -from .notification_message import ( - NotificationMessage, -) -from .organization_settings import ( - OrganizationSettings, -) -from .resource import ( - Resource, -) -from .run_asset_discovery_response import ( - RunAssetDiscoveryResponse, -) -from .security_marks import ( - SecurityMarks, -) -from .securitycenter_service import ( - CreateFindingRequest, - CreateNotificationConfigRequest, - CreateSourceRequest, - DeleteNotificationConfigRequest, - GetNotificationConfigRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, - RunAssetDiscoveryRequest, - SetFindingStateRequest, - UpdateFindingRequest, - UpdateNotificationConfigRequest, - UpdateOrganizationSettingsRequest, - UpdateSecurityMarksRequest, - UpdateSourceRequest, -) -from .source import ( - Source, -) - -__all__ = ( - 'Asset', - 'Finding', - 'Folder', - 'NotificationConfig', - 'NotificationMessage', - 'OrganizationSettings', - 'Resource', - 'RunAssetDiscoveryResponse', - 'SecurityMarks', - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'RunAssetDiscoveryRequest', - 'SetFindingStateRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSecurityMarksRequest', - 'UpdateSourceRequest', - 'Source', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py deleted file mode 100644 index 8617389d..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/asset.py +++ /dev/null @@ -1,223 +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.securitycenter_v1p1beta1.types import folder -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Asset', - }, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (google.cloud.securitycenter_v1p1beta1.types.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.Asset.ResourcePropertiesEntry]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the asset was last updated - or added in Cloud SCC. - iam_policy (google.cloud.securitycenter_v1p1beta1.types.Asset.IamPolicy): - Cloud IAM Policy information associated with - the Google Cloud resource described by the - Security Command Center asset. This information - is managed and defined by the Google Cloud - resource and cannot be modified by the user. - canonical_name (str): - The canonical name of the resource. It's either - "organizations/{organization_id}/assets/{asset_id}", - "folders/{folder_id}/assets/{asset_id}" or - "projects/{project_number}/assets/{asset_id}", depending on - the closest CRM ancestor of the resource. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - The full resource name of the Google Cloud resource this - asset represents. This field is immutable after create time. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (Sequence[str]): - Owners of the Google Cloud resource. - resource_display_name (str): - The user defined display name for this - resource. - resource_parent_display_name (str): - The user defined display name for the parent - of this resource. - resource_project_display_name (str): - The user defined display name for the project - of this resource. - folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - resource_name = proto.Field( - proto.STRING, - number=1, - ) - resource_type = proto.Field( - proto.STRING, - number=2, - ) - resource_parent = proto.Field( - proto.STRING, - number=3, - ) - resource_project = proto.Field( - proto.STRING, - number=4, - ) - resource_owners = proto.RepeatedField( - proto.STRING, - number=5, - ) - resource_display_name = proto.Field( - proto.STRING, - number=6, - ) - resource_parent_display_name = proto.Field( - proto.STRING, - number=7, - ) - resource_project_display_name = proto.Field( - proto.STRING, - number=8, - ) - folders = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - class IamPolicy(proto.Message): - r"""Cloud IAM Policy information associated with the Google Cloud - resource described by the Security Command Center asset. This - information is managed and defined by the Google Cloud resource - and cannot be modified by the user. - - Attributes: - policy_blob (str): - The JSON representation of the Policy - associated with the asset. See - https://cloud.google.com/iam/docs/reference/rest/v1/Policy - for format details. - """ - - policy_blob = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - security_center_properties = proto.Field( - proto.MESSAGE, - number=2, - message=SecurityCenterProperties, - ) - resource_properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - create_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - iam_policy = proto.Field( - proto.MESSAGE, - number=11, - message=IamPolicy, - ) - canonical_name = proto.Field( - proto.STRING, - number=13, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py deleted file mode 100644 index 0c2b4ff0..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/finding.py +++ /dev/null @@ -1,180 +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.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Finding', - }, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - A finding is a record of assessment data (security, risk, health - or privacy) ingested into Security Command Center for - presentation, notification, analysis, policy testing, and - enforcement. For example, an XSS vulnerability in an App Engine - application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.Finding.SourcePropertiesEntry]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the event took place, or - when an update to the finding occurred. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. If the finding - were to be resolved afterward, this time would - reflect when the finding was resolved. Must not - be set to a value greater than the current - timestamp. - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the finding was created in - Security Command Center. - severity (google.cloud.securitycenter_v1p1beta1.types.Finding.Severity): - The severity of the finding. This field is - managed by the source that writes the finding. - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}" - or - "projects/{project_number}/sources/{source_id}/findings/{finding_id}", - depending on the closest CRM ancestor of the resource - associated with the finding. - """ - class State(proto.Enum): - r"""The state of the finding.""" - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - class Severity(proto.Enum): - r"""The severity of the finding. This field is managed by the - source that writes the finding. - """ - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - name = proto.Field( - proto.STRING, - number=1, - ) - parent = proto.Field( - proto.STRING, - number=2, - ) - resource_name = proto.Field( - proto.STRING, - number=3, - ) - state = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - category = proto.Field( - proto.STRING, - number=5, - ) - external_uri = proto.Field( - proto.STRING, - number=6, - ) - source_properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=7, - message=struct_pb2.Value, - ) - security_marks = proto.Field( - proto.MESSAGE, - number=8, - message=gcs_security_marks.SecurityMarks, - ) - event_time = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - create_time = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - severity = proto.Field( - proto.ENUM, - number=13, - enum=Severity, - ) - canonical_name = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py deleted file mode 100644 index 90b8f72c..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/folder.py +++ /dev/null @@ -1,50 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Folder', - }, -) - - -class Folder(proto.Message): - r"""Message that contains the resource name and display name of a - folder resource. - - Attributes: - resource_folder (str): - Full resource name of this folder. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_folder_display_name (str): - The user defined display name for this - folder. - """ - - resource_folder = proto.Field( - proto.STRING, - number=1, - ) - resource_folder_display_name = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py deleted file mode 100644 index e314b944..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_config.py +++ /dev/null @@ -1,126 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'NotificationConfig', - }, -) - - -class NotificationConfig(proto.Message): - r"""Security Command Center notification configs. - A notification config is a Security Command Center resource that - contains the configuration to send notifications for - create/update events of findings, assets and etc. - - Attributes: - name (str): - The relative resource name of this notification config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/notificationConfigs/notify_public_bucket". - description (str): - The description of the notification config - (max of 1024 characters). - event_type (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.EventType): - The type of events the config is for, e.g. - FINDING. - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - """ - class EventType(proto.Enum): - r"""The type of events.""" - EVENT_TYPE_UNSPECIFIED = 0 - FINDING = 1 - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter = proto.Field( - proto.STRING, - number=1, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - description = proto.Field( - proto.STRING, - number=2, - ) - event_type = proto.Field( - proto.ENUM, - number=3, - enum=EventType, - ) - pubsub_topic = proto.Field( - proto.STRING, - number=4, - ) - service_account = proto.Field( - proto.STRING, - number=5, - ) - streaming_config = proto.Field( - proto.MESSAGE, - number=6, - oneof='notify_config', - message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py deleted file mode 100644 index ad874607..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/notification_message.py +++ /dev/null @@ -1,60 +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.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'NotificationMessage', - }, -) - - -class NotificationMessage(proto.Message): - r"""Security Command Center's Notification - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - If it's a Finding based notification config, - this field will be populated. - resource (google.cloud.securitycenter_v1p1beta1.types.Resource): - The Cloud resource tied to the notification. - """ - - notification_config_name = proto.Field( - proto.STRING, - number=1, - ) - finding = proto.Field( - proto.MESSAGE, - number=2, - oneof='event', - message=gcs_finding.Finding, - ) - resource = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_resource.Resource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py deleted file mode 100644 index 0626dfa8..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py +++ /dev/null @@ -1,104 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'OrganizationSettings', - }, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - Attributes: - project_ids (Sequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - folder_ids (Sequence[str]): - The folder ids to use for filtering asset - discovery. It consists of only digits, e.g., - 756619654966. - """ - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids = proto.RepeatedField( - proto.STRING, - number=1, - ) - inclusion_mode = proto.Field( - proto.ENUM, - number=2, - enum='OrganizationSettings.AssetDiscoveryConfig.InclusionMode', - ) - folder_ids = proto.RepeatedField( - proto.STRING, - number=3, - ) - - name = proto.Field( - proto.STRING, - number=1, - ) - enable_asset_discovery = proto.Field( - proto.BOOL, - number=2, - ) - asset_discovery_config = proto.Field( - proto.MESSAGE, - number=3, - message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py deleted file mode 100644 index eb56efe2..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/resource.py +++ /dev/null @@ -1,80 +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.securitycenter_v1p1beta1.types import folder - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Resource', - }, -) - - -class Resource(proto.Message): - r"""Information related to the Google Cloud resource. - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Output only. Contains a Folder message for - each folder in the assets ancestry. The first - folder is the deepest nested folder, and the - last folder is the folder directly under the - Organization. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - project = proto.Field( - proto.STRING, - number=2, - ) - project_display_name = proto.Field( - proto.STRING, - number=3, - ) - parent = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name = proto.Field( - proto.STRING, - number=5, - ) - folders = proto.RepeatedField( - proto.MESSAGE, - number=7, - message=folder.Folder, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py deleted file mode 100644 index a8f0d526..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py +++ /dev/null @@ -1,57 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'RunAssetDiscoveryResponse', - }, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - Attributes: - state (google.cloud.securitycenter_v1p1beta1.types.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (google.protobuf.duration_pb2.Duration): - The duration between asset discovery run - start and end - """ - class State(proto.Enum): - r"""The state of an asset discovery run.""" - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py deleted file mode 100644 index bb9b46e5..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/security_marks.py +++ /dev/null @@ -1,76 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'SecurityMarks', - }, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[google.cloud.securitycenter_v1p1beta1.types.SecurityMarks.MarksEntry]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - canonical_name (str): - The canonical name of the marks. Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "folders/{folder_id}/assets/{asset_id}/securityMarks" - "projects/{project_number}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks" - "projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - marks = proto.MapField( - proto.STRING, - proto.STRING, - number=2, - ) - canonical_name = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py deleted file mode 100644 index b32dabc4..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py +++ /dev/null @@ -1,1581 +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.securitycenter_v1p1beta1.types import asset as gcs_asset -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import folder -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'CreateFindingRequest', - 'CreateNotificationConfigRequest', - 'CreateSourceRequest', - 'DeleteNotificationConfigRequest', - 'GetNotificationConfigRequest', - 'GetOrganizationSettingsRequest', - 'GetSourceRequest', - 'GroupAssetsRequest', - 'GroupAssetsResponse', - 'GroupFindingsRequest', - 'GroupFindingsResponse', - 'GroupResult', - 'ListNotificationConfigsRequest', - 'ListNotificationConfigsResponse', - 'ListSourcesRequest', - 'ListSourcesResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFindingsRequest', - 'ListFindingsResponse', - 'SetFindingStateRequest', - 'RunAssetDiscoveryRequest', - 'UpdateFindingRequest', - 'UpdateNotificationConfigRequest', - 'UpdateOrganizationSettingsRequest', - 'UpdateSourceRequest', - 'UpdateSecurityMarksRequest', - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - finding_id = proto.Field( - proto.STRING, - number=2, - ) - finding = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_finding.Finding, - ) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - config_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - between 1 and 128 characters, and contains - alphanumeric characters, underscores or hyphens - only. - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - config_id = proto.Field( - proto.STRING, - number=2, - ) - notification_config = proto.Field( - proto.MESSAGE, - number=3, - message=gcs_notification_config.NotificationConfig, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - source = proto.Field( - proto.MESSAGE, - number=2, - message=gcs_source.Source, - ) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - Attributes: - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - Attributes: - name (str): - Required. Name of the notification config to get. Its format - is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id], folders/[folder_id], or - projects/[project_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_name_display_name: - ``=``, ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" property is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - group_by = proto.Field( - proto.STRING, - number=3, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=4, - message=duration_pb2.Duration, - ) - read_time = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - page_token = proto.Field( - proto.STRING, - number=7, - ) - page_size = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - Attributes: - group_by_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]", - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]. To groupBy across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/-, or - projects/{project_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - - severity: ``=``, ``:`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state_change``). The string value - should follow SQL syntax: comma separated list of fields. - For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - severity - - The following fields are supported when compare_duration is - set: - - - state_change - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the GroupResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - group_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - page_token = proto.Field( - proto.STRING, - number=7, - ) - page_size = proto.Field( - proto.INT32, - number=8, - ) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - Attributes: - group_by_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GroupResult', - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (Sequence[google.cloud.securitycenter_v1p1beta1.types.GroupResult.PropertiesEntry]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message=struct_pb2.Value, - ) - count = proto.Field( - proto.INT64, - number=2, - ) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - Attributes: - parent (str): - Required. Name of the organization to list notification - configs. Its format is "organizations/[organization_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - - -class ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - Attributes: - notification_configs (Sequence[google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - page_token = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=7, - ) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - Attributes: - sources (Sequence[google.cloud.securitycenter_v1p1beta1.types.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - next_page_token = proto.Field( - proto.STRING, - number=2, - ) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id], - folders/[folder_id], or projects/[project_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following are the allowed field and operator - combinations: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - - The following fields are supported: name update_time - resource_properties security_marks.marks - security_center_properties.resource_name - security_center_properties.resource_display_name - security_center_properties.resource_parent - security_center_properties.resource_parent_display_name - security_center_properties.resource_project - security_center_properties.resource_project_display_name - security_center_properties.resource_type - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListAssetsResult's - "state_change" attribute is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the ListAssetsResult - fields to be listed in the response. - An empty field mask will list all fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - order_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - page_size = proto.Field( - proto.INT32, - number=9, - ) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - Attributes: - list_assets_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - Attributes: - asset (google.cloud.securitycenter_v1p1beta1.types.Asset): - Asset matching the search request. - state_change (google.cloud.securitycenter_v1p1beta1.types.ListAssetsResponse.ListAssetsResult.StateChange): - State change of the asset between the points - in time. - """ - class StateChange(proto.Enum): - r"""The change in state of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state change will be: - UNUSED - """ - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - asset = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_asset.Asset, - ) - state_change = proto.Field( - proto.ENUM, - number=2, - enum='ListAssetsResponse.ListAssetsResult.StateChange', - ) - - @property - def raw_page(self): - return self - - list_assets_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListAssetsResult, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id], - folders/[folder_id]/sources/[source_id], or - projects/[project_id]/sources/[source_id]". To list across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/-, - folders/{folder_id}/sources/- or - projects/{projects_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - - severity: ``=``, ``:`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - security_marks.marks: ``=``, ``:`` source_properties: ``=``, - ``:``, ``>``, ``<``, ``>=``, ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time source_properties - security_marks.marks - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (google.protobuf.duration_pb2.Duration): - When compare_duration is set, the ListFindingsResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added in any state during - the compare_duration period of time that precedes the - read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - field_mask (google.protobuf.field_mask_pb2.FieldMask): - A field mask to specify the Finding fields to - be listed in the response. An empty field mask - will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - filter = proto.Field( - proto.STRING, - number=2, - ) - order_by = proto.Field( - proto.STRING, - number=3, - ) - read_time = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - compare_duration = proto.Field( - proto.MESSAGE, - number=5, - message=duration_pb2.Duration, - ) - field_mask = proto.Field( - proto.MESSAGE, - number=7, - message=field_mask_pb2.FieldMask, - ) - page_token = proto.Field( - proto.STRING, - number=8, - ) - page_size = proto.Field( - proto.INT32, - number=9, - ) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - Attributes: - list_findings_results (Sequence[google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding and its StateChange. - Attributes: - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Finding matching the search request. - state_change (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.StateChange): - State change of the finding between the - points in time. - resource (google.cloud.securitycenter_v1p1beta1.types.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - class StateChange(proto.Enum): - r"""The change in state of the finding. - - When querying across two points in time this describes the change in - the finding between the two points: CHANGED, UNCHANGED, ADDED, or - REMOVED. Findings can not be deleted, so REMOVED implies that the - finding at timestamp does not match the filter specified, but it did - at timestamp - compare_duration. If there was no compare_duration - supplied in the request the state change will be: UNUSED - """ - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project_name (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent_name (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - folders (Sequence[google.cloud.securitycenter_v1p1beta1.types.Folder]): - Contains a Folder message for each folder in - the assets ancestry. The first folder is the - deepest nested folder, and the last folder is - the folder directly under the Organization. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - project_name = proto.Field( - proto.STRING, - number=2, - ) - project_display_name = proto.Field( - proto.STRING, - number=3, - ) - parent_name = proto.Field( - proto.STRING, - number=4, - ) - parent_display_name = proto.Field( - proto.STRING, - number=5, - ) - folders = proto.RepeatedField( - proto.MESSAGE, - number=10, - message=folder.Folder, - ) - - finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - state_change = proto.Field( - proto.ENUM, - number=2, - enum='ListFindingsResponse.ListFindingsResult.StateChange', - ) - resource = proto.Field( - proto.MESSAGE, - number=3, - message='ListFindingsResponse.ListFindingsResult.Resource', - ) - - @property - def raw_page(self): - return self - - list_findings_results = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=ListFindingsResult, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - next_page_token = proto.Field( - proto.STRING, - number=3, - ) - total_size = proto.Field( - proto.INT32, - number=4, - ) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (google.cloud.securitycenter_v1p1beta1.types.Finding.State): - Required. The desired State of the finding. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - state = proto.Field( - proto.ENUM, - number=2, - enum=gcs_finding.Finding.State, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - Attributes: - finding (google.cloud.securitycenter_v1p1beta1.types.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_finding.Finding, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - Attributes: - notification_config (google.cloud.securitycenter_v1p1beta1.types.NotificationConfig): - Required. The notification config to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_notification_config.NotificationConfig, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - Attributes: - organization_settings (google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the - settings resource. - If empty all mutable fields will be updated. - """ - - organization_settings = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_organization_settings.OrganizationSettings, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - Attributes: - source (google.cloud.securitycenter_v1p1beta1.types.Source): - Required. The source resource to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_source.Source, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - Attributes: - security_marks (google.cloud.securitycenter_v1p1beta1.types.SecurityMarks): - Required. The security marks resource to - update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time at which the updated SecurityMarks - take effect. If not set uses current server - time. Updates will be applied to the - SecurityMarks that are active immediately - preceding this time. - """ - - security_marks = proto.Field( - proto.MESSAGE, - number=1, - message=gcs_security_marks.SecurityMarks, - ) - update_mask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - start_time = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py b/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py deleted file mode 100644 index d8885041..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/securitycenter_v1p1beta1/types/source.py +++ /dev/null @@ -1,83 +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 - - -__protobuf__ = proto.module( - package='google.cloud.securitycenter.v1p1beta1', - manifest={ - 'Source', - }, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, etc. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and - outdated/insecure libraries.". - canonical_name (str): - The canonical name of the finding. It's either - "organizations/{organization_id}/sources/{source_id}", - "folders/{folder_id}/sources/{source_id}" or - "projects/{project_number}/sources/{source_id}", depending - on the closest CRM ancestor of the resource associated with - the finding. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - display_name = proto.Field( - proto.STRING, - number=2, - ) - description = proto.Field( - proto.STRING, - number=3, - ) - canonical_name = proto.Field( - proto.STRING, - number=14, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/mypy.ini b/owl-bot-staging/v1p1beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1p1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1p1beta1/noxfile.py b/owl-bot-staging/v1p1beta1/noxfile.py deleted file mode 100644 index 29b101a6..00000000 --- a/owl-bot-staging/v1p1beta1/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']) -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/securitycenter_v1p1beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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']) -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.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) diff --git a/owl-bot-staging/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py b/owl-bot-staging/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py deleted file mode 100644 index 43acd75e..00000000 --- a/owl-bot-staging/v1p1beta1/scripts/fixup_securitycenter_v1p1beta1_keywords.py +++ /dev/null @@ -1,198 +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 securitycenterCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_finding': ('parent', 'finding_id', 'finding', ), - 'create_notification_config': ('parent', 'config_id', 'notification_config', ), - 'create_source': ('parent', 'source', ), - 'delete_notification_config': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_notification_config': ('name', ), - 'get_organization_settings': ('name', ), - 'get_source': ('name', ), - 'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ), - 'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'compare_duration', 'page_token', 'page_size', ), - 'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ), - 'list_notification_configs': ('parent', 'page_token', 'page_size', ), - 'list_sources': ('parent', 'page_token', 'page_size', ), - 'run_asset_discovery': ('parent', ), - 'set_finding_state': ('name', 'state', 'start_time', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_finding': ('finding', 'update_mask', ), - 'update_notification_config': ('notification_config', 'update_mask', ), - 'update_organization_settings': ('organization_settings', 'update_mask', ), - 'update_security_marks': ('security_marks', 'update_mask', 'start_time', ), - 'update_source': ('source', 'update_mask', ), - } - - 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: not a.keyword.value 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=securitycenterCallTransformer(), -): - """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 securitycenter 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/v1p1beta1/setup.py b/owl-bot-staging/v1p1beta1/setup.py deleted file mode 100644 index 0653f115..00000000 --- a/owl-bot-staging/v1p1beta1/setup.py +++ /dev/null @@ -1,54 +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-securitycenter', - 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.27.0, < 3.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', '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/v1p1beta1/tests/__init__.py b/owl-bot-staging/v1p1beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/__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/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py deleted file mode 100644 index 18b18e7a..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py +++ /dev/null @@ -1,7809 +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 packaging.version - -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 future -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 operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.securitycenter_v1p1beta1.services.security_center import SecurityCenterAsyncClient -from google.cloud.securitycenter_v1p1beta1.services.security_center import SecurityCenterClient -from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.services.security_center import transports -from google.cloud.securitycenter_v1p1beta1.services.security_center.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import notification_config as gcs_notification_config -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import organization_settings as gcs_organization_settings -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -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.longrunning import operations_pb2 -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 struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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 SecurityCenterClient._get_default_mtls_endpoint(None) is None - assert SecurityCenterClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SecurityCenterClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [ - SecurityCenterClient, - SecurityCenterAsyncClient, -]) -def test_security_center_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 == 'securitycenter.googleapis.com:443' - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SecurityCenterGrpcTransport, "grpc"), - (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_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", [ - SecurityCenterClient, - SecurityCenterAsyncClient, -]) -def test_security_center_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 == 'securitycenter.googleapis.com:443' - - -def test_security_center_client_get_transport_class(): - transport = SecurityCenterClient.get_transport_class() - available_transports = [ - transports.SecurityCenterGrpcTransport, - ] - assert transport in available_transports - - transport = SecurityCenterClient.get_transport_class("grpc") - assert transport == transports.SecurityCenterGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -def test_security_center_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(SecurityCenterClient, '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(SecurityCenterClient, '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(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() - 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() - 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() - - # 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() - - # 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) - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "true"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc", "false"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio", "false"), -]) -@mock.patch.object(SecurityCenterClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterClient)) -@mock.patch.object(SecurityCenterAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityCenterAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_security_center_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) - - 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() - 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() - 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,transport_class,transport_name", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_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) - 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", [ - (SecurityCenterClient, transports.SecurityCenterGrpcTransport, "grpc"), - (SecurityCenterAsyncClient, transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_security_center_client_client_options_credentials_file(client_class, transport_class, transport_name): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options) - 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_security_center_client_client_options_from_dict(): - with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SecurityCenterClient( - 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, - ) - - -def test_create_source(transport: str = 'grpc', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_create_source_from_dict(): - test_create_source(request_type=dict) - - -def test_create_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.create_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - -@pytest.mark.asyncio -async def test_create_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.create_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_source_async_from_dict(): - await test_create_source_async(request_type=dict) - - -def test_create_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.create_source(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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateSourceRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.create_source(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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_source( - parent='parent_value', - source=gcs_source.Source(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] - assert args[0].parent == 'parent_value' - assert args[0].source == gcs_source.Source(name='name_value') - - -def test_create_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_source( - parent='parent_value', - source=gcs_source.Source(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] - assert args[0].parent == 'parent_value' - assert args[0].source == gcs_source.Source(name='name_value') - - -@pytest.mark.asyncio -async def test_create_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.CreateSourceRequest(), - parent='parent_value', - source=gcs_source.Source(name='name_value'), - ) - - -def test_create_finding(transport: str = 'grpc', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_create_finding_from_dict(): - test_create_finding(request_type=dict) - - -def test_create_finding_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 = SecurityCenterClient( - 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_finding), - '__call__') as call: - client.create_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - -@pytest.mark.asyncio -async def test_create_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.create_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_create_finding_async_from_dict(): - await test_create_finding_async(request_type=dict) - - -def test_create_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.create_finding(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_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateFindingRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.create_finding(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_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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] - assert args[0].parent == 'parent_value' - assert args[0].finding_id == 'finding_id_value' - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -def test_create_finding_flattened_error(): - client = SecurityCenterClient( - 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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_finding( - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(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] - assert args[0].parent == 'parent_value' - assert args[0].finding_id == 'finding_id_value' - assert args[0].finding == gcs_finding.Finding(name='name_value') - - -@pytest.mark.asyncio -async def test_create_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_finding( - securitycenter_service.CreateFindingRequest(), - parent='parent_value', - finding_id='finding_id_value', - finding=gcs_finding.Finding(name='name_value'), - ) - - -def test_create_notification_config(transport: str = 'grpc', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - streaming_config=gcs_notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), - ) - response = client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_create_notification_config_from_dict(): - test_create_notification_config(request_type=dict) - - -def test_create_notification_config_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 = SecurityCenterClient( - 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_notification_config), - '__call__') as call: - client.create_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - -@pytest.mark.asyncio -async def test_create_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.CreateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.create_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.CreateNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_create_notification_config_async_from_dict(): - await test_create_notification_config_async(request_type=dict) - - -def test_create_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.create_notification_config(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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.CreateNotificationConfigRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.create_notification_config(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_notification_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(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] - assert args[0].parent == 'parent_value' - assert args[0].config_id == 'config_id_value' - assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') - - -def test_create_notification_config_flattened_error(): - client = SecurityCenterClient( - 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_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_notification_config( - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(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] - assert args[0].parent == 'parent_value' - assert args[0].config_id == 'config_id_value' - assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') - - -@pytest.mark.asyncio -async def test_create_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_notification_config( - securitycenter_service.CreateNotificationConfigRequest(), - parent='parent_value', - config_id='config_id_value', - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - ) - - -def test_delete_notification_config(transport: str = 'grpc', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_notification_config_from_dict(): - test_delete_notification_config(request_type=dict) - - -def test_delete_notification_config_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 = SecurityCenterClient( - 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.delete_notification_config), - '__call__') as call: - client.delete_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - -@pytest.mark.asyncio -async def test_delete_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.DeleteNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.DeleteNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_notification_config_async_from_dict(): - await test_delete_notification_config_async(request_type=dict) - - -def test_delete_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value = None - client.delete_notification_config(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_delete_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.DeleteNotificationConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_notification_config(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_delete_notification_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_notification_config( - 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] - assert args[0].name == 'name_value' - - -def test_delete_notification_config_flattened_error(): - client = SecurityCenterClient( - 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.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_notification_config( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_delete_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.delete_notification_config( - securitycenter_service.DeleteNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - test_get_iam_policy(request_type=dict) - - -def test_get_iam_policy_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 = SecurityCenterClient( - 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_iam_policy), - '__call__') as call: - client.get_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.GetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_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] == iam_policy_pb2.GetIamPolicyRequest() - - # 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_from_dict(): - await test_get_iam_policy_async(request_type=dict) - - -def test_get_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_get_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_iam_policy( - resource='resource_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] - assert args[0].resource == 'resource_value' - - -def test_get_iam_policy_flattened_error(): - client = SecurityCenterClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_get_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_iam_policy( - iam_policy_pb2.GetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_get_notification_config(transport: str = 'grpc', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - streaming_config=notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), - ) - response = client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_get_notification_config_from_dict(): - test_get_notification_config(request_type=dict) - - -def test_get_notification_config_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 = SecurityCenterClient( - 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_notification_config), - '__call__') as call: - client.get_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - -@pytest.mark.asyncio -async def test_get_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.get_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_async_from_dict(): - await test_get_notification_config_async(request_type=dict) - - -def test_get_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value = notification_config.NotificationConfig() - client.get_notification_config(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_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetNotificationConfigRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - await client.get_notification_config(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_notification_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_notification_config( - 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] - assert args[0].name == 'name_value' - - -def test_get_notification_config_flattened_error(): - client = SecurityCenterClient( - 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_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_notification_config( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_notification_config( - securitycenter_service.GetNotificationConfigRequest(), - name='name_value', - ) - - -def test_get_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_get_organization_settings_from_dict(): - test_get_organization_settings(request_type=dict) - - -def test_get_organization_settings_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 = SecurityCenterClient( - 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_organization_settings), - '__call__') as call: - client.get_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - -@pytest.mark.asyncio -async def test_get_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.get_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_get_organization_settings_async_from_dict(): - await test_get_organization_settings_async(request_type=dict) - - -def test_get_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = organization_settings.OrganizationSettings() - client.get_organization_settings(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_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetOrganizationSettingsRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - await client.get_organization_settings(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_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_organization_settings( - 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] - assert args[0].name == 'name_value' - - -def test_get_organization_settings_flattened_error(): - client = SecurityCenterClient( - 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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_organization_settings( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_organization_settings( - securitycenter_service.GetOrganizationSettingsRequest(), - name='name_value', - ) - - -def test_get_source(transport: str = 'grpc', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_get_source_from_dict(): - test_get_source(request_type=dict) - - -def test_get_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.get_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - -@pytest.mark.asyncio -async def test_get_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GetSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.get_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GetSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_get_source_async_from_dict(): - await test_get_source_async(request_type=dict) - - -def test_get_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = source.Source() - client.get_source(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_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GetSourceRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - await client.get_source(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_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_source( - 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] - assert args[0].name == 'name_value' - - -def test_get_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -@pytest.mark.asyncio -async def test_get_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_source( - 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] - assert args[0].name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.GetSourceRequest(), - name='name_value', - ) - - -def test_group_assets(transport: str = 'grpc', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_assets_from_dict(): - test_group_assets(request_type=dict) - - -def test_group_assets_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 = SecurityCenterClient( - 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.group_assets), - '__call__') as call: - client.group_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - -@pytest.mark.asyncio -async def test_group_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_assets_async_from_dict(): - await test_group_assets_async(request_type=dict) - - -def test_group_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = securitycenter_service.GroupAssetsResponse() - client.group_assets(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_group_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupAssetsResponse()) - await client.group_assets(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_group_assets_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_assets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - -def test_group_assets_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_assets(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_group_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_assets(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, securitycenter_service.GroupResult) - for i in responses) - -@pytest.mark.asyncio -async def test_group_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupAssetsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.group_assets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_group_findings(transport: str = 'grpc', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_group_findings_from_dict(): - test_group_findings(request_type=dict) - - -def test_group_findings_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 = SecurityCenterClient( - 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.group_findings), - '__call__') as call: - client.group_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - -@pytest.mark.asyncio -async def test_group_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.GroupFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.group_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.GroupFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GroupFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_group_findings_async_from_dict(): - await test_group_findings_async(request_type=dict) - - -def test_group_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = securitycenter_service.GroupFindingsResponse() - client.group_findings(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_group_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.GroupFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - await client.group_findings(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_group_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.group_findings( - parent='parent_value', - group_by='group_by_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] - assert args[0].parent == 'parent_value' - assert args[0].group_by == 'group_by_value' - - -def test_group_findings_flattened_error(): - client = SecurityCenterClient( - 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.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -@pytest.mark.asyncio -async def test_group_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.GroupFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.GroupFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.group_findings( - parent='parent_value', - group_by='group_by_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].parent == 'parent_value' - assert args[0].group_by == 'group_by_value' - - -@pytest.mark.asyncio -async def test_group_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.group_findings( - securitycenter_service.GroupFindingsRequest(), - parent='parent_value', - group_by='group_by_value', - ) - - -def test_group_findings_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.group_findings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.GroupResult) - for i in results) - -def test_group_findings_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = list(client.group_findings(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_group_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.group_findings(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, securitycenter_service.GroupResult) - for i in responses) - -@pytest.mark.asyncio -async def test_group_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.group_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - next_page_token='abc', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[], - next_page_token='def', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.GroupFindingsResponse( - group_by_results=[ - securitycenter_service.GroupResult(), - securitycenter_service.GroupResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.group_findings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_assets(transport: str = 'grpc', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_assets_from_dict(): - test_list_assets(request_type=dict) - - -def test_list_assets_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 = SecurityCenterClient( - 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_assets), - '__call__') as call: - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListAssetsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = securitycenter_service.ListAssetsResponse() - client.list_assets(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_assets_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListAssetsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - await client.list_assets(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_assets_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_assets( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_assets_flattened_error(): - client = SecurityCenterClient( - 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_assets( - securitycenter_service.ListAssetsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_assets_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListAssetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListAssetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_assets( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_assets_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_assets( - securitycenter_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in results) - -def test_list_assets_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, securitycenter_service.ListAssetsResponse.ListAssetsResult) - for i in responses) - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[], - next_page_token='def', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListAssetsResponse( - list_assets_results=[ - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - securitycenter_service.ListAssetsResponse.ListAssetsResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_assets(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_findings(transport: str = 'grpc', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_findings_from_dict(): - test_list_findings(request_type=dict) - - -def test_list_findings_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 = SecurityCenterClient( - 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_findings), - '__call__') as call: - client.list_findings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - -@pytest.mark.asyncio -async def test_list_findings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListFindingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_findings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListFindingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFindingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_findings_async_from_dict(): - await test_list_findings_async(request_type=dict) - - -def test_list_findings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = securitycenter_service.ListFindingsResponse() - client.list_findings(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_findings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListFindingsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse()) - await client.list_findings(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_findings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListFindingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_findings( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_findings_flattened_error(): - client = SecurityCenterClient( - 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_findings( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_findings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListFindingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListFindingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_findings( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_findings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_findings( - securitycenter_service.ListFindingsRequest(), - parent='parent_value', - ) - - -def test_list_findings_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_findings(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in results) - -def test_list_findings_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - RuntimeError, - ) - pages = list(client.list_findings(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_findings_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_findings(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, securitycenter_service.ListFindingsResponse.ListFindingsResult) - for i in responses) - -@pytest.mark.asyncio -async def test_list_findings_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_findings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='abc', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[], - next_page_token='def', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListFindingsResponse( - list_findings_results=[ - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - securitycenter_service.ListFindingsResponse.ListFindingsResult(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_findings(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_notification_configs(transport: str = 'grpc', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_notification_configs_from_dict(): - test_list_notification_configs(request_type=dict) - - -def test_list_notification_configs_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 = SecurityCenterClient( - 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_notification_configs), - '__call__') as call: - client.list_notification_configs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - -@pytest.mark.asyncio -async def test_list_notification_configs_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListNotificationConfigsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_notification_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListNotificationConfigsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_async_from_dict(): - await test_list_notification_configs_async(request_type=dict) - - -def test_list_notification_configs_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - client.list_notification_configs(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_notification_configs_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListNotificationConfigsRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - await client.list_notification_configs(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_notification_configs_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_notification_configs( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_notification_configs_flattened_error(): - client = SecurityCenterClient( - 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_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListNotificationConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListNotificationConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_notification_configs( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_notification_configs_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_notification_configs( - securitycenter_service.ListNotificationConfigsRequest(), - parent='parent_value', - ) - - -def test_list_notification_configs_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_notification_configs(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, notification_config.NotificationConfig) - for i in results) - -def test_list_notification_configs_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = list(client.list_notification_configs(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_notification_configs_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_notification_configs(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, notification_config.NotificationConfig) - for i in responses) - -@pytest.mark.asyncio -async def test_list_notification_configs_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_notification_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - next_page_token='abc', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[], - next_page_token='def', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListNotificationConfigsResponse( - notification_configs=[ - notification_config.NotificationConfig(), - notification_config.NotificationConfig(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_notification_configs(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_list_sources(transport: str = 'grpc', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sources_from_dict(): - test_list_sources(request_type=dict) - - -def test_list_sources_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 = SecurityCenterClient( - 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_sources), - '__call__') as call: - client.list_sources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - -@pytest.mark.asyncio -async def test_list_sources_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.ListSourcesRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.ListSourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sources_async_from_dict(): - await test_list_sources_async(request_type=dict) - - -def test_list_sources_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = securitycenter_service.ListSourcesResponse() - client.list_sources(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_sources_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.ListSourcesRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - await client.list_sources(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_sources_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_sources( - 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] - assert args[0].parent == 'parent_value' - - -def test_list_sources_flattened_error(): - client = SecurityCenterClient( - 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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_list_sources_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = securitycenter_service.ListSourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(securitycenter_service.ListSourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_sources( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_list_sources_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_sources( - securitycenter_service.ListSourcesRequest(), - parent='parent_value', - ) - - -def test_list_sources_pager(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_sources(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, source.Source) - for i in results) - -def test_list_sources_pages(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = list(client.list_sources(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_sources_async_pager(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_sources(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, source.Source) - for i in responses) - -@pytest.mark.asyncio -async def test_list_sources_async_pages(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - source.Source(), - ], - next_page_token='abc', - ), - securitycenter_service.ListSourcesResponse( - sources=[], - next_page_token='def', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - ], - next_page_token='ghi', - ), - securitycenter_service.ListSourcesResponse( - sources=[ - source.Source(), - source.Source(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_sources(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -def test_run_asset_discovery(transport: str = 'grpc', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_run_asset_discovery_from_dict(): - test_run_asset_discovery(request_type=dict) - - -def test_run_asset_discovery_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 = SecurityCenterClient( - 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.run_asset_discovery), - '__call__') as call: - client.run_asset_discovery() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - -@pytest.mark.asyncio -async def test_run_asset_discovery_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.RunAssetDiscoveryRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.run_asset_discovery(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.RunAssetDiscoveryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_run_asset_discovery_async_from_dict(): - await test_run_asset_discovery_async(request_type=dict) - - -def test_run_asset_discovery_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.run_asset_discovery(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_run_asset_discovery_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.RunAssetDiscoveryRequest() - - request.parent = 'parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.run_asset_discovery(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_run_asset_discovery_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.run_asset_discovery( - 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] - assert args[0].parent == 'parent_value' - - -def test_run_asset_discovery_flattened_error(): - client = SecurityCenterClient( - 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.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.run_asset_discovery), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.run_asset_discovery( - 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] - assert args[0].parent == 'parent_value' - - -@pytest.mark.asyncio -async def test_run_asset_discovery_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.run_asset_discovery( - securitycenter_service.RunAssetDiscoveryRequest(), - parent='parent_value', - ) - - -def test_set_finding_state(transport: str = 'grpc', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_set_finding_state_from_dict(): - test_set_finding_state(request_type=dict) - - -def test_set_finding_state_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 = SecurityCenterClient( - 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.set_finding_state), - '__call__') as call: - client.set_finding_state() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - -@pytest.mark.asyncio -async def test_set_finding_state_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.SetFindingStateRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.set_finding_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.SetFindingStateRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_set_finding_state_async_from_dict(): - await test_set_finding_state_async(request_type=dict) - - -def test_set_finding_state_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = finding.Finding() - client.set_finding_state(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_set_finding_state_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.SetFindingStateRequest() - - request.name = 'name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - await client.set_finding_state(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_set_finding_state_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].state == finding.Finding.State.ACTIVE - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -def test_set_finding_state_flattened_error(): - client = SecurityCenterClient( - 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.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.set_finding_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_finding_state( - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].name == 'name_value' - assert args[0].state == finding.Finding.State.ACTIVE - assert TimestampRule().to_proto(args[0].start_time) == timestamp_pb2.Timestamp(seconds=751) - - -@pytest.mark.asyncio -async def test_set_finding_state_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.set_finding_state( - securitycenter_service.SetFindingStateRequest(), - name='name_value', - state=finding.Finding.State.ACTIVE, - start_time=timestamp_pb2.Timestamp(seconds=751), - ) - - -def test_set_iam_policy(transport: str = 'grpc', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - test_set_iam_policy(request_type=dict) - - -def test_set_iam_policy_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 = SecurityCenterClient( - 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.set_iam_policy), - '__call__') as call: - client.set_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.SetIamPolicyRequest() - - -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.SetIamPolicyRequest() - - # 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_from_dict(): - await test_set_iam_policy_async(request_type=dict) - - -def test_set_iam_policy_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_set_iam_policy_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.set_iam_policy( - resource='resource_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] - assert args[0].resource == 'resource_value' - - -def test_set_iam_policy_flattened_error(): - client = SecurityCenterClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.set_iam_policy( - resource='resource_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - - -@pytest.mark.asyncio -async def test_set_iam_policy_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.set_iam_policy( - iam_policy_pb2.SetIamPolicyRequest(), - resource='resource_value', - ) - - -def test_test_iam_permissions(transport: str = 'grpc', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - test_test_iam_permissions(request_type=dict) - - -def test_test_iam_permissions_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 = SecurityCenterClient( - 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.test_iam_permissions), - '__call__') as call: - client.test_iam_permissions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = 'grpc_asyncio', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.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] == iam_policy_pb2.TestIamPermissionsRequest() - - # 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_from_dict(): - await test_test_iam_permissions_async(request_type=dict) - - -def test_test_iam_permissions_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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_foreign(): - client = SecurityCenterClient( - 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() - - -def test_test_iam_permissions_flattened(): - client = SecurityCenterClient( - 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() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_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] - assert args[0].resource == 'resource_value' - assert args[0].permissions == ['permissions_value'] - - -def test_test_iam_permissions_flattened_error(): - client = SecurityCenterClient( - 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.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_async(): - client = SecurityCenterAsyncClient( - 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() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam_policy_pb2.TestIamPermissionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.test_iam_permissions( - resource='resource_value', - permissions=['permissions_value'], - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0].resource == 'resource_value' - assert args[0].permissions == ['permissions_value'] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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.test_iam_permissions( - iam_policy_pb2.TestIamPermissionsRequest(), - resource='resource_value', - permissions=['permissions_value'], - ) - - -def test_update_finding(transport: str = 'grpc', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - ) - response = client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -def test_update_finding_from_dict(): - test_update_finding(request_type=dict) - - -def test_update_finding_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 = SecurityCenterClient( - 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_finding), - '__call__') as call: - client.update_finding() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - -@pytest.mark.asyncio -async def test_update_finding_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateFindingRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding( - name='name_value', - parent='parent_value', - resource_name='resource_name_value', - state=gcs_finding.Finding.State.ACTIVE, - category='category_value', - external_uri='external_uri_value', - severity=gcs_finding.Finding.Severity.CRITICAL, - canonical_name='canonical_name_value', - )) - response = await client.update_finding(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateFindingRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_finding.Finding) - assert response.name == 'name_value' - assert response.parent == 'parent_value' - assert response.resource_name == 'resource_name_value' - assert response.state == gcs_finding.Finding.State.ACTIVE - assert response.category == 'category_value' - assert response.external_uri == 'external_uri_value' - assert response.severity == gcs_finding.Finding.Severity.CRITICAL - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_finding_async_from_dict(): - await test_update_finding_async(request_type=dict) - - -def test_update_finding_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'finding.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = gcs_finding.Finding() - client.update_finding(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', - 'finding.name=finding.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_finding_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateFindingRequest() - - request.finding.name = 'finding.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - await client.update_finding(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', - 'finding.name=finding.name/value', - ) in kw['metadata'] - - -def test_update_finding_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_finding( - finding=gcs_finding.Finding(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] - assert args[0].finding == gcs_finding.Finding(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_finding_flattened_error(): - client = SecurityCenterClient( - 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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_finding_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_finding), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_finding.Finding() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_finding.Finding()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_finding( - finding=gcs_finding.Finding(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] - assert args[0].finding == gcs_finding.Finding(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_finding_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_finding( - securitycenter_service.UpdateFindingRequest(), - finding=gcs_finding.Finding(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_notification_config(transport: str = 'grpc', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - streaming_config=gcs_notification_config.NotificationConfig.StreamingConfig(filter='filter_value'), - ) - response = client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -def test_update_notification_config_from_dict(): - test_update_notification_config(request_type=dict) - - -def test_update_notification_config_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 = SecurityCenterClient( - 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_notification_config), - '__call__') as call: - client.update_notification_config() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - -@pytest.mark.asyncio -async def test_update_notification_config_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateNotificationConfigRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig( - name='name_value', - description='description_value', - event_type=gcs_notification_config.NotificationConfig.EventType.FINDING, - pubsub_topic='pubsub_topic_value', - service_account='service_account_value', - )) - response = await client.update_notification_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateNotificationConfigRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_notification_config.NotificationConfig) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.event_type == gcs_notification_config.NotificationConfig.EventType.FINDING - assert response.pubsub_topic == 'pubsub_topic_value' - assert response.service_account == 'service_account_value' - - -@pytest.mark.asyncio -async def test_update_notification_config_async_from_dict(): - await test_update_notification_config_async(request_type=dict) - - -def test_update_notification_config_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'notification_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = gcs_notification_config.NotificationConfig() - client.update_notification_config(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', - 'notification_config.name=notification_config.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_notification_config_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateNotificationConfigRequest() - - request.notification_config.name = 'notification_config.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - await client.update_notification_config(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', - 'notification_config.name=notification_config.name/value', - ) in kw['metadata'] - - -def test_update_notification_config_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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] - assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_notification_config_flattened_error(): - client = SecurityCenterClient( - 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_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_notification_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_notification_config.NotificationConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_notification_config.NotificationConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_notification_config( - notification_config=gcs_notification_config.NotificationConfig(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] - assert args[0].notification_config == gcs_notification_config.NotificationConfig(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_notification_config_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_notification_config( - securitycenter_service.UpdateNotificationConfigRequest(), - notification_config=gcs_notification_config.NotificationConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_organization_settings(transport: str = 'grpc', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - ) - response = client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -def test_update_organization_settings_from_dict(): - test_update_organization_settings(request_type=dict) - - -def test_update_organization_settings_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 = SecurityCenterClient( - 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_organization_settings), - '__call__') as call: - client.update_organization_settings() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - -@pytest.mark.asyncio -async def test_update_organization_settings_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateOrganizationSettingsRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings( - name='name_value', - enable_asset_discovery=True, - )) - response = await client.update_organization_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateOrganizationSettingsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_organization_settings.OrganizationSettings) - assert response.name == 'name_value' - assert response.enable_asset_discovery is True - - -@pytest.mark.asyncio -async def test_update_organization_settings_async_from_dict(): - await test_update_organization_settings_async(request_type=dict) - - -def test_update_organization_settings_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'organization_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = gcs_organization_settings.OrganizationSettings() - client.update_organization_settings(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', - 'organization_settings.name=organization_settings.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_organization_settings_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateOrganizationSettingsRequest() - - request.organization_settings.name = 'organization_settings.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - await client.update_organization_settings(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', - 'organization_settings.name=organization_settings.name/value', - ) in kw['metadata'] - - -def test_update_organization_settings_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(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] - assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') - - -def test_update_organization_settings_flattened_error(): - client = SecurityCenterClient( - 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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_organization_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_organization_settings.OrganizationSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_organization_settings.OrganizationSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_organization_settings( - organization_settings=gcs_organization_settings.OrganizationSettings(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] - assert args[0].organization_settings == gcs_organization_settings.OrganizationSettings(name='name_value') - - -@pytest.mark.asyncio -async def test_update_organization_settings_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_organization_settings( - securitycenter_service.UpdateOrganizationSettingsRequest(), - organization_settings=gcs_organization_settings.OrganizationSettings(name='name_value'), - ) - - -def test_update_source(transport: str = 'grpc', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - ) - response = client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_source_from_dict(): - test_update_source(request_type=dict) - - -def test_update_source_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 = SecurityCenterClient( - 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_source), - '__call__') as call: - client.update_source() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - -@pytest.mark.asyncio -async def test_update_source_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSourceRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source( - name='name_value', - display_name='display_name_value', - description='description_value', - canonical_name='canonical_name_value', - )) - response = await client.update_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSourceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_source.Source) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_source_async_from_dict(): - await test_update_source_async(request_type=dict) - - -def test_update_source_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'source.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = gcs_source.Source() - client.update_source(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', - 'source.name=source.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_source_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSourceRequest() - - request.source.name = 'source.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - await client.update_source(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', - 'source.name=source.name/value', - ) in kw['metadata'] - - -def test_update_source_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_source( - source=gcs_source.Source(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] - assert args[0].source == gcs_source.Source(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_source_flattened_error(): - client = SecurityCenterClient( - 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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_source_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_source.Source() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_source.Source()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_source( - source=gcs_source.Source(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] - assert args[0].source == gcs_source.Source(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_source_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_source( - securitycenter_service.UpdateSourceRequest(), - source=gcs_source.Source(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_security_marks(transport: str = 'grpc', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - ) - response = client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -def test_update_security_marks_from_dict(): - test_update_security_marks(request_type=dict) - - -def test_update_security_marks_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 = SecurityCenterClient( - 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_security_marks), - '__call__') as call: - client.update_security_marks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - -@pytest.mark.asyncio -async def test_update_security_marks_async(transport: str = 'grpc_asyncio', request_type=securitycenter_service.UpdateSecurityMarksRequest): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks( - name='name_value', - canonical_name='canonical_name_value', - )) - response = await client.update_security_marks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == securitycenter_service.UpdateSecurityMarksRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_security_marks.SecurityMarks) - assert response.name == 'name_value' - assert response.canonical_name == 'canonical_name_value' - - -@pytest.mark.asyncio -async def test_update_security_marks_async_from_dict(): - await test_update_security_marks_async(request_type=dict) - - -def test_update_security_marks_field_headers(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'security_marks.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = gcs_security_marks.SecurityMarks() - client.update_security_marks(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', - 'security_marks.name=security_marks.name/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_security_marks_field_headers_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = securitycenter_service.UpdateSecurityMarksRequest() - - request.security_marks.name = 'security_marks.name/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - await client.update_security_marks(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', - 'security_marks.name=security_marks.name/value', - ) in kw['metadata'] - - -def test_update_security_marks_flattened(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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] - assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -def test_update_security_marks_flattened_error(): - client = SecurityCenterClient( - 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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_async(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_security_marks), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_security_marks.SecurityMarks() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_security_marks.SecurityMarks()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_security_marks( - security_marks=gcs_security_marks.SecurityMarks(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] - assert args[0].security_marks == gcs_security_marks.SecurityMarks(name='name_value') - assert args[0].update_mask == field_mask_pb2.FieldMask(paths=['paths_value']) - - -@pytest.mark.asyncio -async def test_update_security_marks_flattened_error_async(): - client = SecurityCenterAsyncClient( - 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_security_marks( - securitycenter_service.UpdateSecurityMarksRequest(), - security_marks=gcs_security_marks.SecurityMarks(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.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SecurityCenterClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SecurityCenterClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SecurityCenterGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SecurityCenterGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, -]) -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 = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SecurityCenterGrpcTransport, - ) - -def test_security_center_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_security_center_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SecurityCenterTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_source', - 'create_finding', - 'create_notification_config', - 'delete_notification_config', - 'get_iam_policy', - 'get_notification_config', - 'get_organization_settings', - 'get_source', - 'group_assets', - 'group_findings', - 'list_assets', - 'list_findings', - 'list_notification_configs', - 'list_sources', - 'run_asset_discovery', - 'set_finding_state', - 'set_iam_policy', - 'test_iam_permissions', - 'update_finding', - 'update_notification_config', - 'update_organization_settings', - 'update_source', - 'update_security_marks', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -def test_security_center_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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - 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', -), - quota_project_id="octopus", - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_center_base_transport_with_credentials_file_old_google_auth(): - # 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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - ), - quota_project_id="octopus", - ) - - -def test_security_center_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.securitycenter_v1p1beta1.services.security_center.transports.SecurityCenterTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SecurityCenterTransport() - adc.assert_called_once() - - -@requires_google_auth_gte_1_25_0 -def test_security_center_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) - SecurityCenterClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@requires_google_auth_lt_1_25_0 -def test_security_center_auth_adc_old_google_auth(): - # 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) - SecurityCenterClient() - adc.assert_called_once_with( - scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -def test_security_center_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',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.SecurityCenterGrpcTransport, - transports.SecurityCenterGrpcAsyncIOTransport, - ], -) -@requires_google_auth_lt_1_25_0 -def test_security_center_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.SecurityCenterGrpcTransport, grpc_helpers), - (transports.SecurityCenterGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_security_center_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( - "securitycenter.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="securitycenter.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_host_no_port(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com'), - ) - assert client.transport._host == 'securitycenter.googleapis.com:443' - - -def test_security_center_host_with_port(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='securitycenter.googleapis.com:8000'), - ) - assert client.transport._host == 'securitycenter.googleapis.com:8000' - -def test_security_center_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcTransport( - 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_security_center_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SecurityCenterGrpcAsyncIOTransport( - 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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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.SecurityCenterGrpcTransport, transports.SecurityCenterGrpcAsyncIOTransport]) -def test_security_center_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_security_center_grpc_lro_client(): - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_security_center_grpc_lro_async_client(): - client = SecurityCenterAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_asset_path(): - organization = "squid" - asset = "clam" - expected = "organizations/{organization}/assets/{asset}".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.asset_path(organization, asset) - assert expected == actual - - -def test_parse_asset_path(): - expected = { - "organization": "whelk", - "asset": "octopus", - } - path = SecurityCenterClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_asset_path(path) - assert expected == actual - -def test_finding_path(): - organization = "oyster" - source = "nudibranch" - finding = "cuttlefish" - expected = "organizations/{organization}/sources/{source}/findings/{finding}".format(organization=organization, source=source, finding=finding, ) - actual = SecurityCenterClient.finding_path(organization, source, finding) - assert expected == actual - - -def test_parse_finding_path(): - expected = { - "organization": "mussel", - "source": "winkle", - "finding": "nautilus", - } - path = SecurityCenterClient.finding_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_finding_path(path) - assert expected == actual - -def test_notification_config_path(): - organization = "scallop" - notification_config = "abalone" - expected = "organizations/{organization}/notificationConfigs/{notification_config}".format(organization=organization, notification_config=notification_config, ) - actual = SecurityCenterClient.notification_config_path(organization, notification_config) - assert expected == actual - - -def test_parse_notification_config_path(): - expected = { - "organization": "squid", - "notification_config": "clam", - } - path = SecurityCenterClient.notification_config_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_notification_config_path(path) - assert expected == actual - -def test_organization_settings_path(): - organization = "whelk" - expected = "organizations/{organization}/organizationSettings".format(organization=organization, ) - actual = SecurityCenterClient.organization_settings_path(organization) - assert expected == actual - - -def test_parse_organization_settings_path(): - expected = { - "organization": "octopus", - } - path = SecurityCenterClient.organization_settings_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_organization_settings_path(path) - assert expected == actual - -def test_security_marks_path(): - organization = "oyster" - asset = "nudibranch" - expected = "organizations/{organization}/assets/{asset}/securityMarks".format(organization=organization, asset=asset, ) - actual = SecurityCenterClient.security_marks_path(organization, asset) - assert expected == actual - - -def test_parse_security_marks_path(): - expected = { - "organization": "cuttlefish", - "asset": "mussel", - } - path = SecurityCenterClient.security_marks_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_security_marks_path(path) - assert expected == actual - -def test_source_path(): - organization = "winkle" - source = "nautilus" - expected = "organizations/{organization}/sources/{source}".format(organization=organization, source=source, ) - actual = SecurityCenterClient.source_path(organization, source) - assert expected == actual - - -def test_parse_source_path(): - expected = { - "organization": "scallop", - "source": "abalone", - } - path = SecurityCenterClient.source_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_source_path(path) - assert expected == actual - -def test_topic_path(): - project = "squid" - topic = "clam" - expected = "projects/{project}/topics/{topic}".format(project=project, topic=topic, ) - actual = SecurityCenterClient.topic_path(project, topic) - assert expected == actual - - -def test_parse_topic_path(): - expected = { - "project": "whelk", - "topic": "octopus", - } - path = SecurityCenterClient.topic_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_topic_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SecurityCenterClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = SecurityCenterClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = SecurityCenterClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = SecurityCenterClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SecurityCenterClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = SecurityCenterClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = SecurityCenterClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = SecurityCenterClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SecurityCenterClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = SecurityCenterClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SecurityCenterClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - client = SecurityCenterClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SecurityCenterTransport, '_prep_wrapped_messages') as prep: - transport_class = SecurityCenterClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/securitycenter_v1/test_security_center.py b/tests/unit/gapic/securitycenter_v1/test_security_center.py index 7fac76c8..86b341fa 100644 --- a/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -147,18 +147,6 @@ def test_security_center_client_from_service_account_info(client_class): assert client.transport._host == "securitycenter.googleapis.com:443" -@pytest.mark.parametrize( - "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] -) -def test_security_center_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -166,7 +154,7 @@ def test_security_center_client_service_account_always_use_jwt(client_class): (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_security_center_client_service_account_always_use_jwt_true( +def test_security_center_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -176,6 +164,13 @@ def test_security_center_client_service_account_always_use_jwt_true( 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", [SecurityCenterClient, SecurityCenterAsyncClient,] @@ -256,6 +251,7 @@ def test_security_center_client_client_options( 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 @@ -272,6 +268,7 @@ def test_security_center_client_client_options( 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 @@ -288,6 +285,7 @@ def test_security_center_client_client_options( 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 @@ -316,6 +314,7 @@ def test_security_center_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -382,6 +381,7 @@ def test_security_center_client_mtls_env_auto( 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 @@ -415,6 +415,7 @@ def test_security_center_client_mtls_env_auto( 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. @@ -436,6 +437,7 @@ def test_security_center_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -466,6 +468,7 @@ def test_security_center_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -496,6 +499,7 @@ def test_security_center_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -515,6 +519,7 @@ def test_security_center_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py index 7cb1fe75..4506c320 100644 --- a/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py @@ -146,18 +146,6 @@ def test_security_center_client_from_service_account_info(client_class): assert client.transport._host == "securitycenter.googleapis.com:443" -@pytest.mark.parametrize( - "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] -) -def test_security_center_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -165,7 +153,7 @@ def test_security_center_client_service_account_always_use_jwt(client_class): (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_security_center_client_service_account_always_use_jwt_true( +def test_security_center_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -175,6 +163,13 @@ def test_security_center_client_service_account_always_use_jwt_true( 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", [SecurityCenterClient, SecurityCenterAsyncClient,] @@ -255,6 +250,7 @@ def test_security_center_client_client_options( 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 @@ -271,6 +267,7 @@ def test_security_center_client_client_options( 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 @@ -287,6 +284,7 @@ def test_security_center_client_client_options( 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 @@ -315,6 +313,7 @@ def test_security_center_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -381,6 +380,7 @@ def test_security_center_client_mtls_env_auto( 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 @@ -414,6 +414,7 @@ def test_security_center_client_mtls_env_auto( 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. @@ -435,6 +436,7 @@ def test_security_center_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -465,6 +467,7 @@ def test_security_center_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -495,6 +498,7 @@ def test_security_center_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -514,6 +518,7 @@ def test_security_center_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) diff --git a/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py index a048f6a6..e729675f 100644 --- a/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py +++ b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py @@ -151,18 +151,6 @@ def test_security_center_client_from_service_account_info(client_class): assert client.transport._host == "securitycenter.googleapis.com:443" -@pytest.mark.parametrize( - "client_class", [SecurityCenterClient, SecurityCenterAsyncClient,] -) -def test_security_center_client_service_account_always_use_jwt(client_class): - with mock.patch.object( - service_account.Credentials, "with_always_use_jwt_access", create=True - ) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - @pytest.mark.parametrize( "transport_class,transport_name", [ @@ -170,7 +158,7 @@ def test_security_center_client_service_account_always_use_jwt(client_class): (transports.SecurityCenterGrpcAsyncIOTransport, "grpc_asyncio"), ], ) -def test_security_center_client_service_account_always_use_jwt_true( +def test_security_center_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( @@ -180,6 +168,13 @@ def test_security_center_client_service_account_always_use_jwt_true( 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", [SecurityCenterClient, SecurityCenterAsyncClient,] @@ -260,6 +255,7 @@ def test_security_center_client_client_options( 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 @@ -276,6 +272,7 @@ def test_security_center_client_client_options( 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 @@ -292,6 +289,7 @@ def test_security_center_client_client_options( 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 @@ -320,6 +318,7 @@ def test_security_center_client_client_options( client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -386,6 +385,7 @@ def test_security_center_client_mtls_env_auto( 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 @@ -419,6 +419,7 @@ def test_security_center_client_mtls_env_auto( 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. @@ -440,6 +441,7 @@ def test_security_center_client_mtls_env_auto( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -470,6 +472,7 @@ def test_security_center_client_client_options_scopes( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -500,6 +503,7 @@ def test_security_center_client_client_options_credentials_file( client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, ) @@ -519,6 +523,7 @@ def test_security_center_client_client_options_from_dict(): client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, )