diff --git a/.coveragerc b/.coveragerc index dd39c854..2f4aeed0 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,35 +1,17 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! [run] branch = True [report] fail_under = 100 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 abstract methods - raise NotImplementedError -omit = - */gapic/*.py - */proto/*.py - */core/*.py - */site-packages/*.py \ No newline at end of file + # 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 \ No newline at end of file diff --git a/.kokoro/populate-secrets.sh b/.kokoro/populate-secrets.sh new file mode 100755 index 00000000..f5251425 --- /dev/null +++ b/.kokoro/populate-secrets.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Copyright 2020 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;} +function msg { println "$*" >&2 ;} +function println { printf '%s\n' "$(now) $*" ;} + + +# Populates requested secrets set in SECRET_MANAGER_KEYS from service account: +# kokoro-trampoline@cloud-devrel-kokoro-resources.iam.gserviceaccount.com +SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" +msg "Creating folder on disk for secrets: ${SECRET_LOCATION}" +mkdir -p ${SECRET_LOCATION} +for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g") +do + msg "Retrieving secret ${key}" + docker run --entrypoint=gcloud \ + --volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR} \ + gcr.io/google.com/cloudsdktool/cloud-sdk \ + secrets versions access latest \ + --project cloud-devrel-kokoro-resources \ + --secret ${key} > \ + "${SECRET_LOCATION}/${key}" + if [[ $? == 0 ]]; then + msg "Secret written to ${SECRET_LOCATION}/${key}" + else + msg "Error retrieving secret ${key}" + fi +done diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index bdcf0610..b71fba6a 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,42 +23,18 @@ env_vars: { value: "github/python-securitycenter/.kokoro/release.sh" } -# Fetch the token needed for reporting release status to GitHub -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "yoshi-automation-github-key" - } - } -} - -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - -# Fetch magictoken to use with Magic Github Proxy -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "releasetool-magictoken" - } - } +# Fetch PyPI password +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google_cloud_pypi_password" + } + } } -# Fetch api key to use with Magic Github Proxy -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "magic-github-proxy-api-key" - } - } -} +# Tokens needed to report release status back to GitHub +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg index 042dd5c6..63766e39 100644 --- a/.kokoro/samples/python3.6/common.cfg +++ b/.kokoro/samples/python3.6/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.6" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py36" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-securitycenter/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg index 57a97136..4fcff500 100644 --- a/.kokoro/samples/python3.7/common.cfg +++ b/.kokoro/samples/python3.7/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.7" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py37" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-securitycenter/.kokoro/test-samples.sh" diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg index cee81cd5..169cd74c 100644 --- a/.kokoro/samples/python3.8/common.cfg +++ b/.kokoro/samples/python3.8/common.cfg @@ -13,6 +13,12 @@ env_vars: { value: "py-3.8" } +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-py38" +} + env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-securitycenter/.kokoro/test-samples.sh" diff --git a/.kokoro/trampoline.sh b/.kokoro/trampoline.sh index e8c4251f..f39236e9 100755 --- a/.kokoro/trampoline.sh +++ b/.kokoro/trampoline.sh @@ -15,9 +15,14 @@ set -eo pipefail -python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" || ret_code=$? +# Always run the cleanup script, regardless of the success of bouncing into +# the container. +function cleanup() { + chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + echo "cleanup"; +} +trap cleanup EXIT -chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh -${KOKORO_GFILE_DIR}/trampoline_cleanup.sh || true - -exit ${ret_code} +$(dirname $0)/populate-secrets.sh # Secret Manager secrets. +python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 7f522a22..1d8fa16d 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -80,25 +80,6 @@ We use `nox `__ to instrument our tests. .. nox: https://pypi.org/project/nox/ -Note on Editable Installs / Develop Mode -======================================== - -- As mentioned previously, using ``setuptools`` in `develop mode`_ - or a ``pip`` `editable install`_ is not possible with this - library. This is because this library uses `namespace packages`_. - For context see `Issue #2316`_ and the relevant `PyPA issue`_. - - Since ``editable`` / ``develop`` mode can't be used, packages - need to be installed directly. Hence your changes to the source - tree don't get incorporated into the **already installed** - package. - -.. _namespace packages: https://www.python.org/dev/peps/pep-0420/ -.. _Issue #2316: https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2316 -.. _PyPA issue: https://github.com/pypa/packaging-problems/issues/12 -.. _develop mode: https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode -.. _editable install: https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs - ***************************************** I'm getting weird errors... Can you help? ***************************************** diff --git a/README.rst b/README.rst index 5828416c..127c4a3b 100644 --- a/README.rst +++ b/README.rst @@ -50,11 +50,13 @@ dependencies. Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Python >= 3.5 +Python >= 3.6 Deprecated Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^ -Python == 2.7. Python 2.7 support will be removed on January 1, 2020. +Python == 2.7. + +The last version of this library compatible with Python 2.7 is google-cloud-securitycenter==0.6.0. Mac/Linux diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 00000000..18e6f580 --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,179 @@ +# 2.0.0 Migration Guide + +The 2.0 release of the `google-cloud-securitycenter` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage. + +If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-securitycenter/issues). + +## Supported Python Versions + +> **WARNING**: Breaking change + +The 2.0.0 release requires Python 3.6+. + + +## Method Calls + +> **WARNING**: Breaking change + +Methods expect request objects. We provide a script that will convert most common use cases. + +* Install the library + +```py +python3 -m pip install google-cloud-securitycenter +``` + +* The script `fixup_securitycenter_v1_keywords.py` is shipped with the library. It expects +an input directory (with the code to convert) and an empty destination directory. + +```sh +$ fixup_securitycenter_v1_keywords.py --input-directory .samples/ --output-directory samples/ +``` + +**Before:** +```py +from google.cloud import securitycenter + +client = securitycenter.SecurityCenterClient() + +assets = client.list_assets( + org_name, filter_=project_filter, read_time=timestamp_proto +) +``` + + +**After:** +```py +from google.cloud import securitycenter + +client = securitycenter.securitycenterClient() + +assets = client.list_assets( + request={ + "org_name": org_name, + "filter_:": project_filter, + "read_time": timestamp_proto + } +) +``` + +### More Details + +In `google-cloud-securitycenter<2.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters. + +**Before:** +```py + def list_assets( + self, + parent, + filter_=None, + order_by=None, + read_time=None, + compare_duration=None, + field_mask=None, + page_size=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): +``` + +In the 2.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional. + +Some methods have additional keyword only parameters. The available parameters depend on the `google.api.method_signature` annotation specified by the API producer. + + +**After:** +```py + 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: +``` + +> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive. +> Passing both will result in an error. + + +Both of these calls are valid: + +```py +response = client.set_finding_state( + request={ + "name": name, + "state": state, + "start_time": start_time, + } +) +``` + +```py +response = client.set_finding_state( + name=name, + state=state, + start_time=start_time +) +``` + +This call is invalid because it mixes `request` with a keyword argument `start_time`. Executing this code +will result in an error. + +```py +response = client.set_finding_state( + request={ + "name": name, + "state": state, + }, + start_time=start_time +) +``` + + + +## Enums and Types + + +> **WARNING**: Breaking change + +The submodules `enums` and `types` have been removed. + +**Before:** +```py + +from google.cloud import securitycenter + +finding = securitycenter.types.Finding() +``` + +**After:** +```py + +from google.cloud import securitycenter + +finding = securitycenter.Finding() +``` + +## Datetime and Timedelta + +Native Python datetime and timedeltas can be passed to the library. + +```py +from google.cloud import securitycenter + +client = securitycenter.SecurityCenterClient() + +read_time = datetime.utcnow() - timedelta(days=1) + +group_result_iterator = client.group_findings( + request={ + "parent": source_name, + "group_by": "category", + "read_time": read_time, + } +) +``` + diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md new file mode 120000 index 00000000..01097c8c --- /dev/null +++ b/docs/UPGRADING.md @@ -0,0 +1 @@ +../UPGRADING.md \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py index 7341e8bd..060155c0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -39,6 +39,7 @@ "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.coverage", + "sphinx.ext.doctest", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index 2374f76d..00000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Security Command Center API -====================================== - -.. automodule:: google.cloud.securitycenter_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst deleted file mode 100644 index 89fdb487..00000000 --- a/docs/gapic/v1beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Security Command Center API -====================================== - -.. automodule:: google.cloud.securitycenter_v1beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst deleted file mode 100644 index 1ec286a2..00000000 --- a/docs/gapic/v1beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Security Command Center API Client -============================================ - -.. automodule:: google.cloud.securitycenter_v1beta1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1p1beta1/api.rst b/docs/gapic/v1p1beta1/api.rst deleted file mode 100644 index 75578ebf..00000000 --- a/docs/gapic/v1p1beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Security Command Center API -====================================== - -.. automodule:: google.cloud.securitycenter_v1p1beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1p1beta1/types.rst b/docs/gapic/v1p1beta1/types.rst deleted file mode 100644 index caba995a..00000000 --- a/docs/gapic/v1p1beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Security Command Center API Client -============================================ - -.. automodule:: google.cloud.securitycenter_v1p1beta1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 32c71ab5..02ac87bb 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -10,21 +10,36 @@ v1 .. toctree:: :maxdepth: 2 - gapic/v1/api - gapic/v1/types + securitycenter_v1/services + securitycenter_v1/types v1beta1 ~~~~~~~ .. toctree:: - gapic/v1beta1/api - gapic/v1beta1/types + :maxdepth: 2 + + securitycenter_v1beta1/services + securitycenter_v1beta1/types v1p1beta1 ~~~~~~~~~ .. toctree:: - gapic/v1p1beta1/api - gapic/v1p1beta1/types + :maxdepth: 2 + + securitycenter_v1p1beta1/services + securitycenter_v1p1beta1/types + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING + Changelog ---------- diff --git a/docs/securitycenter_v1/services.rst b/docs/securitycenter_v1/services.rst new file mode 100644 index 00000000..d1a1378e --- /dev/null +++ b/docs/securitycenter_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1 API +=============================================== + +.. automodule:: google.cloud.securitycenter_v1.services.security_center + :members: + :inherited-members: diff --git a/docs/gapic/v1/types.rst b/docs/securitycenter_v1/types.rst similarity index 62% rename from docs/gapic/v1/types.rst rename to docs/securitycenter_v1/types.rst index ef2b084e..14eaa881 100644 --- a/docs/gapic/v1/types.rst +++ b/docs/securitycenter_v1/types.rst @@ -1,5 +1,5 @@ -Types for Security Command Center API Client +Types for Google Cloud Securitycenter v1 API ============================================ .. automodule:: google.cloud.securitycenter_v1.types - :members: \ No newline at end of file + :members: diff --git a/docs/securitycenter_v1beta1/services.rst b/docs/securitycenter_v1beta1/services.rst new file mode 100644 index 00000000..212796c8 --- /dev/null +++ b/docs/securitycenter_v1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1beta1 API +==================================================== + +.. automodule:: google.cloud.securitycenter_v1beta1.services.security_center + :members: + :inherited-members: diff --git a/docs/securitycenter_v1beta1/types.rst b/docs/securitycenter_v1beta1/types.rst new file mode 100644 index 00000000..b0ca8b93 --- /dev/null +++ b/docs/securitycenter_v1beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Securitycenter v1beta1 API +================================================= + +.. automodule:: google.cloud.securitycenter_v1beta1.types + :members: diff --git a/docs/securitycenter_v1p1beta1/services.rst b/docs/securitycenter_v1p1beta1/services.rst new file mode 100644 index 00000000..5034b831 --- /dev/null +++ b/docs/securitycenter_v1p1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Securitycenter v1p1beta1 API +====================================================== + +.. automodule:: google.cloud.securitycenter_v1p1beta1.services.security_center + :members: + :inherited-members: diff --git a/docs/securitycenter_v1p1beta1/types.rst b/docs/securitycenter_v1p1beta1/types.rst new file mode 100644 index 00000000..390f90e2 --- /dev/null +++ b/docs/securitycenter_v1p1beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Securitycenter v1p1beta1 API +=================================================== + +.. automodule:: google.cloud.securitycenter_v1p1beta1.types + :members: diff --git a/google/cloud/securitycenter/__init__.py b/google/cloud/securitycenter/__init__.py new file mode 100644 index 00000000..986b34a6 --- /dev/null +++ b/google/cloud/securitycenter/__init__.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.async_client import ( + SecurityCenterAsyncClient, +) +from google.cloud.securitycenter_v1.services.security_center.client import ( + SecurityCenterClient, +) +from google.cloud.securitycenter_v1.types.asset import Asset +from google.cloud.securitycenter_v1.types.finding import Finding +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__ = ( + "Asset", + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "Finding", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "NotificationConfig", + "NotificationMessage", + "OrganizationSettings", + "Resource", + "RunAssetDiscoveryRequest", + "RunAssetDiscoveryResponse", + "SecurityCenterAsyncClient", + "SecurityCenterClient", + "SecurityMarks", + "SetFindingStateRequest", + "Source", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", +) diff --git a/google/cloud/securitycenter/py.typed b/google/cloud/securitycenter/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/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/google/cloud/securitycenter_v1/__init__.py b/google/cloud/securitycenter_v1/__init__.py index e7f67b46..27c3ed04 100644 --- a/google/cloud/securitycenter_v1/__init__.py +++ b/google/cloud/securitycenter_v1/__init__.py @@ -1,45 +1,95 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.securitycenter_v1 import types -from google.cloud.securitycenter_v1.gapic import enums -from google.cloud.securitycenter_v1.gapic import security_center_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class SecurityCenterClient(security_center_client.SecurityCenterClient): - __doc__ = security_center_client.SecurityCenterClient.__doc__ - enums = enums +from .services.security_center import SecurityCenterClient +from .types.asset import Asset +from .types.finding import Finding +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__ = ( - "enums", - "types", + "Asset", + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "Finding", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "NotificationConfig", + "NotificationMessage", + "OrganizationSettings", + "Resource", + "RunAssetDiscoveryRequest", + "RunAssetDiscoveryResponse", + "SecurityMarks", + "SetFindingStateRequest", + "Source", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1/gapic/__init__.py b/google/cloud/securitycenter_v1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1/gapic/enums.py b/google/cloud/securitycenter_v1/gapic/enums.py deleted file mode 100644 index 7a314985..00000000 --- a/google/cloud/securitycenter_v1/gapic/enums.py +++ /dev/null @@ -1,150 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class NullValue(enum.IntEnum): - """ - ``NullValue`` is a singleton enumeration to represent the null value - for the ``Value`` type union. - - The JSON representation for ``NullValue`` is JSON ``null``. - - Attributes: - NULL_VALUE (int): Null value. - """ - - NULL_VALUE = 0 - - -class Finding(object): - class State(enum.IntEnum): - """ - The state of the finding. - - Attributes: - STATE_UNSPECIFIED (int): Unspecified state. - ACTIVE (int): The finding requires attention and has not been addressed yet. - INACTIVE (int): The finding has been fixed, triaged as a non-issue or otherwise addressed - and is no longer active. - """ - - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - -class ListAssetsResponse(object): - class ListAssetsResult(object): - class StateChange(enum.IntEnum): - """ - 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 - - Attributes: - UNUSED (int): State change is unused, this is the canonical default for this enum. - ADDED (int): Asset was added between the points in time. - REMOVED (int): Asset was removed between the points in time. - ACTIVE (int): Asset was present at both point(s) in time. - """ - - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - -class ListFindingsResponse(object): - class ListFindingsResult(object): - class StateChange(enum.IntEnum): - """ - 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 - - Attributes: - UNUSED (int): State change is unused, this is the canonical default for this enum. - CHANGED (int): The finding has changed state in some way between the points in time - and existed at both points. - UNCHANGED (int): The finding has not changed state between the points in time and - existed at both points. - ADDED (int): The finding was created between the points in time. - REMOVED (int): The finding at timestamp does not match the filter specified, but it - did at timestamp - compare_duration. - """ - - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - -class OrganizationSettings(object): - class AssetDiscoveryConfig(object): - class InclusionMode(enum.IntEnum): - """ - 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. - - Attributes: - INCLUSION_MODE_UNSPECIFIED (int): Unspecified. Setting the mode with this value will disable - inclusion/exclusion filtering for Asset Discovery. - INCLUDE_ONLY (int): Asset Discovery will capture only the resources within the projects - specified. All other resources will be ignored. - EXCLUDE (int): Asset Discovery will ignore all resources under the projects specified. - All other resources will be retrieved. - """ - - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - -class RunAssetDiscoveryResponse(object): - class State(enum.IntEnum): - """ - The state of an asset discovery run. - - Attributes: - STATE_UNSPECIFIED (int): Asset discovery run state was unspecified. - COMPLETED (int): Asset discovery run completed successfully. - SUPERSEDED (int): Asset discovery run was cancelled with tasks still pending, as another - run for the same organization was started with a higher priority. - TERMINATED (int): Asset discovery run was killed and terminated. - """ - - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 diff --git a/google/cloud/securitycenter_v1/gapic/security_center_client.py b/google/cloud/securitycenter_v1/gapic/security_center_client.py deleted file mode 100644 index e6c19fcd..00000000 --- a/google/cloud/securitycenter_v1/gapic/security_center_client.py +++ /dev/null @@ -1,2833 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.securitycenter.v1 SecurityCenter API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.securitycenter_v1.gapic import enums -from google.cloud.securitycenter_v1.gapic import security_center_client_config -from google.cloud.securitycenter_v1.gapic.transports import ( - security_center_grpc_transport, -) -from google.cloud.securitycenter_v1.proto import finding_pb2 -from google.cloud.securitycenter_v1.proto import notification_config_pb2 -from google.cloud.securitycenter_v1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1.proto import run_asset_discovery_response_pb2 -from google.cloud.securitycenter_v1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1.proto import securitycenter_service_pb2_grpc -from google.cloud.securitycenter_v1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-securitycenter", -).version - - -class SecurityCenterClient(object): - """V1 APIs for Security Center service.""" - - SERVICE_ADDRESS = "securitycenter.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.securitycenter.v1.SecurityCenter" - - @classmethod - def from_service_account_file(cls, filename, *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 - - @classmethod - def asset_security_marks_path(cls, organization, asset): - """Return a fully-qualified asset_security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/assets/{asset}/securityMarks", - organization=organization, - asset=asset, - ) - - @classmethod - def finding_path(cls, organization, source, finding): - """Return a fully-qualified finding string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}/findings/{finding}", - organization=organization, - source=source, - finding=finding, - ) - - @classmethod - def finding_security_marks_path(cls, organization, source, finding): - """Return a fully-qualified finding_security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}/findings/{finding}/securityMarks", - organization=organization, - source=source, - finding=finding, - ) - - @classmethod - def notification_config_path(cls, organization, notification_config): - """Return a fully-qualified notification_config string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/notificationConfigs/{notification_config}", - organization=organization, - notification_config=notification_config, - ) - - @classmethod - def organization_path(cls, organization): - """Return a fully-qualified organization string.""" - return google.api_core.path_template.expand( - "organizations/{organization}", organization=organization, - ) - - @classmethod - def organization_settings_path(cls, organization): - """Return a fully-qualified organization_settings string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/organizationSettings", - organization=organization, - ) - - @classmethod - def security_marks_path(cls, organization, asset): - """Return a fully-qualified security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/assets/{asset}/securityMarks", - organization=organization, - asset=asset, - ) - - @classmethod - def source_path(cls, organization, source): - """Return a fully-qualified source string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}", - organization=organization, - source=source, - ) - - @classmethod - def topic_path(cls, project, topic): - """Return a fully-qualified topic string.""" - return google.api_core.path_template.expand( - "projects/{project}/topics/{topic}", project=project, topic=topic, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.SecurityCenterGrpcTransport, - Callable[[~.Credentials, type], ~.SecurityCenterGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = security_center_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=security_center_grpc_transport.SecurityCenterGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = security_center_grpc_transport.SecurityCenterGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def create_source( - self, - parent, - source, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a source. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `source`: - >>> source = {} - >>> - >>> response = client.create_source(parent, source) - - Args: - parent (str): Required. Resource name of the new source's parent. Its format - should be "organizations/[organization_id]". - source (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Source` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_source" not in self._inner_api_calls: - self._inner_api_calls[ - "create_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_source, - default_retry=self._method_configs["CreateSource"].retry, - default_timeout=self._method_configs["CreateSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_finding( - self, - parent, - finding_id, - finding, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a finding. The corresponding source must exist for finding creation - to succeed. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `finding_id`: - >>> finding_id = '' - >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} - >>> - >>> response = client.create_finding(parent, finding_id, finding) - - Args: - 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 (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Finding` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_finding" not in self._inner_api_calls: - self._inner_api_calls[ - "create_finding" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_finding, - default_retry=self._method_configs["CreateFinding"].retry, - default_timeout=self._method_configs["CreateFinding"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_finding"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_notification_config( - self, - parent, - config_id, - notification_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a notification config. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `config_id`: - >>> config_id = '' - >>> - >>> # TODO: Initialize `notification_config`: - >>> notification_config = {} - >>> - >>> response = client.create_notification_config(parent, config_id, notification_config) - - Args: - 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 (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_notification_config" not in self._inner_api_calls: - self._inner_api_calls[ - "create_notification_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_notification_config, - default_retry=self._method_configs["CreateNotificationConfig"].retry, - default_timeout=self._method_configs[ - "CreateNotificationConfig" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.CreateNotificationConfigRequest( - parent=parent, config_id=config_id, notification_config=notification_config, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_notification_config( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a notification config. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') - >>> - >>> client.delete_notification_config(name) - - Args: - name (str): Required. Name of the notification config to delete. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_notification_config" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_notification_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_notification_config, - default_retry=self._method_configs["DeleteNotificationConfig"].retry, - default_timeout=self._method_configs[ - "DeleteNotificationConfig" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.DeleteNotificationConfigRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_iam_policy( - self, - resource, - options_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the access control policy on the specified Source. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> response = client.get_iam_policy(resource) - - Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.securitycenter_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.GetPolicyOptions` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "get_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_notification_config( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a notification config. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') - >>> - >>> response = client.get_notification_config(name) - - Args: - name (str): Required. Name of the notification config to get. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_notification_config" not in self._inner_api_calls: - self._inner_api_calls[ - "get_notification_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_notification_config, - default_retry=self._method_configs["GetNotificationConfig"].retry, - default_timeout=self._method_configs["GetNotificationConfig"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GetNotificationConfigRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_organization_settings( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the settings for an organization. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.organization_settings_path('[ORGANIZATION]') - >>> - >>> response = client.get_organization_settings(name) - - Args: - name (str): Required. Name of the organization to get organization settings for. - Its format is "organizations/[organization_id]/organizationSettings". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_organization_settings" not in self._inner_api_calls: - self._inner_api_calls[ - "get_organization_settings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_organization_settings, - default_retry=self._method_configs["GetOrganizationSettings"].retry, - default_timeout=self._method_configs["GetOrganizationSettings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_organization_settings"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_source( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a source. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> response = client.get_source(name) - - Args: - name (str): Required. Relative resource name of the source. Its format is - "organizations/[organization_id]/source/[source_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_source" not in self._inner_api_calls: - self._inner_api_calls[ - "get_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_source, - default_retry=self._method_configs["GetSource"].retry, - default_timeout=self._method_configs["GetSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GetSourceRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def group_assets( - self, - parent, - group_by, - filter_=None, - compare_duration=None, - read_time=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Filters an organization's assets and groups them by their specified - properties. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_assets(parent, group_by): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_assets(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - 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 - 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 : ""`` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.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``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - read_time (Union[dict, ~google.cloud.securitycenter_v1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "group_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "group_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_assets, - default_retry=self._method_configs["GroupAssets"].retry, - default_timeout=self._method_configs["GroupAssets"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - compare_duration=compare_duration, - read_time=read_time, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def group_findings( - self, - parent, - group_by, - filter_=None, - read_time=None, - compare_duration=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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 - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_findings(parent, group_by): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_findings(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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/- - 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 - - The following fields are supported when compare_duration is set: - - - state_change - 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`` - - - 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 : ""`` - read_time (Union[dict, ~google.cloud.securitycenter_v1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.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``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "group_findings" not in self._inner_api_calls: - self._inner_api_calls[ - "group_findings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_findings, - default_retry=self._method_configs["GroupFindings"].retry, - default_timeout=self._method_configs["GroupFindings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - read_time=read_time, - compare_duration=compare_duration, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_assets( - self, - parent, - filter_=None, - order_by=None, - read_time=None, - compare_duration=None, - field_mask=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists an organization's assets. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_assets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_assets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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 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 (Union[dict, ~google.cloud.securitycenter_v1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - field_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): Optional. A field mask to specify the ListAssetsResult fields to be listed - in the response. An empty field mask will list all fields. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.FieldMask` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.ListAssetsResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_assets, - default_retry=self._method_configs["ListAssets"].retry, - default_timeout=self._method_configs["ListAssets"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListAssetsRequest( - parent=parent, - filter=filter_, - order_by=order_by, - read_time=read_time, - compare_duration=compare_duration, - field_mask=field_mask, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="list_assets_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_findings( - self, - parent, - filter_=None, - order_by=None, - read_time=None, - compare_duration=None, - field_mask=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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 - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # Iterate over all results - >>> for element in client.list_findings(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_findings(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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 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`` - - 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 (Union[dict, ~google.cloud.securitycenter_v1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - field_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): Optional. A field mask to specify the Finding fields to be listed in the - response. An empty field mask will list all fields. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.FieldMask` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.ListFindingsResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_findings" not in self._inner_api_calls: - self._inner_api_calls[ - "list_findings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_findings, - default_retry=self._method_configs["ListFindings"].retry, - default_timeout=self._method_configs["ListFindings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListFindingsRequest( - parent=parent, - filter=filter_, - order_by=order_by, - read_time=read_time, - compare_duration=compare_duration, - field_mask=field_mask, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="list_findings_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_notification_configs( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists notification configs. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_notification_configs(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_notification_configs(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Name of the organization to list notification configs. Its - format is "organizations/[organization_id]". - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_notification_configs" not in self._inner_api_calls: - self._inner_api_calls[ - "list_notification_configs" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_notification_configs, - default_retry=self._method_configs["ListNotificationConfigs"].retry, - default_timeout=self._method_configs["ListNotificationConfigs"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListNotificationConfigsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_notification_configs"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="notification_configs", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_sources( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists all sources belonging to an organization. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_sources(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_sources(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Resource name of the parent of sources to list. Its format - should be "organizations/[organization_id]". - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.Source` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_sources" not in self._inner_api_calls: - self._inner_api_calls[ - "list_sources" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_sources, - default_retry=self._method_configs["ListSources"].retry, - default_timeout=self._method_configs["ListSources"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListSourcesRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_sources"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="sources", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def run_asset_discovery( - self, - parent, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> response = client.run_asset_discovery(parent) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. Name of the organization to run asset discovery for. Its - format is "organizations/[organization_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "run_asset_discovery" not in self._inner_api_calls: - self._inner_api_calls[ - "run_asset_discovery" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.run_asset_discovery, - default_retry=self._method_configs["RunAssetDiscovery"].retry, - default_timeout=self._method_configs["RunAssetDiscovery"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.RunAssetDiscoveryRequest(parent=parent,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["run_asset_discovery"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - run_asset_discovery_response_pb2.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - def set_finding_state( - self, - name, - state, - start_time, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates the state of a finding. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> from google.cloud.securitycenter_v1 import enums - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.finding_path('[ORGANIZATION]', '[SOURCE]', '[FINDING]') - >>> - >>> # TODO: Initialize `state`: - >>> state = enums.Finding.State.STATE_UNSPECIFIED - >>> - >>> # TODO: Initialize `start_time`: - >>> start_time = {} - >>> - >>> response = client.set_finding_state(name, state, start_time) - - Args: - 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.State): Required. The desired State of the finding. - start_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Required. The time at which the updated state takes effect. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_finding_state" not in self._inner_api_calls: - self._inner_api_calls[ - "set_finding_state" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_finding_state, - default_retry=self._method_configs["SetFindingState"].retry, - default_timeout=self._method_configs["SetFindingState"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.SetFindingStateRequest( - name=name, state=state, start_time=start_time, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_finding_state"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def set_iam_policy( - self, - resource, - policy, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sets the access control policy on the specified Source. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `policy`: - >>> policy = {} - >>> - >>> response = client.set_iam_policy(resource, policy) - - Args: - resource (str): REQUIRED: The resource for which the policy is being specified. - See the operation documentation for the appropriate value for this field. - policy (Union[dict, ~google.cloud.securitycenter_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The - size of the policy is limited to a few 10s of KB. An empty policy is a - valid policy but certain Cloud Platform services (such as Projects) - might reject them. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Policy` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "set_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_iam_policy, - default_retry=self._method_configs["SetIamPolicy"].retry, - default_timeout=self._method_configs["SetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def test_iam_permissions( - self, - resource, - permissions, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns the permissions that a caller has on the specified source. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] - >>> - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[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 `__. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.TestIamPermissionsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: - self._inner_api_calls[ - "test_iam_permissions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["test_iam_permissions"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_finding( - self, - finding, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates or updates a finding. The corresponding source must exist for a - finding creation to succeed. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} - >>> - >>> response = client.update_finding(finding) - - Args: - finding (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Finding` - update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_finding" not in self._inner_api_calls: - self._inner_api_calls[ - "update_finding" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_finding, - default_retry=self._method_configs["UpdateFinding"].retry, - default_timeout=self._method_configs["UpdateFinding"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateFindingRequest( - finding=finding, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("finding.name", finding.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_finding"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_notification_config( - self, - notification_config, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `notification_config`: - >>> notification_config = {} - >>> - >>> response = client.update_notification_config(notification_config) - - Args: - notification_config (Union[dict, ~google.cloud.securitycenter_v1.types.NotificationConfig]): Required. The notification config to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` - update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): The FieldMask to use when updating the notification config. - - If empty all mutable fields will be updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_notification_config" not in self._inner_api_calls: - self._inner_api_calls[ - "update_notification_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_notification_config, - default_retry=self._method_configs["UpdateNotificationConfig"].retry, - default_timeout=self._method_configs[ - "UpdateNotificationConfig" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateNotificationConfigRequest( - notification_config=notification_config, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("notification_config.name", notification_config.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_organization_settings( - self, - organization_settings, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates an organization's settings. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `organization_settings`: - >>> organization_settings = {} - >>> - >>> response = client.update_organization_settings(organization_settings) - - Args: - organization_settings (Union[dict, ~google.cloud.securitycenter_v1.types.OrganizationSettings]): Required. The organization settings resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` - update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): The FieldMask to use when updating the settings resource. - - If empty all mutable fields will be updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_organization_settings" not in self._inner_api_calls: - self._inner_api_calls[ - "update_organization_settings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_organization_settings, - default_retry=self._method_configs["UpdateOrganizationSettings"].retry, - default_timeout=self._method_configs[ - "UpdateOrganizationSettings" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateOrganizationSettingsRequest( - organization_settings=organization_settings, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [ - ("organization_settings.name", organization_settings.name) - ] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_organization_settings"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_source( - self, - source, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a source. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `source`: - >>> source = {} - >>> - >>> response = client.update_source(source) - - Args: - source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): Required. The source resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Source` - update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.FieldMask]): The FieldMask to use when updating the source resource. - - If empty all mutable fields will be updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_source" not in self._inner_api_calls: - self._inner_api_calls[ - "update_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_source, - default_retry=self._method_configs["UpdateSource"].retry, - default_timeout=self._method_configs["UpdateSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateSourceRequest( - source=source, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("source.name", source.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_security_marks( - self, - security_marks, - update_mask=None, - start_time=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates security marks. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `security_marks`: - >>> security_marks = {} - >>> - >>> response = client.update_security_marks(security_marks) - - Args: - security_marks (Union[dict, ~google.cloud.securitycenter_v1.types.SecurityMarks]): Required. The security marks resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` - update_mask (Union[dict, ~google.cloud.securitycenter_v1.types.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.". - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.FieldMask` - start_time (Union[dict, ~google.cloud.securitycenter_v1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.SecurityMarks` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_security_marks" not in self._inner_api_calls: - self._inner_api_calls[ - "update_security_marks" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_security_marks, - default_retry=self._method_configs["UpdateSecurityMarks"].retry, - default_timeout=self._method_configs["UpdateSecurityMarks"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateSecurityMarksRequest( - security_marks=security_marks, - update_mask=update_mask, - start_time=start_time, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("security_marks.name", security_marks.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_security_marks"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/securitycenter_v1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1/gapic/security_center_client_config.py deleted file mode 100644 index 111431ea..00000000 --- a/google/cloud/securitycenter_v1/gapic/security_center_client_config.py +++ /dev/null @@ -1,177 +0,0 @@ -config = { - "interfaces": { - "google.cloud.securitycenter.v1.SecurityCenter": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_2_codes": [], - "no_retry_codes": [], - "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_2_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, - }, - "methods": { - "CreateSource": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateFinding": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateNotificationConfig": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DeleteNotificationConfig": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetNotificationConfig": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetOrganizationSettings": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetSource": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GroupAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "GroupFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListNotificationConfigs": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "ListSources": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "RunAssetDiscovery": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "SetFindingState": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "SetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "UpdateFinding": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateNotificationConfig": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateOrganizationSettings": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateSource": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateSecurityMarks": { - "timeout_millis": 480000, - "retry_codes_name": "no_retry_2_codes", - "retry_params_name": "no_retry_2_params", - }, - }, - } - } -} diff --git a/google/cloud/securitycenter_v1/gapic/transports/__init__.py b/google/cloud/securitycenter_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py b/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py deleted file mode 100644 index 58249a17..00000000 --- a/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py +++ /dev/null @@ -1,436 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.securitycenter_v1.proto import securitycenter_service_pb2_grpc - - -class SecurityCenterGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.securitycenter.v1 SecurityCenter API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - channel=None, - credentials=None, - address="securitycenter.googleapis.com:443", - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "security_center_stub": securitycenter_service_pb2_grpc.SecurityCenterStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="securitycenter.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def create_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.create_source`. - - Creates a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].CreateSource - - @property - def create_finding(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.create_finding`. - - Creates a finding. The corresponding source must exist for finding creation - to succeed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].CreateFinding - - @property - def create_notification_config(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.create_notification_config`. - - Creates a notification config. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].CreateNotificationConfig - - @property - def delete_notification_config(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.delete_notification_config`. - - Deletes a notification config. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].DeleteNotificationConfig - - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. - - Gets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetIamPolicy - - @property - def get_notification_config(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_notification_config`. - - Gets a notification config. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetNotificationConfig - - @property - def get_organization_settings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_organization_settings`. - - Gets the settings for an organization. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetOrganizationSettings - - @property - def get_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_source`. - - Gets a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetSource - - @property - def group_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. - - Filters an organization's assets and groups them by their specified - properties. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupAssets - - @property - def group_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. - - 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 - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupFindings - - @property - def list_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_assets`. - - Lists an organization's assets. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListAssets - - @property - def list_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_findings`. - - 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: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListFindings - - @property - def list_notification_configs(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_notification_configs`. - - Lists notification configs. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListNotificationConfigs - - @property - def list_sources(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_sources`. - - Lists all sources belonging to an organization. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListSources - - @property - def run_asset_discovery(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.run_asset_discovery`. - - 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: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].RunAssetDiscovery - - @property - def set_finding_state(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.set_finding_state`. - - Updates the state of a finding. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].SetFindingState - - @property - def set_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.set_iam_policy`. - - Sets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].SetIamPolicy - - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. - - Returns the permissions that a caller has on the specified source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].TestIamPermissions - - @property - def update_finding(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_finding`. - - Creates or updates a finding. The corresponding source must exist for a - finding creation to succeed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateFinding - - @property - def update_notification_config(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_notification_config`. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateNotificationConfig - - @property - def update_organization_settings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_organization_settings`. - - Updates an organization's settings. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateOrganizationSettings - - @property - def update_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_source`. - - Updates a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateSource - - @property - def update_security_marks(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_security_marks`. - - Updates security marks. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateSecurityMarks diff --git a/google/cloud/securitycenter_v1/proto/__init__.py b/google/cloud/securitycenter_v1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1/proto/asset_pb2.py b/google/cloud/securitycenter_v1/proto/asset_pb2.py deleted file mode 100644 index 834f4147..00000000 --- a/google/cloud/securitycenter_v1/proto/asset_pb2.py +++ /dev/null @@ -1,623 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/asset.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2, -) -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/asset.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1P\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n0google/cloud/securitycenter_v1/proto/asset.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto\x1a\x39google/cloud/securitycenter_v1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\x92\x07\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x62\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32>.google.cloud.securitycenter.v1.Asset.SecurityCenterProperties\x12Z\n\x13resource_properties\x18\x07 \x03(\x0b\x32=.google.cloud.securitycenter.v1.Asset.ResourcePropertiesEntry\x12\x45\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32-.google.cloud.securitycenter.v1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x43\n\niam_policy\x18\x0b \x01(\x0b\x32/.google.cloud.securitycenter.v1.Asset.IamPolicy\x1a\x80\x02\n\x18SecurityCenterProperties\x12\x15\n\rresource_name\x18\x01 \x01(\t\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x12\x1d\n\x15resource_display_name\x18\x06 \x01(\t\x12$\n\x1cresource_parent_display_name\x18\x07 \x01(\t\x12%\n\x1dresource_project_display_name\x18\x08 \x01(\t\x1a \n\tIamPolicy\x12\x13\n\x0bpolicy_blob\x18\x01 \x01(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01:U\xea\x41R\n#securitycenter.googleapis.com/Asset\x12+organizations/{organization}/assets/{asset}B\xda\x01\n"com.google.cloud.securitycenter.v1P\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_ASSET_SECURITYCENTERPROPERTIES = _descriptor.Descriptor( - name="SecurityCenterProperties", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="resource_name", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties.resource_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_type", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties.resource_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_parent", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties.resource_parent", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_project", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties.resource_project", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_owners", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties.resource_owners", - index=4, - number=5, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_display_name", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties.resource_display_name", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_parent_display_name", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties.resource_parent_display_name", - index=6, - number=7, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_project_display_name", - full_name="google.cloud.securitycenter.v1.Asset.SecurityCenterProperties.resource_project_display_name", - index=7, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=718, - serialized_end=974, -) - -_ASSET_IAMPOLICY = _descriptor.Descriptor( - name="IamPolicy", - full_name="google.cloud.securitycenter.v1.Asset.IamPolicy", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="policy_blob", - full_name="google.cloud.securitycenter.v1.Asset.IamPolicy.policy_blob", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=976, - serialized_end=1008, -) - -_ASSET_RESOURCEPROPERTIESENTRY = _descriptor.Descriptor( - name="ResourcePropertiesEntry", - full_name="google.cloud.securitycenter.v1.Asset.ResourcePropertiesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1.Asset.ResourcePropertiesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1.Asset.ResourcePropertiesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1010, - serialized_end=1091, -) - -_ASSET = _descriptor.Descriptor( - name="Asset", - full_name="google.cloud.securitycenter.v1.Asset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.Asset.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_center_properties", - full_name="google.cloud.securitycenter.v1.Asset.security_center_properties", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_properties", - full_name="google.cloud.securitycenter.v1.Asset.resource_properties", - index=2, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_marks", - full_name="google.cloud.securitycenter.v1.Asset.security_marks", - index=3, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.securitycenter.v1.Asset.create_time", - index=4, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_time", - full_name="google.cloud.securitycenter.v1.Asset.update_time", - index=5, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="iam_policy", - full_name="google.cloud.securitycenter.v1.Asset.iam_policy", - index=6, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _ASSET_SECURITYCENTERPROPERTIES, - _ASSET_IAMPOLICY, - _ASSET_RESOURCEPROPERTIESENTRY, - ], - enum_types=[], - serialized_options=b"\352AR\n#securitycenter.googleapis.com/Asset\022+organizations/{organization}/assets/{asset}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=264, - serialized_end=1178, -) - -_ASSET_SECURITYCENTERPROPERTIES.containing_type = _ASSET -_ASSET_IAMPOLICY.containing_type = _ASSET -_ASSET_RESOURCEPROPERTIESENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_ASSET_RESOURCEPROPERTIESENTRY.containing_type = _ASSET -_ASSET.fields_by_name[ - "security_center_properties" -].message_type = _ASSET_SECURITYCENTERPROPERTIES -_ASSET.fields_by_name[ - "resource_properties" -].message_type = _ASSET_RESOURCEPROPERTIESENTRY -_ASSET.fields_by_name[ - "security_marks" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2._SECURITYMARKS -) -_ASSET.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name[ - "update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name["iam_policy"].message_type = _ASSET_IAMPOLICY -DESCRIPTOR.message_types_by_name["Asset"] = _ASSET -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Asset = _reflection.GeneratedProtocolMessageType( - "Asset", - (_message.Message,), - { - "SecurityCenterProperties": _reflection.GeneratedProtocolMessageType( - "SecurityCenterProperties", - (_message.Message,), - { - "DESCRIPTOR": _ASSET_SECURITYCENTERPROPERTIES, - "__module__": "google.cloud.securitycenter_v1.proto.asset_pb2", - "__doc__": """Security Command Center managed properties. These properties are - managed by Security Command Center and cannot be modified by the user. - - Attributes: - resource_name: - The full resource name of the Google Cloud resource this asset - represents. This field is immutable after create time. See: ht - tps://cloud.google.com/apis/design/resource_names#full_resourc - e_name - resource_type: - 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: - The full resource name of the immediate parent of the - resource. See: https://cloud.google.com/apis/design/resource_n - ames#full_resource_name - resource_project: - 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: - Owners of the Google Cloud resource. - resource_display_name: - The user defined display name for this resource. - resource_parent_display_name: - The user defined display name for the parent of this resource. - resource_project_display_name: - The user defined display name for the project of this - resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Asset.SecurityCenterProperties) - }, - ), - "IamPolicy": _reflection.GeneratedProtocolMessageType( - "IamPolicy", - (_message.Message,), - { - "DESCRIPTOR": _ASSET_IAMPOLICY, - "__module__": "google.cloud.securitycenter_v1.proto.asset_pb2", - "__doc__": """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: - The JSON representation of the Policy associated with the - asset. See - https://cloud.google.com/iam/reference/rest/v1/Policy for - format details. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Asset.IamPolicy) - }, - ), - "ResourcePropertiesEntry": _reflection.GeneratedProtocolMessageType( - "ResourcePropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _ASSET_RESOURCEPROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1.proto.asset_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Asset.ResourcePropertiesEntry) - }, - ), - "DESCRIPTOR": _ASSET, - "__module__": "google.cloud.securitycenter_v1.proto.asset_pb2", - "__doc__": """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: - The relative resource name of this asset. See: https://cloud.g - oogle.com/apis/design/resource_names#relative_resource_name - Example: “organizations/{organization_id}/assets/{asset_id}”. - security_center_properties: - Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified - by the user. - resource_properties: - Resource managed properties. These properties are managed and - defined by the Google Cloud resource and cannot be modified by - the user. - security_marks: - 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: - The time at which the asset was created in Security Command - Center. - update_time: - The time at which the asset was last updated, added, or - deleted in Security Command Center. - iam_policy: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Asset) - }, -) -_sym_db.RegisterMessage(Asset) -_sym_db.RegisterMessage(Asset.SecurityCenterProperties) -_sym_db.RegisterMessage(Asset.IamPolicy) -_sym_db.RegisterMessage(Asset.ResourcePropertiesEntry) - - -DESCRIPTOR._options = None -_ASSET_RESOURCEPROPERTIESENTRY._options = None -_ASSET._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/asset_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/asset_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/asset_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/proto/finding_pb2.py b/google/cloud/securitycenter_v1/proto/finding_pb2.py deleted file mode 100644 index 1730357e..00000000 --- a/google/cloud/securitycenter_v1/proto/finding_pb2.py +++ /dev/null @@ -1,459 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/finding.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2, -) -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/finding.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1P\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n2google/cloud/securitycenter_v1/proto/finding.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x39google/cloud/securitycenter_v1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xa4\x05\n\x07\x46inding\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06parent\x18\x02 \x01(\t\x12\x15\n\rresource_name\x18\x03 \x01(\t\x12<\n\x05state\x18\x04 \x01(\x0e\x32-.google.cloud.securitycenter.v1.Finding.State\x12\x10\n\x08\x63\x61tegory\x18\x05 \x01(\t\x12\x14\n\x0c\x65xternal_uri\x18\x06 \x01(\t\x12X\n\x11source_properties\x18\x07 \x03(\x0b\x32=.google.cloud.securitycenter.v1.Finding.SourcePropertiesEntry\x12J\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32-.google.cloud.securitycenter.v1.SecurityMarksB\x03\xe0\x41\x03\x12.\n\nevent_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63reate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1aO\n\x15SourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"8\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08INACTIVE\x10\x02:l\xea\x41i\n%securitycenter.googleapis.com/Finding\x12@organizations/{organization}/sources/{source}/findings/{finding}B\xda\x01\n"com.google.cloud.securitycenter.v1P\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_FINDING_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.securitycenter.v1.Finding.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INACTIVE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=809, - serialized_end=865, -) -_sym_db.RegisterEnumDescriptor(_FINDING_STATE) - - -_FINDING_SOURCEPROPERTIESENTRY = _descriptor.Descriptor( - name="SourcePropertiesEntry", - full_name="google.cloud.securitycenter.v1.Finding.SourcePropertiesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1.Finding.SourcePropertiesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1.Finding.SourcePropertiesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=728, - serialized_end=807, -) - -_FINDING = _descriptor.Descriptor( - name="Finding", - full_name="google.cloud.securitycenter.v1.Finding", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.Finding.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.Finding.parent", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_name", - full_name="google.cloud.securitycenter.v1.Finding.resource_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.securitycenter.v1.Finding.state", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.securitycenter.v1.Finding.category", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="external_uri", - full_name="google.cloud.securitycenter.v1.Finding.external_uri", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_properties", - full_name="google.cloud.securitycenter.v1.Finding.source_properties", - index=6, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_marks", - full_name="google.cloud.securitycenter.v1.Finding.security_marks", - index=7, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="event_time", - full_name="google.cloud.securitycenter.v1.Finding.event_time", - index=8, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.securitycenter.v1.Finding.create_time", - index=9, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_FINDING_SOURCEPROPERTIESENTRY,], - enum_types=[_FINDING_STATE,], - serialized_options=b"\352Ai\n%securitycenter.googleapis.com/Finding\022@organizations/{organization}/sources/{source}/findings/{finding}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=299, - serialized_end=975, -) - -_FINDING_SOURCEPROPERTIESENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_FINDING_SOURCEPROPERTIESENTRY.containing_type = _FINDING -_FINDING.fields_by_name["state"].enum_type = _FINDING_STATE -_FINDING.fields_by_name[ - "source_properties" -].message_type = _FINDING_SOURCEPROPERTIESENTRY -_FINDING.fields_by_name[ - "security_marks" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2._SECURITYMARKS -) -_FINDING.fields_by_name[ - "event_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_FINDING.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_FINDING_STATE.containing_type = _FINDING -DESCRIPTOR.message_types_by_name["Finding"] = _FINDING -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Finding = _reflection.GeneratedProtocolMessageType( - "Finding", - (_message.Message,), - { - "SourcePropertiesEntry": _reflection.GeneratedProtocolMessageType( - "SourcePropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _FINDING_SOURCEPROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1.proto.finding_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Finding.SourcePropertiesEntry) - }, - ), - "DESCRIPTOR": _FINDING, - "__module__": "google.cloud.securitycenter_v1.proto.finding_pb2", - "__doc__": """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: - 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: - The relative resource name of the source the finding belongs - to. See: https://cloud.google.com/apis/design/resource_names#r - elative_resource_name This field is immutable after creation - time. For example: - “organizations/{organization_id}/sources/{source_id}” - resource_name: - 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_nam - e 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: - The state of the finding. - category: - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. Example: - “XSS_FLASH_INJECTION” - external_uri: - 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: - 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: - 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: - 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: - The time at which the finding was created in Security Command - Center. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Finding) - }, -) -_sym_db.RegisterMessage(Finding) -_sym_db.RegisterMessage(Finding.SourcePropertiesEntry) - - -DESCRIPTOR._options = None -_FINDING_SOURCEPROPERTIESENTRY._options = None -_FINDING.fields_by_name["security_marks"]._options = None -_FINDING._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/finding_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/finding_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/finding_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/proto/notification_config_pb2.py b/google/cloud/securitycenter_v1/proto/notification_config_pb2.py deleted file mode 100644 index 5a318bba..00000000 --- a/google/cloud/securitycenter_v1/proto/notification_config_pb2.py +++ /dev/null @@ -1,285 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/notification_config.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/notification_config.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1B\027NotificationConfigProtoP\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1\352A@\n\033pubsub.googleapis.com/Topic\022!projects/{project}/topics/{topic}', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n>google/cloud/securitycenter_v1/proto/notification_config.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto"\xa0\x03\n\x12NotificationConfig\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x36\n\x0cpubsub_topic\x18\x03 \x01(\tB \xfa\x41\x1d\n\x1bpubsub.googleapis.com/Topic\x12\x1c\n\x0fservice_account\x18\x04 \x01(\tB\x03\xe0\x41\x03\x12^\n\x10streaming_config\x18\x05 \x01(\x0b\x32\x42.google.cloud.securitycenter.v1.NotificationConfig.StreamingConfigH\x00\x1a!\n\x0fStreamingConfig\x12\x0e\n\x06\x66ilter\x18\x01 \x01(\t:}\xea\x41z\n0securitycenter.googleapis.com/NotificationConfig\x12\x46organizations/{organization}/notificationConfigs/{notification_config}B\x0f\n\rnotify_configB\xb6\x02\n"com.google.cloud.securitycenter.v1B\x17NotificationConfigProtoP\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1\xea\x41@\n\x1bpubsub.googleapis.com/Topic\x12!projects/{project}/topics/{topic}b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_NOTIFICATIONCONFIG_STREAMINGCONFIG = _descriptor.Descriptor( - name="StreamingConfig", - full_name="google.cloud.securitycenter.v1.NotificationConfig.StreamingConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1.NotificationConfig.StreamingConfig.filter", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=428, - serialized_end=461, -) - -_NOTIFICATIONCONFIG = _descriptor.Descriptor( - name="NotificationConfig", - full_name="google.cloud.securitycenter.v1.NotificationConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.NotificationConfig.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.securitycenter.v1.NotificationConfig.description", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pubsub_topic", - full_name="google.cloud.securitycenter.v1.NotificationConfig.pubsub_topic", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\372A\035\n\033pubsub.googleapis.com/Topic", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="service_account", - full_name="google.cloud.securitycenter.v1.NotificationConfig.service_account", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="streaming_config", - full_name="google.cloud.securitycenter.v1.NotificationConfig.streaming_config", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_NOTIFICATIONCONFIG_STREAMINGCONFIG,], - enum_types=[], - serialized_options=b"\352Az\n0securitycenter.googleapis.com/NotificationConfig\022Forganizations/{organization}/notificationConfigs/{notification_config}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="notify_config", - full_name="google.cloud.securitycenter.v1.NotificationConfig.notify_config", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=189, - serialized_end=605, -) - -_NOTIFICATIONCONFIG_STREAMINGCONFIG.containing_type = _NOTIFICATIONCONFIG -_NOTIFICATIONCONFIG.fields_by_name[ - "streaming_config" -].message_type = _NOTIFICATIONCONFIG_STREAMINGCONFIG -_NOTIFICATIONCONFIG.oneofs_by_name["notify_config"].fields.append( - _NOTIFICATIONCONFIG.fields_by_name["streaming_config"] -) -_NOTIFICATIONCONFIG.fields_by_name[ - "streaming_config" -].containing_oneof = _NOTIFICATIONCONFIG.oneofs_by_name["notify_config"] -DESCRIPTOR.message_types_by_name["NotificationConfig"] = _NOTIFICATIONCONFIG -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -NotificationConfig = _reflection.GeneratedProtocolMessageType( - "NotificationConfig", - (_message.Message,), - { - "StreamingConfig": _reflection.GeneratedProtocolMessageType( - "StreamingConfig", - (_message.Message,), - { - "DESCRIPTOR": _NOTIFICATIONCONFIG_STREAMINGCONFIG, - "__module__": "google.cloud.securitycenter_v1.proto.notification_config_pb2", - "__doc__": """The config for streaming-based notifications, which send each event as - soon as it is detected. - - Attributes: - filter: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.NotificationConfig.StreamingConfig) - }, - ), - "DESCRIPTOR": _NOTIFICATIONCONFIG, - "__module__": "google.cloud.securitycenter_v1.proto.notification_config_pb2", - "__doc__": """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: - The relative resource name of this notification config. See: h - ttps://cloud.google.com/apis/design/resource_names#relative_re - source_name Example: “organizations/{organization_id}/notifica - tionConfigs/notify_public_bucket”. - description: - The description of the notification config (max of 1024 - characters). - pubsub_topic: - The PubSub topic to send notifications to. Its format is - “projects/[project_id]/topics/[topic]”. - service_account: - Output only. The service account that needs - “pubsub.topics.publish” permission to publish to the PubSub - topic. - notify_config: - The config for triggering notifications. - streaming_config: - The config for triggering streaming-based notifications. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.NotificationConfig) - }, -) -_sym_db.RegisterMessage(NotificationConfig) -_sym_db.RegisterMessage(NotificationConfig.StreamingConfig) - - -DESCRIPTOR._options = None -_NOTIFICATIONCONFIG.fields_by_name["pubsub_topic"]._options = None -_NOTIFICATIONCONFIG.fields_by_name["service_account"]._options = None -_NOTIFICATIONCONFIG._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/notification_config_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/notification_config_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/notification_config_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/proto/notification_message_pb2.py b/google/cloud/securitycenter_v1/proto/notification_message_pb2.py deleted file mode 100644 index a7bd5d51..00000000 --- a/google/cloud/securitycenter_v1/proto/notification_message_pb2.py +++ /dev/null @@ -1,172 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/notification_message.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.cloud.securitycenter_v1.proto import ( - finding_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - resource_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_resource__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/notification_message.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1B\030NotificationMessageProtoP\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n?google/cloud/securitycenter_v1/proto/notification_message.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x32google/cloud/securitycenter_v1/proto/finding.proto\x1a\x33google/cloud/securitycenter_v1/proto/resource.proto"\xb8\x01\n\x13NotificationMessage\x12 \n\x18notification_config_name\x18\x01 \x01(\t\x12:\n\x07\x66inding\x18\x02 \x01(\x0b\x32\'.google.cloud.securitycenter.v1.FindingH\x00\x12:\n\x08resource\x18\x03 \x01(\x0b\x32(.google.cloud.securitycenter.v1.ResourceB\x07\n\x05\x65ventB\xf4\x01\n"com.google.cloud.securitycenter.v1B\x18NotificationMessageProtoP\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_NOTIFICATIONMESSAGE = _descriptor.Descriptor( - name="NotificationMessage", - full_name="google.cloud.securitycenter.v1.NotificationMessage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="notification_config_name", - full_name="google.cloud.securitycenter.v1.NotificationMessage.notification_config_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="finding", - full_name="google.cloud.securitycenter.v1.NotificationMessage.finding", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.securitycenter.v1.NotificationMessage.resource", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="event", - full_name="google.cloud.securitycenter.v1.NotificationMessage.event", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=235, - serialized_end=419, -) - -_NOTIFICATIONMESSAGE.fields_by_name[ - "finding" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2._FINDING -) -_NOTIFICATIONMESSAGE.fields_by_name[ - "resource" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_resource__pb2._RESOURCE -) -_NOTIFICATIONMESSAGE.oneofs_by_name["event"].fields.append( - _NOTIFICATIONMESSAGE.fields_by_name["finding"] -) -_NOTIFICATIONMESSAGE.fields_by_name[ - "finding" -].containing_oneof = _NOTIFICATIONMESSAGE.oneofs_by_name["event"] -DESCRIPTOR.message_types_by_name["NotificationMessage"] = _NOTIFICATIONMESSAGE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -NotificationMessage = _reflection.GeneratedProtocolMessageType( - "NotificationMessage", - (_message.Message,), - { - "DESCRIPTOR": _NOTIFICATIONMESSAGE, - "__module__": "google.cloud.securitycenter_v1.proto.notification_message_pb2", - "__doc__": """Cloud SCC’s Notification - - Attributes: - notification_config_name: - Name of the notification config that generated current - notification. - event: - Notification Event. - finding: - If it’s a Finding based notification config, this field will - be populated. - resource: - The Cloud resource tied to this notification’s Finding. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.NotificationMessage) - }, -) -_sym_db.RegisterMessage(NotificationMessage) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/notification_message_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/notification_message_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/notification_message_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/proto/organization_settings_pb2.py b/google/cloud/securitycenter_v1/proto/organization_settings_pb2.py deleted file mode 100644 index bd872c24..00000000 --- a/google/cloud/securitycenter_v1/proto/organization_settings_pb2.py +++ /dev/null @@ -1,272 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/organization_settings.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/organization_settings.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1P\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n@google/cloud/securitycenter_v1/proto/organization_settings.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto"\x8a\x04\n\x14OrganizationSettings\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1e\n\x16\x65nable_asset_discovery\x18\x02 \x01(\x08\x12i\n\x16\x61sset_discovery_config\x18\x03 \x01(\x0b\x32I.google.cloud.securitycenter.v1.OrganizationSettings.AssetDiscoveryConfig\x1a\xec\x01\n\x14\x41ssetDiscoveryConfig\x12\x13\n\x0bproject_ids\x18\x01 \x03(\t\x12o\n\x0einclusion_mode\x18\x02 \x01(\x0e\x32W.google.cloud.securitycenter.v1.OrganizationSettings.AssetDiscoveryConfig.InclusionMode"N\n\rInclusionMode\x12\x1e\n\x1aINCLUSION_MODE_UNSPECIFIED\x10\x00\x12\x10\n\x0cINCLUDE_ONLY\x10\x01\x12\x0b\n\x07\x45XCLUDE\x10\x02:j\xea\x41g\n2securitycenter.googleapis.com/OrganizationSettings\x12\x31organizations/{organization}/organizationSettingsB\xda\x01\n"com.google.cloud.securitycenter.v1P\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE = _descriptor.EnumDescriptor( - name="InclusionMode", - full_name="google.cloud.securitycenter.v1.OrganizationSettings.AssetDiscoveryConfig.InclusionMode", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="INCLUSION_MODE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INCLUDE_ONLY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="EXCLUDE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=494, - serialized_end=572, -) -_sym_db.RegisterEnumDescriptor(_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE) - - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG = _descriptor.Descriptor( - name="AssetDiscoveryConfig", - full_name="google.cloud.securitycenter.v1.OrganizationSettings.AssetDiscoveryConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="project_ids", - full_name="google.cloud.securitycenter.v1.OrganizationSettings.AssetDiscoveryConfig.project_ids", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="inclusion_mode", - full_name="google.cloud.securitycenter.v1.OrganizationSettings.AssetDiscoveryConfig.inclusion_mode", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=336, - serialized_end=572, -) - -_ORGANIZATIONSETTINGS = _descriptor.Descriptor( - name="OrganizationSettings", - full_name="google.cloud.securitycenter.v1.OrganizationSettings", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.OrganizationSettings.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="enable_asset_discovery", - full_name="google.cloud.securitycenter.v1.OrganizationSettings.enable_asset_discovery", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_discovery_config", - full_name="google.cloud.securitycenter.v1.OrganizationSettings.asset_discovery_config", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG,], - enum_types=[], - serialized_options=b"\352Ag\n2securitycenter.googleapis.com/OrganizationSettings\0221organizations/{organization}/organizationSettings", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=158, - serialized_end=680, -) - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG.fields_by_name[ - "inclusion_mode" -].enum_type = _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG.containing_type = _ORGANIZATIONSETTINGS -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE.containing_type = ( - _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG -) -_ORGANIZATIONSETTINGS.fields_by_name[ - "asset_discovery_config" -].message_type = _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG -DESCRIPTOR.message_types_by_name["OrganizationSettings"] = _ORGANIZATIONSETTINGS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -OrganizationSettings = _reflection.GeneratedProtocolMessageType( - "OrganizationSettings", - (_message.Message,), - { - "AssetDiscoveryConfig": _reflection.GeneratedProtocolMessageType( - "AssetDiscoveryConfig", - (_message.Message,), - { - "DESCRIPTOR": _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG, - "__module__": "google.cloud.securitycenter_v1.proto.organization_settings_pb2", - "__doc__": """The configuration used for Asset Discovery runs. - - Attributes: - project_ids: - The project ids to use for filtering asset discovery. - inclusion_mode: - The mode to use for filtering asset discovery. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.OrganizationSettings.AssetDiscoveryConfig) - }, - ), - "DESCRIPTOR": _ORGANIZATIONSETTINGS, - "__module__": "google.cloud.securitycenter_v1.proto.organization_settings_pb2", - "__doc__": """User specified settings that are attached to the Security Command - Center organization. - - Attributes: - name: - 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: - 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: - The configuration used for Asset Discovery runs. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.OrganizationSettings) - }, -) -_sym_db.RegisterMessage(OrganizationSettings) -_sym_db.RegisterMessage(OrganizationSettings.AssetDiscoveryConfig) - - -DESCRIPTOR._options = None -_ORGANIZATIONSETTINGS._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/organization_settings_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/organization_settings_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/organization_settings_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/proto/resource_pb2.py b/google/cloud/securitycenter_v1/proto/resource_pb2.py deleted file mode 100644 index c9c16fef..00000000 --- a/google/cloud/securitycenter_v1/proto/resource_pb2.py +++ /dev/null @@ -1,178 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/resource.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/resource.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1B\rResourceProtoP\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n3google/cloud/securitycenter_v1/proto/resource.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto"t\n\x08Resource\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x1c\n\x14project_display_name\x18\x03 \x01(\t\x12\x0e\n\x06parent\x18\x04 \x01(\t\x12\x1b\n\x13parent_display_name\x18\x05 \x01(\tB\xe9\x01\n"com.google.cloud.securitycenter.v1B\rResourceProtoP\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1b\x06proto3', - dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,], -) - - -_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.securitycenter.v1.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.Resource.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project", - full_name="google.cloud.securitycenter.v1.Resource.project", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project_display_name", - full_name="google.cloud.securitycenter.v1.Resource.project_display_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.Resource.parent", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent_display_name", - full_name="google.cloud.securitycenter.v1.Resource.parent_display_name", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=117, - serialized_end=233, -) - -DESCRIPTOR.message_types_by_name["Resource"] = _RESOURCE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Resource = _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _RESOURCE, - "__module__": "google.cloud.securitycenter_v1.proto.resource_pb2", - "__doc__": """Information related to the Google Cloud resource. - - Attributes: - name: - The full resource name of the resource. See: https://cloud.goo - gle.com/apis/design/resource_names#full_resource_name - project: - The full resource name of project that the resource belongs - to. - project_display_name: - The human readable name of project that the resource belongs - to. - parent: - The full resource name of resource’s parent. - parent_display_name: - The human readable name of resource’s parent. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Resource) - }, -) -_sym_db.RegisterMessage(Resource) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/resource_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/resource_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/resource_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2.py b/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2.py deleted file mode 100644 index c4e2b2bd..00000000 --- a/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2.py +++ /dev/null @@ -1,173 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/run_asset_discovery_response.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/run_asset_discovery_response.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1P\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nGgoogle/cloud/securitycenter_v1/proto/run_asset_discovery_response.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1egoogle/protobuf/duration.proto"\xe7\x01\n\x19RunAssetDiscoveryResponse\x12N\n\x05state\x18\x01 \x01(\x0e\x32?.google.cloud.securitycenter.v1.RunAssetDiscoveryResponse.State\x12+\n\x08\x64uration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"M\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\r\n\tCOMPLETED\x10\x01\x12\x0e\n\nSUPERSEDED\x10\x02\x12\x0e\n\nTERMINATED\x10\x03\x42\xda\x01\n"com.google.cloud.securitycenter.v1P\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - ], -) - - -_RUNASSETDISCOVERYRESPONSE_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.securitycenter.v1.RunAssetDiscoveryResponse.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="COMPLETED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUPERSEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TERMINATED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=324, - serialized_end=401, -) -_sym_db.RegisterEnumDescriptor(_RUNASSETDISCOVERYRESPONSE_STATE) - - -_RUNASSETDISCOVERYRESPONSE = _descriptor.Descriptor( - name="RunAssetDiscoveryResponse", - full_name="google.cloud.securitycenter.v1.RunAssetDiscoveryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.securitycenter.v1.RunAssetDiscoveryResponse.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="duration", - full_name="google.cloud.securitycenter.v1.RunAssetDiscoveryResponse.duration", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_RUNASSETDISCOVERYRESPONSE_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=170, - serialized_end=401, -) - -_RUNASSETDISCOVERYRESPONSE.fields_by_name[ - "state" -].enum_type = _RUNASSETDISCOVERYRESPONSE_STATE -_RUNASSETDISCOVERYRESPONSE.fields_by_name[ - "duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_RUNASSETDISCOVERYRESPONSE_STATE.containing_type = _RUNASSETDISCOVERYRESPONSE -DESCRIPTOR.message_types_by_name[ - "RunAssetDiscoveryResponse" -] = _RUNASSETDISCOVERYRESPONSE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -RunAssetDiscoveryResponse = _reflection.GeneratedProtocolMessageType( - "RunAssetDiscoveryResponse", - (_message.Message,), - { - "DESCRIPTOR": _RUNASSETDISCOVERYRESPONSE, - "__module__": "google.cloud.securitycenter_v1.proto.run_asset_discovery_response_pb2", - "__doc__": """Response of asset discovery run - - Attributes: - state: - The state of an asset discovery run. - duration: - The duration between asset discovery run start and end - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.RunAssetDiscoveryResponse) - }, -) -_sym_db.RegisterMessage(RunAssetDiscoveryResponse) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/proto/security_marks_pb2.py b/google/cloud/securitycenter_v1/proto/security_marks_pb2.py deleted file mode 100644 index c110683b..00000000 --- a/google/cloud/securitycenter_v1/proto/security_marks_pb2.py +++ /dev/null @@ -1,201 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/security_marks.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/security_marks.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1P\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/securitycenter_v1/proto/security_marks.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto"\xd3\x02\n\rSecurityMarks\x12\x0c\n\x04name\x18\x01 \x01(\t\x12G\n\x05marks\x18\x02 \x03(\x0b\x32\x38.google.cloud.securitycenter.v1.SecurityMarks.MarksEntry\x1a,\n\nMarksEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01:\xbc\x01\xea\x41\xb8\x01\n+securitycenter.googleapis.com/SecurityMarks\x12\x39organizations/{organization}/assets/{asset}/securityMarks\x12Norganizations/{organization}/sources/{source}/findings/{finding}/securityMarksB\xda\x01\n"com.google.cloud.securitycenter.v1P\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_SECURITYMARKS_MARKSENTRY = _descriptor.Descriptor( - name="MarksEntry", - full_name="google.cloud.securitycenter.v1.SecurityMarks.MarksEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1.SecurityMarks.MarksEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1.SecurityMarks.MarksEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=255, - serialized_end=299, -) - -_SECURITYMARKS = _descriptor.Descriptor( - name="SecurityMarks", - full_name="google.cloud.securitycenter.v1.SecurityMarks", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.SecurityMarks.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="marks", - full_name="google.cloud.securitycenter.v1.SecurityMarks.marks", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_SECURITYMARKS_MARKSENTRY,], - enum_types=[], - serialized_options=b"\352A\270\001\n+securitycenter.googleapis.com/SecurityMarks\0229organizations/{organization}/assets/{asset}/securityMarks\022Norganizations/{organization}/sources/{source}/findings/{finding}/securityMarks", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=151, - serialized_end=490, -) - -_SECURITYMARKS_MARKSENTRY.containing_type = _SECURITYMARKS -_SECURITYMARKS.fields_by_name["marks"].message_type = _SECURITYMARKS_MARKSENTRY -DESCRIPTOR.message_types_by_name["SecurityMarks"] = _SECURITYMARKS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -SecurityMarks = _reflection.GeneratedProtocolMessageType( - "SecurityMarks", - (_message.Message,), - { - "MarksEntry": _reflection.GeneratedProtocolMessageType( - "MarksEntry", - (_message.Message,), - { - "DESCRIPTOR": _SECURITYMARKS_MARKSENTRY, - "__module__": "google.cloud.securitycenter_v1.proto.security_marks_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.SecurityMarks.MarksEntry) - }, - ), - "DESCRIPTOR": _SECURITYMARKS, - "__module__": "google.cloud.securitycenter_v1.proto.security_marks_pb2", - "__doc__": """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: - 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: - 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) - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.SecurityMarks) - }, -) -_sym_db.RegisterMessage(SecurityMarks) -_sym_db.RegisterMessage(SecurityMarks.MarksEntry) - - -DESCRIPTOR._options = None -_SECURITYMARKS_MARKSENTRY._options = None -_SECURITYMARKS._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/security_marks_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/security_marks_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/security_marks_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2.py b/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2.py deleted file mode 100644 index 4bb4b007..00000000 --- a/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2.py +++ /dev/null @@ -1,4233 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/securitycenter_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.cloud.securitycenter_v1.proto import ( - run_asset_discovery_response_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_run__asset__discovery__response__pb2, -) -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1.proto import ( - asset_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_asset__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - finding_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - notification_config_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - organization_settings_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - source_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - -from google.cloud.securitycenter_v1.proto.run_asset_discovery_response_pb2 import * - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/securitycenter_service.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1P\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nAgoogle/cloud/securitycenter_v1/proto/securitycenter_service.proto\x12\x1egoogle.cloud.securitycenter.v1\x1aGgoogle/cloud/securitycenter_v1/proto/run_asset_discovery_response.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x30google/cloud/securitycenter_v1/proto/asset.proto\x1a\x32google/cloud/securitycenter_v1/proto/finding.proto\x1a>google/cloud/securitycenter_v1/proto/notification_config.proto\x1a@google/cloud/securitycenter_v1/proto/organization_settings.proto\x1a\x39google/cloud/securitycenter_v1/proto/security_marks.proto\x1a\x31google/cloud/securitycenter_v1/proto/source.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a#google/longrunning/operations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xac\x01\n\x14\x43reateFindingRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x17\n\nfinding_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12=\n\x07\x66inding\x18\x03 \x01(\x0b\x32\'.google.cloud.securitycenter.v1.FindingB\x03\xe0\x41\x02"\xd9\x01\n\x1f\x43reateNotificationConfigRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x16\n\tconfig_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12T\n\x13notification_config\x18\x03 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1.NotificationConfigB\x03\xe0\x41\x02"\x9c\x01\n\x13\x43reateSourceRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12;\n\x06source\x18\x02 \x01(\x0b\x32&.google.cloud.securitycenter.v1.SourceB\x03\xe0\x41\x02"i\n\x1f\x44\x65leteNotificationConfigRequest\x12\x46\n\x04name\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0securitycenter.googleapis.com/NotificationConfig"f\n\x1cGetNotificationConfigRequest\x12\x46\n\x04name\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0securitycenter.googleapis.com/NotificationConfig"j\n\x1eGetOrganizationSettingsRequest\x12H\n\x04name\x18\x01 \x01(\tB:\xe0\x41\x02\xfa\x41\x34\n2securitycenter.googleapis.com/OrganizationSettings"N\n\x10GetSourceRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source"\x90\x02\n\x12GroupAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12\x33\n\x10\x63ompare_duration\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12-\n\tread_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xb8\x01\n\x13GroupAssetsResponse\x12\x45\n\x10group_by_results\x18\x01 \x03(\x0b\x32+.google.cloud.securitycenter.v1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\x86\x02\n\x14GroupFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xba\x01\n\x15GroupFindingsResponse\x12\x45\n\x10group_by_results\x18\x01 \x03(\x0b\x32+.google.cloud.securitycenter.v1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\xb8\x01\n\x0bGroupResult\x12O\n\nproperties\x18\x01 \x03(\x0b\x32;.google.cloud.securitycenter.v1.GroupResult.PropertiesEntry\x12\r\n\x05\x63ount\x18\x02 \x01(\x03\x1aI\n\x0fPropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"\x91\x01\n\x1eListNotificationConfigsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x03 \x01(\x05"\x8c\x01\n\x1fListNotificationConfigsResponse\x12P\n\x14notification_configs\x18\x01 \x03(\x0b\x32\x32.google.cloud.securitycenter.v1.NotificationConfig\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\x85\x01\n\x12ListSourcesRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x07 \x01(\x05"g\n\x13ListSourcesResponse\x12\x37\n\x07sources\x18\x01 \x03(\x0b\x32&.google.cloud.securitycenter.v1.Source\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\xbf\x02\n\x11ListAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x33\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x01\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xc3\x03\n\x12ListAssetsResponse\x12`\n\x13list_assets_results\x18\x01 \x03(\x0b\x32\x43.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\xee\x01\n\x10ListAssetsResult\x12\x34\n\x05\x61sset\x18\x01 \x01(\x0b\x32%.google.cloud.securitycenter.v1.Asset\x12\x65\n\x0cstate_change\x18\x02 \x01(\x0e\x32O.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult.StateChange"=\n\x0bStateChange\x12\n\n\x06UNUSED\x10\x00\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x01\x12\x0b\n\x07REMOVED\x10\x02\x12\n\n\x06\x41\x43TIVE\x10\x03"\xb5\x02\n\x13ListFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x33\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x01\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xc9\x05\n\x14ListFindingsResponse\x12\x66\n\x15list_findings_results\x18\x01 \x03(\x0b\x32G.google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\xec\x03\n\x12ListFindingsResult\x12\x38\n\x07\x66inding\x18\x01 \x01(\x0b\x32\'.google.cloud.securitycenter.v1.Finding\x12i\n\x0cstate_change\x18\x02 \x01(\x0e\x32S.google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.StateChange\x12\x62\n\x08resource\x18\x03 \x01(\x0b\x32P.google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.Resource\x1a~\n\x08Resource\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cproject_name\x18\x02 \x01(\t\x12\x1c\n\x14project_display_name\x18\x03 \x01(\t\x12\x13\n\x0bparent_name\x18\x04 \x01(\t\x12\x1b\n\x13parent_display_name\x18\x05 \x01(\t"M\n\x0bStateChange\x12\n\n\x06UNUSED\x10\x00\x12\x0b\n\x07\x43HANGED\x10\x01\x12\r\n\tUNCHANGED\x10\x02\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x03\x12\x0b\n\x07REMOVED\x10\x04"\xcd\x01\n\x16SetFindingStateRequest\x12;\n\x04name\x18\x01 \x01(\tB-\xe0\x41\x02\xfa\x41\'\n%securitycenter.googleapis.com/Finding\x12\x41\n\x05state\x18\x02 \x01(\x0e\x32-.google.cloud.securitycenter.v1.Finding.StateB\x03\xe0\x41\x02\x12\x33\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x02"d\n\x18RunAssetDiscoveryRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization"\x86\x01\n\x14UpdateFindingRequest\x12=\n\x07\x66inding\x18\x01 \x01(\x0b\x32\'.google.cloud.securitycenter.v1.FindingB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xa8\x01\n\x1fUpdateNotificationConfigRequest\x12T\n\x13notification_config\x18\x01 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1.NotificationConfigB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xae\x01\n!UpdateOrganizationSettingsRequest\x12X\n\x15organization_settings\x18\x01 \x01(\x0b\x32\x34.google.cloud.securitycenter.v1.OrganizationSettingsB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\x83\x01\n\x13UpdateSourceRequest\x12;\n\x06source\x18\x01 \x01(\x0b\x32&.google.cloud.securitycenter.v1.SourceB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xc9\x01\n\x1aUpdateSecurityMarksRequest\x12J\n\x0esecurity_marks\x18\x01 \x01(\x0b\x32-.google.cloud.securitycenter.v1.SecurityMarksB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12.\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\xd6&\n\x0eSecurityCenter\x12\xb1\x01\n\x0c\x43reateSource\x12\x33.google.cloud.securitycenter.v1.CreateSourceRequest\x1a&.google.cloud.securitycenter.v1.Source"D\x82\xd3\xe4\x93\x02."$/v1/{parent=organizations/*}/sources:\x06source\xda\x41\rparent,source\x12\xcc\x01\n\rCreateFinding\x12\x34.google.cloud.securitycenter.v1.CreateFindingRequest\x1a\'.google.cloud.securitycenter.v1.Finding"\\\x82\xd3\xe4\x93\x02:"//v1/{parent=organizations/*/sources/*}/findings:\x07\x66inding\xda\x41\x19parent,finding_id,finding\x12\xa3\x02\n\x18\x43reateNotificationConfig\x12?.google.cloud.securitycenter.v1.CreateNotificationConfigRequest\x1a\x32.google.cloud.securitycenter.v1.NotificationConfig"\x91\x01\x82\xd3\xe4\x93\x02G"0/v1/{parent=organizations/*}/notificationConfigs:\x13notification_config\xda\x41$parent,config_id,notification_config\xda\x41\x1aparent,notification_config\x12\xb4\x01\n\x18\x44\x65leteNotificationConfig\x12?.google.cloud.securitycenter.v1.DeleteNotificationConfigRequest\x1a\x16.google.protobuf.Empty"?\x82\xd3\xe4\x93\x02\x32*0/v1/{name=organizations/*/notificationConfigs/*}\xda\x41\x04name\x12\x96\x01\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"K\x82\xd3\xe4\x93\x02:"5/v1/{resource=organizations/*/sources/*}:getIamPolicy:\x01*\xda\x41\x08resource\x12\xca\x01\n\x15GetNotificationConfig\x12<.google.cloud.securitycenter.v1.GetNotificationConfigRequest\x1a\x32.google.cloud.securitycenter.v1.NotificationConfig"?\x82\xd3\xe4\x93\x02\x32\x12\x30/v1/{name=organizations/*/notificationConfigs/*}\xda\x41\x04name\x12\xcf\x01\n\x17GetOrganizationSettings\x12>.google.cloud.securitycenter.v1.GetOrganizationSettingsRequest\x1a\x34.google.cloud.securitycenter.v1.OrganizationSettings">\x82\xd3\xe4\x93\x02\x31\x12//v1/{name=organizations/*/organizationSettings}\xda\x41\x04name\x12\x9a\x01\n\tGetSource\x12\x30.google.cloud.securitycenter.v1.GetSourceRequest\x1a&.google.cloud.securitycenter.v1.Source"3\x82\xd3\xe4\x93\x02&\x12$/v1/{name=organizations/*/sources/*}\xda\x41\x04name\x12\xac\x01\n\x0bGroupAssets\x12\x32.google.cloud.securitycenter.v1.GroupAssetsRequest\x1a\x33.google.cloud.securitycenter.v1.GroupAssetsResponse"4\x82\xd3\xe4\x93\x02.")/v1/{parent=organizations/*}/assets:group:\x01*\x12\xd0\x01\n\rGroupFindings\x12\x34.google.cloud.securitycenter.v1.GroupFindingsRequest\x1a\x35.google.cloud.securitycenter.v1.GroupFindingsResponse"R\x82\xd3\xe4\x93\x02:"5/v1/{parent=organizations/*/sources/*}/findings:group:\x01*\xda\x41\x0fparent,group_by\x12\xa0\x01\n\nListAssets\x12\x31.google.cloud.securitycenter.v1.ListAssetsRequest\x1a\x32.google.cloud.securitycenter.v1.ListAssetsResponse"+\x82\xd3\xe4\x93\x02%\x12#/v1/{parent=organizations/*}/assets\x12\xb2\x01\n\x0cListFindings\x12\x33.google.cloud.securitycenter.v1.ListFindingsRequest\x1a\x34.google.cloud.securitycenter.v1.ListFindingsResponse"7\x82\xd3\xe4\x93\x02\x31\x12//v1/{parent=organizations/*/sources/*}/findings\x12\xdd\x01\n\x17ListNotificationConfigs\x12>.google.cloud.securitycenter.v1.ListNotificationConfigsRequest\x1a?.google.cloud.securitycenter.v1.ListNotificationConfigsResponse"A\x82\xd3\xe4\x93\x02\x32\x12\x30/v1/{parent=organizations/*}/notificationConfigs\xda\x41\x06parent\x12\xad\x01\n\x0bListSources\x12\x32.google.cloud.securitycenter.v1.ListSourcesRequest\x1a\x33.google.cloud.securitycenter.v1.ListSourcesResponse"5\x82\xd3\xe4\x93\x02&\x12$/v1/{parent=organizations/*}/sources\xda\x41\x06parent\x12\x87\x02\n\x11RunAssetDiscovery\x12\x38.google.cloud.securitycenter.v1.RunAssetDiscoveryRequest\x1a\x1d.google.longrunning.Operation"\x98\x01\x82\xd3\xe4\x93\x02\x35"0/v1/{parent=organizations/*}/assets:runDiscovery:\x01*\xda\x41\x06parent\xca\x41Q\n8google.cloud.securitycenter.v1.RunAssetDiscoveryResponse\x12\x15google.protobuf.Empty\x12\xcf\x01\n\x0fSetFindingState\x12\x36.google.cloud.securitycenter.v1.SetFindingStateRequest\x1a\'.google.cloud.securitycenter.v1.Finding"[\x82\xd3\xe4\x93\x02="8/v1/{name=organizations/*/sources/*/findings/*}:setState:\x01*\xda\x41\x15name,state,start_time\x12\x9d\x01\n\x0cSetIamPolicy\x12".google.iam.v1.SetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"R\x82\xd3\xe4\x93\x02:"5/v1/{resource=organizations/*/sources/*}:setIamPolicy:\x01*\xda\x41\x0fresource,policy\x12\xc8\x01\n\x12TestIamPermissions\x12(.google.iam.v1.TestIamPermissionsRequest\x1a).google.iam.v1.TestIamPermissionsResponse"]\x82\xd3\xe4\x93\x02@";/v1/{resource=organizations/*/sources/*}:testIamPermissions:\x01*\xda\x41\x14resource,permissions\x12\xc2\x01\n\rUpdateFinding\x12\x34.google.cloud.securitycenter.v1.UpdateFindingRequest\x1a\'.google.cloud.securitycenter.v1.Finding"R\x82\xd3\xe4\x93\x02\x42\x32\x37/v1/{finding.name=organizations/*/sources/*/findings/*}:\x07\x66inding\xda\x41\x07\x66inding\x12\xab\x02\n\x18UpdateNotificationConfig\x12?.google.cloud.securitycenter.v1.UpdateNotificationConfigRequest\x1a\x32.google.cloud.securitycenter.v1.NotificationConfig"\x99\x01\x82\xd3\xe4\x93\x02[2D/v1/{notification_config.name=organizations/*/notificationConfigs/*}:\x13notification_config\xda\x41\x13notification_config\xda\x41\x1fnotification_config,update_mask\x12\x93\x02\n\x1aUpdateOrganizationSettings\x12\x41.google.cloud.securitycenter.v1.UpdateOrganizationSettingsRequest\x1a\x34.google.cloud.securitycenter.v1.OrganizationSettings"|\x82\xd3\xe4\x93\x02^2E/v1/{organization_settings.name=organizations/*/organizationSettings}:\x15organization_settings\xda\x41\x15organization_settings\x12\xb1\x01\n\x0cUpdateSource\x12\x33.google.cloud.securitycenter.v1.UpdateSourceRequest\x1a&.google.cloud.securitycenter.v1.Source"D\x82\xd3\xe4\x93\x02\x35\x32+/v1/{source.name=organizations/*/sources/*}:\x06source\xda\x41\x06source\x12\xcd\x02\n\x13UpdateSecurityMarks\x12:.google.cloud.securitycenter.v1.UpdateSecurityMarksRequest\x1a-.google.cloud.securitycenter.v1.SecurityMarks"\xca\x01\x82\xd3\xe4\x93\x02\xb2\x01\x32@/v1/{security_marks.name=organizations/*/assets/*/securityMarks}:\x0esecurity_marksZ^2L/v1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}:\x0esecurity_marks\xda\x41\x0esecurity_marks\x1aQ\xca\x41\x1dsecuritycenter.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xda\x01\n"com.google.cloud.securitycenter.v1P\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1P\x00\x62\x06proto3', - dependencies=[ - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_run__asset__discovery__response__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_asset__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_iam__policy__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], - public_dependencies=[ - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_run__asset__discovery__response__pb2.DESCRIPTOR, - ], -) - - -_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE = _descriptor.EnumDescriptor( - name="StateChange", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult.StateChange", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNUSED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ADDED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="REMOVED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=4187, - serialized_end=4248, -) -_sym_db.RegisterEnumDescriptor(_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE) - -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE = _descriptor.EnumDescriptor( - name="StateChange", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.StateChange", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNUSED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHANGED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UNCHANGED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ADDED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="REMOVED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=5199, - serialized_end=5276, -) -_sym_db.RegisterEnumDescriptor(_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE) - - -_CREATEFINDINGREQUEST = _descriptor.Descriptor( - name="CreateFindingRequest", - full_name="google.cloud.securitycenter.v1.CreateFindingRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.CreateFindingRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$securitycenter.googleapis.com/Source", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="finding_id", - full_name="google.cloud.securitycenter.v1.CreateFindingRequest.finding_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="finding", - full_name="google.cloud.securitycenter.v1.CreateFindingRequest.finding", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=887, - serialized_end=1059, -) - - -_CREATENOTIFICATIONCONFIGREQUEST = _descriptor.Descriptor( - name="CreateNotificationConfigRequest", - full_name="google.cloud.securitycenter.v1.CreateNotificationConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.CreateNotificationConfigRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="config_id", - full_name="google.cloud.securitycenter.v1.CreateNotificationConfigRequest.config_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="notification_config", - full_name="google.cloud.securitycenter.v1.CreateNotificationConfigRequest.notification_config", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1062, - serialized_end=1279, -) - - -_CREATESOURCEREQUEST = _descriptor.Descriptor( - name="CreateSourceRequest", - full_name="google.cloud.securitycenter.v1.CreateSourceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.CreateSourceRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source", - full_name="google.cloud.securitycenter.v1.CreateSourceRequest.source", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1282, - serialized_end=1438, -) - - -_DELETENOTIFICATIONCONFIGREQUEST = _descriptor.Descriptor( - name="DeleteNotificationConfigRequest", - full_name="google.cloud.securitycenter.v1.DeleteNotificationConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.DeleteNotificationConfigRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0securitycenter.googleapis.com/NotificationConfig", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1440, - serialized_end=1545, -) - - -_GETNOTIFICATIONCONFIGREQUEST = _descriptor.Descriptor( - name="GetNotificationConfigRequest", - full_name="google.cloud.securitycenter.v1.GetNotificationConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.GetNotificationConfigRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0securitycenter.googleapis.com/NotificationConfig", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1547, - serialized_end=1649, -) - - -_GETORGANIZATIONSETTINGSREQUEST = _descriptor.Descriptor( - name="GetOrganizationSettingsRequest", - full_name="google.cloud.securitycenter.v1.GetOrganizationSettingsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.GetOrganizationSettingsRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A4\n2securitycenter.googleapis.com/OrganizationSettings", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1651, - serialized_end=1757, -) - - -_GETSOURCEREQUEST = _descriptor.Descriptor( - name="GetSourceRequest", - full_name="google.cloud.securitycenter.v1.GetSourceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.GetSourceRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$securitycenter.googleapis.com/Source", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1759, - serialized_end=1837, -) - - -_GROUPASSETSREQUEST = _descriptor.Descriptor( - name="GroupAssetsRequest", - full_name="google.cloud.securitycenter.v1.GroupAssetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.GroupAssetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1.GroupAssetsRequest.filter", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="group_by", - full_name="google.cloud.securitycenter.v1.GroupAssetsRequest.group_by", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compare_duration", - full_name="google.cloud.securitycenter.v1.GroupAssetsRequest.compare_duration", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1.GroupAssetsRequest.read_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1.GroupAssetsRequest.page_token", - index=5, - number=7, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1.GroupAssetsRequest.page_size", - index=6, - number=8, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1840, - serialized_end=2112, -) - - -_GROUPASSETSRESPONSE = _descriptor.Descriptor( - name="GroupAssetsResponse", - full_name="google.cloud.securitycenter.v1.GroupAssetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="group_by_results", - full_name="google.cloud.securitycenter.v1.GroupAssetsResponse.group_by_results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1.GroupAssetsResponse.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1.GroupAssetsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.securitycenter.v1.GroupAssetsResponse.total_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2115, - serialized_end=2299, -) - - -_GROUPFINDINGSREQUEST = _descriptor.Descriptor( - name="GroupFindingsRequest", - full_name="google.cloud.securitycenter.v1.GroupFindingsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.GroupFindingsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$securitycenter.googleapis.com/Source", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1.GroupFindingsRequest.filter", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="group_by", - full_name="google.cloud.securitycenter.v1.GroupFindingsRequest.group_by", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1.GroupFindingsRequest.read_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compare_duration", - full_name="google.cloud.securitycenter.v1.GroupFindingsRequest.compare_duration", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1.GroupFindingsRequest.page_token", - index=5, - number=7, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1.GroupFindingsRequest.page_size", - index=6, - number=8, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2302, - serialized_end=2564, -) - - -_GROUPFINDINGSRESPONSE = _descriptor.Descriptor( - name="GroupFindingsResponse", - full_name="google.cloud.securitycenter.v1.GroupFindingsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="group_by_results", - full_name="google.cloud.securitycenter.v1.GroupFindingsResponse.group_by_results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1.GroupFindingsResponse.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1.GroupFindingsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.securitycenter.v1.GroupFindingsResponse.total_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2567, - serialized_end=2753, -) - - -_GROUPRESULT_PROPERTIESENTRY = _descriptor.Descriptor( - name="PropertiesEntry", - full_name="google.cloud.securitycenter.v1.GroupResult.PropertiesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1.GroupResult.PropertiesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1.GroupResult.PropertiesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2867, - serialized_end=2940, -) - -_GROUPRESULT = _descriptor.Descriptor( - name="GroupResult", - full_name="google.cloud.securitycenter.v1.GroupResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="properties", - full_name="google.cloud.securitycenter.v1.GroupResult.properties", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="count", - full_name="google.cloud.securitycenter.v1.GroupResult.count", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_GROUPRESULT_PROPERTIESENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2756, - serialized_end=2940, -) - - -_LISTNOTIFICATIONCONFIGSREQUEST = _descriptor.Descriptor( - name="ListNotificationConfigsRequest", - full_name="google.cloud.securitycenter.v1.ListNotificationConfigsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.ListNotificationConfigsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1.ListNotificationConfigsRequest.page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1.ListNotificationConfigsRequest.page_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2943, - serialized_end=3088, -) - - -_LISTNOTIFICATIONCONFIGSRESPONSE = _descriptor.Descriptor( - name="ListNotificationConfigsResponse", - full_name="google.cloud.securitycenter.v1.ListNotificationConfigsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="notification_configs", - full_name="google.cloud.securitycenter.v1.ListNotificationConfigsResponse.notification_configs", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1.ListNotificationConfigsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3091, - serialized_end=3231, -) - - -_LISTSOURCESREQUEST = _descriptor.Descriptor( - name="ListSourcesRequest", - full_name="google.cloud.securitycenter.v1.ListSourcesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.ListSourcesRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1.ListSourcesRequest.page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1.ListSourcesRequest.page_size", - index=2, - number=7, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3234, - serialized_end=3367, -) - - -_LISTSOURCESRESPONSE = _descriptor.Descriptor( - name="ListSourcesResponse", - full_name="google.cloud.securitycenter.v1.ListSourcesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="sources", - full_name="google.cloud.securitycenter.v1.ListSourcesResponse.sources", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1.ListSourcesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3369, - serialized_end=3472, -) - - -_LISTASSETSREQUEST = _descriptor.Descriptor( - name="ListAssetsRequest", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest.filter", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="order_by", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest.order_by", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest.read_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compare_duration", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest.compare_duration", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="field_mask", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest.field_mask", - index=5, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest.page_token", - index=6, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1.ListAssetsRequest.page_size", - index=7, - number=9, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3475, - serialized_end=3794, -) - - -_LISTASSETSRESPONSE_LISTASSETSRESULT = _descriptor.Descriptor( - name="ListAssetsResult", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="asset", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult.asset", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_change", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult.state_change", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4010, - serialized_end=4248, -) - -_LISTASSETSRESPONSE = _descriptor.Descriptor( - name="ListAssetsResponse", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="list_assets_results", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse.list_assets_results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.securitycenter.v1.ListAssetsResponse.total_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_LISTASSETSRESPONSE_LISTASSETSRESULT,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3797, - serialized_end=4248, -) - - -_LISTFINDINGSREQUEST = _descriptor.Descriptor( - name="ListFindingsRequest", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$securitycenter.googleapis.com/Source", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest.filter", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="order_by", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest.order_by", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest.read_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compare_duration", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest.compare_duration", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="field_mask", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest.field_mask", - index=5, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest.page_token", - index=6, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1.ListFindingsRequest.page_size", - index=7, - number=9, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4251, - serialized_end=4560, -) - - -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.Resource.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project_name", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.Resource.project_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project_display_name", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.Resource.project_display_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent_name", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.Resource.parent_name", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent_display_name", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.Resource.parent_display_name", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5071, - serialized_end=5197, -) - -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT = _descriptor.Descriptor( - name="ListFindingsResult", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="finding", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.finding", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_change", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.state_change", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.resource", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE,], - enum_types=[_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4784, - serialized_end=5276, -) - -_LISTFINDINGSRESPONSE = _descriptor.Descriptor( - name="ListFindingsResponse", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="list_findings_results", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.list_findings_results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.securitycenter.v1.ListFindingsResponse.total_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4563, - serialized_end=5276, -) - - -_SETFINDINGSTATEREQUEST = _descriptor.Descriptor( - name="SetFindingStateRequest", - full_name="google.cloud.securitycenter.v1.SetFindingStateRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.SetFindingStateRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A'\n%securitycenter.googleapis.com/Finding", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.securitycenter.v1.SetFindingStateRequest.state", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.cloud.securitycenter.v1.SetFindingStateRequest.start_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5279, - serialized_end=5484, -) - - -_RUNASSETDISCOVERYREQUEST = _descriptor.Descriptor( - name="RunAssetDiscoveryRequest", - full_name="google.cloud.securitycenter.v1.RunAssetDiscoveryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1.RunAssetDiscoveryRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5486, - serialized_end=5586, -) - - -_UPDATEFINDINGREQUEST = _descriptor.Descriptor( - name="UpdateFindingRequest", - full_name="google.cloud.securitycenter.v1.UpdateFindingRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="finding", - full_name="google.cloud.securitycenter.v1.UpdateFindingRequest.finding", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1.UpdateFindingRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5589, - serialized_end=5723, -) - - -_UPDATENOTIFICATIONCONFIGREQUEST = _descriptor.Descriptor( - name="UpdateNotificationConfigRequest", - full_name="google.cloud.securitycenter.v1.UpdateNotificationConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="notification_config", - full_name="google.cloud.securitycenter.v1.UpdateNotificationConfigRequest.notification_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1.UpdateNotificationConfigRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5726, - serialized_end=5894, -) - - -_UPDATEORGANIZATIONSETTINGSREQUEST = _descriptor.Descriptor( - name="UpdateOrganizationSettingsRequest", - full_name="google.cloud.securitycenter.v1.UpdateOrganizationSettingsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="organization_settings", - full_name="google.cloud.securitycenter.v1.UpdateOrganizationSettingsRequest.organization_settings", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1.UpdateOrganizationSettingsRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5897, - serialized_end=6071, -) - - -_UPDATESOURCEREQUEST = _descriptor.Descriptor( - name="UpdateSourceRequest", - full_name="google.cloud.securitycenter.v1.UpdateSourceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="source", - full_name="google.cloud.securitycenter.v1.UpdateSourceRequest.source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1.UpdateSourceRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6074, - serialized_end=6205, -) - - -_UPDATESECURITYMARKSREQUEST = _descriptor.Descriptor( - name="UpdateSecurityMarksRequest", - full_name="google.cloud.securitycenter.v1.UpdateSecurityMarksRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="security_marks", - full_name="google.cloud.securitycenter.v1.UpdateSecurityMarksRequest.security_marks", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1.UpdateSecurityMarksRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.cloud.securitycenter.v1.UpdateSecurityMarksRequest.start_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6208, - serialized_end=6409, -) - -_CREATEFINDINGREQUEST.fields_by_name[ - "finding" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2._FINDING -) -_CREATENOTIFICATIONCONFIGREQUEST.fields_by_name[ - "notification_config" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG -) -_CREATESOURCEREQUEST.fields_by_name[ - "source" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2._SOURCE -) -_GROUPASSETSREQUEST.fields_by_name[ - "compare_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_GROUPASSETSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GROUPASSETSRESPONSE.fields_by_name["group_by_results"].message_type = _GROUPRESULT -_GROUPASSETSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GROUPFINDINGSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GROUPFINDINGSREQUEST.fields_by_name[ - "compare_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_GROUPFINDINGSRESPONSE.fields_by_name["group_by_results"].message_type = _GROUPRESULT -_GROUPFINDINGSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GROUPRESULT_PROPERTIESENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_GROUPRESULT_PROPERTIESENTRY.containing_type = _GROUPRESULT -_GROUPRESULT.fields_by_name["properties"].message_type = _GROUPRESULT_PROPERTIESENTRY -_LISTNOTIFICATIONCONFIGSRESPONSE.fields_by_name[ - "notification_configs" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG -) -_LISTSOURCESRESPONSE.fields_by_name[ - "sources" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2._SOURCE -) -_LISTASSETSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTASSETSREQUEST.fields_by_name[ - "compare_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_LISTASSETSREQUEST.fields_by_name[ - "field_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_LISTASSETSRESPONSE_LISTASSETSRESULT.fields_by_name[ - "asset" -].message_type = google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_asset__pb2._ASSET -_LISTASSETSRESPONSE_LISTASSETSRESULT.fields_by_name[ - "state_change" -].enum_type = _LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE -_LISTASSETSRESPONSE_LISTASSETSRESULT.containing_type = _LISTASSETSRESPONSE -_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE.containing_type = ( - _LISTASSETSRESPONSE_LISTASSETSRESULT -) -_LISTASSETSRESPONSE.fields_by_name[ - "list_assets_results" -].message_type = _LISTASSETSRESPONSE_LISTASSETSRESULT -_LISTASSETSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTFINDINGSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTFINDINGSREQUEST.fields_by_name[ - "compare_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_LISTFINDINGSREQUEST.fields_by_name[ - "field_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE.containing_type = ( - _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT -) -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.fields_by_name[ - "finding" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2._FINDING -) -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.fields_by_name[ - "state_change" -].enum_type = _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.fields_by_name[ - "resource" -].message_type = _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.containing_type = _LISTFINDINGSRESPONSE -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE.containing_type = ( - _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT -) -_LISTFINDINGSRESPONSE.fields_by_name[ - "list_findings_results" -].message_type = _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT -_LISTFINDINGSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SETFINDINGSTATEREQUEST.fields_by_name[ - "state" -].enum_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2._FINDING_STATE -) -_SETFINDINGSTATEREQUEST.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_UPDATEFINDINGREQUEST.fields_by_name[ - "finding" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2._FINDING -) -_UPDATEFINDINGREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATENOTIFICATIONCONFIGREQUEST.fields_by_name[ - "notification_config" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG -) -_UPDATENOTIFICATIONCONFIGREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATEORGANIZATIONSETTINGSREQUEST.fields_by_name[ - "organization_settings" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2._ORGANIZATIONSETTINGS -) -_UPDATEORGANIZATIONSETTINGSREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATESOURCEREQUEST.fields_by_name[ - "source" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2._SOURCE -) -_UPDATESOURCEREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATESECURITYMARKSREQUEST.fields_by_name[ - "security_marks" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2._SECURITYMARKS -) -_UPDATESECURITYMARKSREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATESECURITYMARKSREQUEST.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -DESCRIPTOR.message_types_by_name["CreateFindingRequest"] = _CREATEFINDINGREQUEST -DESCRIPTOR.message_types_by_name[ - "CreateNotificationConfigRequest" -] = _CREATENOTIFICATIONCONFIGREQUEST -DESCRIPTOR.message_types_by_name["CreateSourceRequest"] = _CREATESOURCEREQUEST -DESCRIPTOR.message_types_by_name[ - "DeleteNotificationConfigRequest" -] = _DELETENOTIFICATIONCONFIGREQUEST -DESCRIPTOR.message_types_by_name[ - "GetNotificationConfigRequest" -] = _GETNOTIFICATIONCONFIGREQUEST -DESCRIPTOR.message_types_by_name[ - "GetOrganizationSettingsRequest" -] = _GETORGANIZATIONSETTINGSREQUEST -DESCRIPTOR.message_types_by_name["GetSourceRequest"] = _GETSOURCEREQUEST -DESCRIPTOR.message_types_by_name["GroupAssetsRequest"] = _GROUPASSETSREQUEST -DESCRIPTOR.message_types_by_name["GroupAssetsResponse"] = _GROUPASSETSRESPONSE -DESCRIPTOR.message_types_by_name["GroupFindingsRequest"] = _GROUPFINDINGSREQUEST -DESCRIPTOR.message_types_by_name["GroupFindingsResponse"] = _GROUPFINDINGSRESPONSE -DESCRIPTOR.message_types_by_name["GroupResult"] = _GROUPRESULT -DESCRIPTOR.message_types_by_name[ - "ListNotificationConfigsRequest" -] = _LISTNOTIFICATIONCONFIGSREQUEST -DESCRIPTOR.message_types_by_name[ - "ListNotificationConfigsResponse" -] = _LISTNOTIFICATIONCONFIGSRESPONSE -DESCRIPTOR.message_types_by_name["ListSourcesRequest"] = _LISTSOURCESREQUEST -DESCRIPTOR.message_types_by_name["ListSourcesResponse"] = _LISTSOURCESRESPONSE -DESCRIPTOR.message_types_by_name["ListAssetsRequest"] = _LISTASSETSREQUEST -DESCRIPTOR.message_types_by_name["ListAssetsResponse"] = _LISTASSETSRESPONSE -DESCRIPTOR.message_types_by_name["ListFindingsRequest"] = _LISTFINDINGSREQUEST -DESCRIPTOR.message_types_by_name["ListFindingsResponse"] = _LISTFINDINGSRESPONSE -DESCRIPTOR.message_types_by_name["SetFindingStateRequest"] = _SETFINDINGSTATEREQUEST -DESCRIPTOR.message_types_by_name["RunAssetDiscoveryRequest"] = _RUNASSETDISCOVERYREQUEST -DESCRIPTOR.message_types_by_name["UpdateFindingRequest"] = _UPDATEFINDINGREQUEST -DESCRIPTOR.message_types_by_name[ - "UpdateNotificationConfigRequest" -] = _UPDATENOTIFICATIONCONFIGREQUEST -DESCRIPTOR.message_types_by_name[ - "UpdateOrganizationSettingsRequest" -] = _UPDATEORGANIZATIONSETTINGSREQUEST -DESCRIPTOR.message_types_by_name["UpdateSourceRequest"] = _UPDATESOURCEREQUEST -DESCRIPTOR.message_types_by_name[ - "UpdateSecurityMarksRequest" -] = _UPDATESECURITYMARKSREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -CreateFindingRequest = _reflection.GeneratedProtocolMessageType( - "CreateFindingRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEFINDINGREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for creating a finding. - - Attributes: - parent: - Required. Resource name of the new finding’s parent. Its - format should be - “organizations/[organization_id]/sources/[source_id]”. - finding_id: - 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: - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.CreateFindingRequest) - }, -) -_sym_db.RegisterMessage(CreateFindingRequest) - -CreateNotificationConfigRequest = _reflection.GeneratedProtocolMessageType( - "CreateNotificationConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATENOTIFICATIONCONFIGREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for creating a notification config. - - Attributes: - parent: - Required. Resource name of the new notification config’s - parent. Its format is “organizations/[organization_id]”. - config_id: - 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: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.CreateNotificationConfigRequest) - }, -) -_sym_db.RegisterMessage(CreateNotificationConfigRequest) - -CreateSourceRequest = _reflection.GeneratedProtocolMessageType( - "CreateSourceRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATESOURCEREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for creating a source. - - Attributes: - parent: - Required. Resource name of the new source’s parent. Its format - should be “organizations/[organization_id]”. - source: - Required. The Source being created, only the display_name and - description will be used. All other fields will be ignored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.CreateSourceRequest) - }, -) -_sym_db.RegisterMessage(CreateSourceRequest) - -DeleteNotificationConfigRequest = _reflection.GeneratedProtocolMessageType( - "DeleteNotificationConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETENOTIFICATIONCONFIGREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for deleting a notification config. - - Attributes: - name: - Required. Name of the notification config to delete. Its - format is “organizations/[organization_id]/notificationConfigs - /[config_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.DeleteNotificationConfigRequest) - }, -) -_sym_db.RegisterMessage(DeleteNotificationConfigRequest) - -GetNotificationConfigRequest = _reflection.GeneratedProtocolMessageType( - "GetNotificationConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETNOTIFICATIONCONFIGREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for getting a notification config. - - Attributes: - name: - Required. Name of the notification config to get. Its format - is “organizations/[organization_id]/notificationConfigs/[confi - g_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GetNotificationConfigRequest) - }, -) -_sym_db.RegisterMessage(GetNotificationConfigRequest) - -GetOrganizationSettingsRequest = _reflection.GeneratedProtocolMessageType( - "GetOrganizationSettingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETORGANIZATIONSETTINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for getting organization settings. - - Attributes: - name: - Required. Name of the organization to get organization - settings for. Its format is - “organizations/[organization_id]/organizationSettings”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GetOrganizationSettingsRequest) - }, -) -_sym_db.RegisterMessage(GetOrganizationSettingsRequest) - -GetSourceRequest = _reflection.GeneratedProtocolMessageType( - "GetSourceRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSOURCEREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for getting a source. - - Attributes: - name: - Required. Relative resource name of the source. Its format is - “organizations/[organization_id]/source/[source_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GetSourceRequest) - }, -) -_sym_db.RegisterMessage(GetSourceRequest) - -GroupAssetsRequest = _reflection.GeneratedProtocolMessageType( - "GroupAssetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _GROUPASSETSREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for grouping by assets. - - Attributes: - parent: - Required. Name of the organization to groupBy. Its format is - “organizations/[organization_id]”. - filter: - 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: - 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_proper - ties.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: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GroupAssetsRequest) - }, -) -_sym_db.RegisterMessage(GroupAssetsRequest) - -GroupAssetsResponse = _reflection.GeneratedProtocolMessageType( - "GroupAssetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _GROUPASSETSRESPONSE, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Response message for grouping by assets. - - Attributes: - group_by_results: - 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: - Time used for executing the groupBy request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of results matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GroupAssetsResponse) - }, -) -_sym_db.RegisterMessage(GroupAssetsResponse) - -GroupFindingsRequest = _reflection.GeneratedProtocolMessageType( - "GroupFindingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _GROUPFINDINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for grouping by findings. - - Attributes: - parent: - 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: - 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`` - 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: - 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 - The following fields are supported when compare_duration is - set: - state_change - read_time: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GroupFindingsRequest) - }, -) -_sym_db.RegisterMessage(GroupFindingsRequest) - -GroupFindingsResponse = _reflection.GeneratedProtocolMessageType( - "GroupFindingsResponse", - (_message.Message,), - { - "DESCRIPTOR": _GROUPFINDINGSRESPONSE, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Response message for group by findings. - - Attributes: - group_by_results: - 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: - Time used for executing the groupBy request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of results matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GroupFindingsResponse) - }, -) -_sym_db.RegisterMessage(GroupFindingsResponse) - -GroupResult = _reflection.GeneratedProtocolMessageType( - "GroupResult", - (_message.Message,), - { - "PropertiesEntry": _reflection.GeneratedProtocolMessageType( - "PropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _GROUPRESULT_PROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GroupResult.PropertiesEntry) - }, - ), - "DESCRIPTOR": _GROUPRESULT, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Result containing the properties and count of a groupBy request. - - Attributes: - properties: - Properties matching the groupBy fields in the request. - count: - Total count of resources for the given properties. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.GroupResult) - }, -) -_sym_db.RegisterMessage(GroupResult) -_sym_db.RegisterMessage(GroupResult.PropertiesEntry) - -ListNotificationConfigsRequest = _reflection.GeneratedProtocolMessageType( - "ListNotificationConfigsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTNOTIFICATIONCONFIGSREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing notification configs. - - Attributes: - parent: - Required. Name of the organization to list notification - configs. Its format is “organizations/[organization_id]”. - page_token: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListNotificationConfigsRequest) - }, -) -_sym_db.RegisterMessage(ListNotificationConfigsRequest) - -ListNotificationConfigsResponse = _reflection.GeneratedProtocolMessageType( - "ListNotificationConfigsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTNOTIFICATIONCONFIGSRESPONSE, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing notification configs. - - Attributes: - notification_configs: - Notification configs belonging to the requested parent. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListNotificationConfigsResponse) - }, -) -_sym_db.RegisterMessage(ListNotificationConfigsResponse) - -ListSourcesRequest = _reflection.GeneratedProtocolMessageType( - "ListSourcesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTSOURCESREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing sources. - - Attributes: - parent: - Required. Resource name of the parent of sources to list. Its - format should be “organizations/[organization_id]”. - page_token: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListSourcesRequest) - }, -) -_sym_db.RegisterMessage(ListSourcesRequest) - -ListSourcesResponse = _reflection.GeneratedProtocolMessageType( - "ListSourcesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTSOURCESRESPONSE, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing sources. - - Attributes: - sources: - Sources belonging to the requested parent. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListSourcesResponse) - }, -) -_sym_db.RegisterMessage(ListSourcesResponse) - -ListAssetsRequest = _reflection.GeneratedProtocolMessageType( - "ListAssetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTASSETSREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing assets. - - Attributes: - parent: - Required. Name of the organization assets should belong to. - Its format is “organizations/[organization_id]”. - filter: - 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: - 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: - 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: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListAssetsRequest) - }, -) -_sym_db.RegisterMessage(ListAssetsRequest) - -ListAssetsResponse = _reflection.GeneratedProtocolMessageType( - "ListAssetsResponse", - (_message.Message,), - { - "ListAssetsResult": _reflection.GeneratedProtocolMessageType( - "ListAssetsResult", - (_message.Message,), - { - "DESCRIPTOR": _LISTASSETSRESPONSE_LISTASSETSRESULT, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Result containing the Asset and its State. - - Attributes: - asset: - Asset matching the search request. - state_change: - State change of the asset between the points in time. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult) - }, - ), - "DESCRIPTOR": _LISTASSETSRESPONSE, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing assets. - - Attributes: - list_assets_results: - Assets matching the list request. - read_time: - Time used for executing the list request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of assets matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListAssetsResponse) - }, -) -_sym_db.RegisterMessage(ListAssetsResponse) -_sym_db.RegisterMessage(ListAssetsResponse.ListAssetsResult) - -ListFindingsRequest = _reflection.GeneratedProtocolMessageType( - "ListFindingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTFINDINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing findings. - - Attributes: - parent: - 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: - 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`` 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: - 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: - 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: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListFindingsRequest) - }, -) -_sym_db.RegisterMessage(ListFindingsRequest) - -ListFindingsResponse = _reflection.GeneratedProtocolMessageType( - "ListFindingsResponse", - (_message.Message,), - { - "ListFindingsResult": _reflection.GeneratedProtocolMessageType( - "ListFindingsResult", - (_message.Message,), - { - "Resource": _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Information related to the Google Cloud resource that is associated - with this finding. - - Attributes: - name: - The full resource name of the resource. See: https://cloud.goo - gle.com/apis/design/resource_names#full_resource_name - project_name: - The full resource name of project that the resource belongs - to. - project_display_name: - The human readable name of project that the resource belongs - to. - parent_name: - The full resource name of resource’s parent. - parent_display_name: - The human readable name of resource’s parent. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult.Resource) - }, - ), - "DESCRIPTOR": _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Result containing the Finding and its StateChange. - - Attributes: - finding: - Finding matching the search request. - state_change: - State change of the finding between the points in time. - resource: - Output only. Resource that is associated with this finding. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult) - }, - ), - "DESCRIPTOR": _LISTFINDINGSRESPONSE, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing findings. - - Attributes: - list_findings_results: - Findings matching the list request. - read_time: - Time used for executing the list request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of findings matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.ListFindingsResponse) - }, -) -_sym_db.RegisterMessage(ListFindingsResponse) -_sym_db.RegisterMessage(ListFindingsResponse.ListFindingsResult) -_sym_db.RegisterMessage(ListFindingsResponse.ListFindingsResult.Resource) - -SetFindingStateRequest = _reflection.GeneratedProtocolMessageType( - "SetFindingStateRequest", - (_message.Message,), - { - "DESCRIPTOR": _SETFINDINGSTATEREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a finding’s state. - - Attributes: - name: - Required. The relative resource name of the finding. See: http - s://cloud.google.com/apis/design/resource_names#relative_resou - rce_name Example: “organizations/{organization_id}/sources/{so - urce_id}/finding/{finding_id}”. - state: - Required. The desired State of the finding. - start_time: - Required. The time at which the updated state takes effect. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.SetFindingStateRequest) - }, -) -_sym_db.RegisterMessage(SetFindingStateRequest) - -RunAssetDiscoveryRequest = _reflection.GeneratedProtocolMessageType( - "RunAssetDiscoveryRequest", - (_message.Message,), - { - "DESCRIPTOR": _RUNASSETDISCOVERYREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for running asset discovery for an organization. - - Attributes: - parent: - Required. Name of the organization to run asset discovery for. - Its format is “organizations/[organization_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.RunAssetDiscoveryRequest) - }, -) -_sym_db.RegisterMessage(RunAssetDiscoveryRequest) - -UpdateFindingRequest = _reflection.GeneratedProtocolMessageType( - "UpdateFindingRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEFINDINGREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating or creating a finding. - - Attributes: - 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: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.UpdateFindingRequest) - }, -) -_sym_db.RegisterMessage(UpdateFindingRequest) - -UpdateNotificationConfigRequest = _reflection.GeneratedProtocolMessageType( - "UpdateNotificationConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATENOTIFICATIONCONFIGREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a notification config. - - Attributes: - notification_config: - Required. The notification config to update. - update_mask: - The FieldMask to use when updating the notification config. - If empty all mutable fields will be updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.UpdateNotificationConfigRequest) - }, -) -_sym_db.RegisterMessage(UpdateNotificationConfigRequest) - -UpdateOrganizationSettingsRequest = _reflection.GeneratedProtocolMessageType( - "UpdateOrganizationSettingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEORGANIZATIONSETTINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating an organization’s settings. - - Attributes: - organization_settings: - Required. The organization settings resource to update. - update_mask: - The FieldMask to use when updating the settings resource. If - empty all mutable fields will be updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.UpdateOrganizationSettingsRequest) - }, -) -_sym_db.RegisterMessage(UpdateOrganizationSettingsRequest) - -UpdateSourceRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSourceRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESOURCEREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a source. - - Attributes: - source: - Required. The source resource to update. - update_mask: - The FieldMask to use when updating the source resource. If - empty all mutable fields will be updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.UpdateSourceRequest) - }, -) -_sym_db.RegisterMessage(UpdateSourceRequest) - -UpdateSecurityMarksRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSecurityMarksRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESECURITYMARKSREQUEST, - "__module__": "google.cloud.securitycenter_v1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a SecurityMarks resource. - - Attributes: - security_marks: - Required. The security marks resource to update. - update_mask: - 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: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.UpdateSecurityMarksRequest) - }, -) -_sym_db.RegisterMessage(UpdateSecurityMarksRequest) - - -DESCRIPTOR._options = None -_CREATEFINDINGREQUEST.fields_by_name["parent"]._options = None -_CREATEFINDINGREQUEST.fields_by_name["finding_id"]._options = None -_CREATEFINDINGREQUEST.fields_by_name["finding"]._options = None -_CREATENOTIFICATIONCONFIGREQUEST.fields_by_name["parent"]._options = None -_CREATENOTIFICATIONCONFIGREQUEST.fields_by_name["config_id"]._options = None -_CREATENOTIFICATIONCONFIGREQUEST.fields_by_name["notification_config"]._options = None -_CREATESOURCEREQUEST.fields_by_name["parent"]._options = None -_CREATESOURCEREQUEST.fields_by_name["source"]._options = None -_DELETENOTIFICATIONCONFIGREQUEST.fields_by_name["name"]._options = None -_GETNOTIFICATIONCONFIGREQUEST.fields_by_name["name"]._options = None -_GETORGANIZATIONSETTINGSREQUEST.fields_by_name["name"]._options = None -_GETSOURCEREQUEST.fields_by_name["name"]._options = None -_GROUPASSETSREQUEST.fields_by_name["parent"]._options = None -_GROUPASSETSREQUEST.fields_by_name["group_by"]._options = None -_GROUPFINDINGSREQUEST.fields_by_name["parent"]._options = None -_GROUPFINDINGSREQUEST.fields_by_name["group_by"]._options = None -_GROUPRESULT_PROPERTIESENTRY._options = None -_LISTNOTIFICATIONCONFIGSREQUEST.fields_by_name["parent"]._options = None -_LISTSOURCESREQUEST.fields_by_name["parent"]._options = None -_LISTASSETSREQUEST.fields_by_name["parent"]._options = None -_LISTASSETSREQUEST.fields_by_name["field_mask"]._options = None -_LISTFINDINGSREQUEST.fields_by_name["parent"]._options = None -_LISTFINDINGSREQUEST.fields_by_name["field_mask"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["name"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["state"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["start_time"]._options = None -_RUNASSETDISCOVERYREQUEST.fields_by_name["parent"]._options = None -_UPDATEFINDINGREQUEST.fields_by_name["finding"]._options = None -_UPDATENOTIFICATIONCONFIGREQUEST.fields_by_name["notification_config"]._options = None -_UPDATEORGANIZATIONSETTINGSREQUEST.fields_by_name[ - "organization_settings" -]._options = None -_UPDATESOURCEREQUEST.fields_by_name["source"]._options = None -_UPDATESECURITYMARKSREQUEST.fields_by_name["security_marks"]._options = None - -_SECURITYCENTER = _descriptor.ServiceDescriptor( - name="SecurityCenter", - full_name="google.cloud.securitycenter.v1.SecurityCenter", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\035securitycenter.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=6412, - serialized_end=11362, - methods=[ - _descriptor.MethodDescriptor( - name="CreateSource", - full_name="google.cloud.securitycenter.v1.SecurityCenter.CreateSource", - index=0, - containing_service=None, - input_type=_CREATESOURCEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2._SOURCE, - serialized_options=b'\202\323\344\223\002."$/v1/{parent=organizations/*}/sources:\006source\332A\rparent,source', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateFinding", - full_name="google.cloud.securitycenter.v1.SecurityCenter.CreateFinding", - index=1, - containing_service=None, - input_type=_CREATEFINDINGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2._FINDING, - serialized_options=b'\202\323\344\223\002:"//v1/{parent=organizations/*/sources/*}/findings:\007finding\332A\031parent,finding_id,finding', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateNotificationConfig", - full_name="google.cloud.securitycenter.v1.SecurityCenter.CreateNotificationConfig", - index=2, - containing_service=None, - input_type=_CREATENOTIFICATIONCONFIGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG, - serialized_options=b'\202\323\344\223\002G"0/v1/{parent=organizations/*}/notificationConfigs:\023notification_config\332A$parent,config_id,notification_config\332A\032parent,notification_config', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteNotificationConfig", - full_name="google.cloud.securitycenter.v1.SecurityCenter.DeleteNotificationConfig", - index=3, - containing_service=None, - input_type=_DELETENOTIFICATIONCONFIGREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\0022*0/v1/{name=organizations/*/notificationConfigs/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetIamPolicy", - full_name="google.cloud.securitycenter.v1.SecurityCenter.GetIamPolicy", - index=4, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._GETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\002:"5/v1/{resource=organizations/*/sources/*}:getIamPolicy:\001*\332A\010resource', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetNotificationConfig", - full_name="google.cloud.securitycenter.v1.SecurityCenter.GetNotificationConfig", - index=5, - containing_service=None, - input_type=_GETNOTIFICATIONCONFIGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG, - serialized_options=b"\202\323\344\223\0022\0220/v1/{name=organizations/*/notificationConfigs/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetOrganizationSettings", - full_name="google.cloud.securitycenter.v1.SecurityCenter.GetOrganizationSettings", - index=6, - containing_service=None, - input_type=_GETORGANIZATIONSETTINGSREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2._ORGANIZATIONSETTINGS, - serialized_options=b"\202\323\344\223\0021\022//v1/{name=organizations/*/organizationSettings}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSource", - full_name="google.cloud.securitycenter.v1.SecurityCenter.GetSource", - index=7, - containing_service=None, - input_type=_GETSOURCEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2._SOURCE, - serialized_options=b"\202\323\344\223\002&\022$/v1/{name=organizations/*/sources/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GroupAssets", - full_name="google.cloud.securitycenter.v1.SecurityCenter.GroupAssets", - index=8, - containing_service=None, - input_type=_GROUPASSETSREQUEST, - output_type=_GROUPASSETSRESPONSE, - serialized_options=b'\202\323\344\223\002.")/v1/{parent=organizations/*}/assets:group:\001*', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GroupFindings", - full_name="google.cloud.securitycenter.v1.SecurityCenter.GroupFindings", - index=9, - containing_service=None, - input_type=_GROUPFINDINGSREQUEST, - output_type=_GROUPFINDINGSRESPONSE, - serialized_options=b'\202\323\344\223\002:"5/v1/{parent=organizations/*/sources/*}/findings:group:\001*\332A\017parent,group_by', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListAssets", - full_name="google.cloud.securitycenter.v1.SecurityCenter.ListAssets", - index=10, - containing_service=None, - input_type=_LISTASSETSREQUEST, - output_type=_LISTASSETSRESPONSE, - serialized_options=b"\202\323\344\223\002%\022#/v1/{parent=organizations/*}/assets", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListFindings", - full_name="google.cloud.securitycenter.v1.SecurityCenter.ListFindings", - index=11, - containing_service=None, - input_type=_LISTFINDINGSREQUEST, - output_type=_LISTFINDINGSRESPONSE, - serialized_options=b"\202\323\344\223\0021\022//v1/{parent=organizations/*/sources/*}/findings", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListNotificationConfigs", - full_name="google.cloud.securitycenter.v1.SecurityCenter.ListNotificationConfigs", - index=12, - containing_service=None, - input_type=_LISTNOTIFICATIONCONFIGSREQUEST, - output_type=_LISTNOTIFICATIONCONFIGSRESPONSE, - serialized_options=b"\202\323\344\223\0022\0220/v1/{parent=organizations/*}/notificationConfigs\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListSources", - full_name="google.cloud.securitycenter.v1.SecurityCenter.ListSources", - index=13, - containing_service=None, - input_type=_LISTSOURCESREQUEST, - output_type=_LISTSOURCESRESPONSE, - serialized_options=b"\202\323\344\223\002&\022$/v1/{parent=organizations/*}/sources\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="RunAssetDiscovery", - full_name="google.cloud.securitycenter.v1.SecurityCenter.RunAssetDiscovery", - index=14, - containing_service=None, - input_type=_RUNASSETDISCOVERYREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\0025"0/v1/{parent=organizations/*}/assets:runDiscovery:\001*\332A\006parent\312AQ\n8google.cloud.securitycenter.v1.RunAssetDiscoveryResponse\022\025google.protobuf.Empty', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SetFindingState", - full_name="google.cloud.securitycenter.v1.SecurityCenter.SetFindingState", - index=15, - containing_service=None, - input_type=_SETFINDINGSTATEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2._FINDING, - serialized_options=b'\202\323\344\223\002="8/v1/{name=organizations/*/sources/*/findings/*}:setState:\001*\332A\025name,state,start_time', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SetIamPolicy", - full_name="google.cloud.securitycenter.v1.SecurityCenter.SetIamPolicy", - index=16, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._SETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\002:"5/v1/{resource=organizations/*/sources/*}:setIamPolicy:\001*\332A\017resource,policy', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="TestIamPermissions", - full_name="google.cloud.securitycenter.v1.SecurityCenter.TestIamPermissions", - index=17, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSREQUEST, - output_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSRESPONSE, - serialized_options=b'\202\323\344\223\002@";/v1/{resource=organizations/*/sources/*}:testIamPermissions:\001*\332A\024resource,permissions', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateFinding", - full_name="google.cloud.securitycenter.v1.SecurityCenter.UpdateFinding", - index=18, - containing_service=None, - input_type=_UPDATEFINDINGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2._FINDING, - serialized_options=b"\202\323\344\223\002B27/v1/{finding.name=organizations/*/sources/*/findings/*}:\007finding\332A\007finding", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateNotificationConfig", - full_name="google.cloud.securitycenter.v1.SecurityCenter.UpdateNotificationConfig", - index=19, - containing_service=None, - input_type=_UPDATENOTIFICATIONCONFIGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG, - serialized_options=b"\202\323\344\223\002[2D/v1/{notification_config.name=organizations/*/notificationConfigs/*}:\023notification_config\332A\023notification_config\332A\037notification_config,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateOrganizationSettings", - full_name="google.cloud.securitycenter.v1.SecurityCenter.UpdateOrganizationSettings", - index=20, - containing_service=None, - input_type=_UPDATEORGANIZATIONSETTINGSREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2._ORGANIZATIONSETTINGS, - serialized_options=b"\202\323\344\223\002^2E/v1/{organization_settings.name=organizations/*/organizationSettings}:\025organization_settings\332A\025organization_settings", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateSource", - full_name="google.cloud.securitycenter.v1.SecurityCenter.UpdateSource", - index=21, - containing_service=None, - input_type=_UPDATESOURCEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2._SOURCE, - serialized_options=b"\202\323\344\223\00252+/v1/{source.name=organizations/*/sources/*}:\006source\332A\006source", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateSecurityMarks", - full_name="google.cloud.securitycenter.v1.SecurityCenter.UpdateSecurityMarks", - index=22, - containing_service=None, - input_type=_UPDATESECURITYMARKSREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2._SECURITYMARKS, - serialized_options=b"\202\323\344\223\002\262\0012@/v1/{security_marks.name=organizations/*/assets/*/securityMarks}:\016security_marksZ^2L/v1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}:\016security_marks\332A\016security_marks", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_SECURITYCENTER) - -DESCRIPTOR.services_by_name["SecurityCenter"] = _SECURITYCENTER - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2_grpc.py deleted file mode 100644 index 3f9d084b..00000000 --- a/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2_grpc.py +++ /dev/null @@ -1,1088 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.securitycenter_v1.proto import ( - finding_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - notification_config_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - organization_settings_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - securitycenter_service_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2, -) -from google.cloud.securitycenter_v1.proto import ( - source_pb2 as google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class SecurityCenterStub(object): - """V1 APIs for Security Center service. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.CreateSource = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateSource", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateSourceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.FromString, - ) - self.CreateFinding = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateFindingRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.FromString, - ) - self.CreateNotificationConfig = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateNotificationConfigRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - ) - self.DeleteNotificationConfig = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.DeleteNotificationConfigRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.GetIamPolicy = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.GetNotificationConfig = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetNotificationConfigRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - ) - self.GetOrganizationSettings = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetOrganizationSettingsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.FromString, - ) - self.GetSource = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetSource", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetSourceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.FromString, - ) - self.GroupAssets = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsResponse.FromString, - ) - self.GroupFindings = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsResponse.FromString, - ) - self.ListAssets = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListAssets", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListAssetsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListAssetsResponse.FromString, - ) - self.ListFindings = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListFindings", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListFindingsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListFindingsResponse.FromString, - ) - self.ListNotificationConfigs = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsResponse.FromString, - ) - self.ListSources = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListSources", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListSourcesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListSourcesResponse.FromString, - ) - self.RunAssetDiscovery = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.RunAssetDiscoveryRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.SetFindingState = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.SetFindingStateRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.FromString, - ) - self.SetIamPolicy = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.TestIamPermissions = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - ) - self.UpdateFinding = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateFindingRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.FromString, - ) - self.UpdateNotificationConfig = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateNotificationConfigRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - ) - self.UpdateOrganizationSettings = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateOrganizationSettingsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.FromString, - ) - self.UpdateSource = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateSourceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.FromString, - ) - self.UpdateSecurityMarks = channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks", - request_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateSecurityMarksRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2.SecurityMarks.FromString, - ) - - -class SecurityCenterServicer(object): - """V1 APIs for Security Center service. - """ - - def CreateSource(self, request, context): - """Creates a source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateFinding(self, request, context): - """Creates a finding. The corresponding source must exist for finding creation - to succeed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateNotificationConfig(self, request, context): - """Creates a notification config. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteNotificationConfig(self, request, context): - """Deletes a notification config. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetIamPolicy(self, request, context): - """Gets the access control policy on the specified Source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetNotificationConfig(self, request, context): - """Gets a notification config. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetOrganizationSettings(self, request, context): - """Gets the settings for an organization. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSource(self, request, context): - """Gets a source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GroupAssets(self, request, context): - """Filters an organization's assets and groups them by their specified - properties. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GroupFindings(self, request, context): - """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 - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListAssets(self, request, context): - """Lists an organization's assets. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListFindings(self, request, context): - """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 - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListNotificationConfigs(self, request, context): - """Lists notification configs. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListSources(self, request, context): - """Lists all sources belonging to an organization. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def RunAssetDiscovery(self, request, context): - """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. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SetFindingState(self, request, context): - """Updates the state of a finding. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SetIamPolicy(self, request, context): - """Sets the access control policy on the specified Source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def TestIamPermissions(self, request, context): - """Returns the permissions that a caller has on the specified source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateFinding(self, request, context): - """Creates or updates a finding. The corresponding source must exist for a - finding creation to succeed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateNotificationConfig(self, request, context): - """Updates a notification config. The following update - fields are allowed: description, pubsub_topic, streaming_config.filter - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateOrganizationSettings(self, request, context): - """Updates an organization's settings. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateSource(self, request, context): - """Updates a source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateSecurityMarks(self, request, context): - """Updates security marks. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_SecurityCenterServicer_to_server(servicer, server): - rpc_method_handlers = { - "CreateSource": grpc.unary_unary_rpc_method_handler( - servicer.CreateSource, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateSourceRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.SerializeToString, - ), - "CreateFinding": grpc.unary_unary_rpc_method_handler( - servicer.CreateFinding, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateFindingRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.SerializeToString, - ), - "CreateNotificationConfig": grpc.unary_unary_rpc_method_handler( - servicer.CreateNotificationConfig, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateNotificationConfigRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.SerializeToString, - ), - "DeleteNotificationConfig": grpc.unary_unary_rpc_method_handler( - servicer.DeleteNotificationConfig, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.DeleteNotificationConfigRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "GetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.GetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "GetNotificationConfig": grpc.unary_unary_rpc_method_handler( - servicer.GetNotificationConfig, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetNotificationConfigRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.SerializeToString, - ), - "GetOrganizationSettings": grpc.unary_unary_rpc_method_handler( - servicer.GetOrganizationSettings, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetOrganizationSettingsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.SerializeToString, - ), - "GetSource": grpc.unary_unary_rpc_method_handler( - servicer.GetSource, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetSourceRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.SerializeToString, - ), - "GroupAssets": grpc.unary_unary_rpc_method_handler( - servicer.GroupAssets, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsResponse.SerializeToString, - ), - "GroupFindings": grpc.unary_unary_rpc_method_handler( - servicer.GroupFindings, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsResponse.SerializeToString, - ), - "ListAssets": grpc.unary_unary_rpc_method_handler( - servicer.ListAssets, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListAssetsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListAssetsResponse.SerializeToString, - ), - "ListFindings": grpc.unary_unary_rpc_method_handler( - servicer.ListFindings, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListFindingsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListFindingsResponse.SerializeToString, - ), - "ListNotificationConfigs": grpc.unary_unary_rpc_method_handler( - servicer.ListNotificationConfigs, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsResponse.SerializeToString, - ), - "ListSources": grpc.unary_unary_rpc_method_handler( - servicer.ListSources, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListSourcesRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListSourcesResponse.SerializeToString, - ), - "RunAssetDiscovery": grpc.unary_unary_rpc_method_handler( - servicer.RunAssetDiscovery, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.RunAssetDiscoveryRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "SetFindingState": grpc.unary_unary_rpc_method_handler( - servicer.SetFindingState, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.SetFindingStateRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.SerializeToString, - ), - "SetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.SetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "TestIamPermissions": grpc.unary_unary_rpc_method_handler( - servicer.TestIamPermissions, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, - ), - "UpdateFinding": grpc.unary_unary_rpc_method_handler( - servicer.UpdateFinding, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateFindingRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.SerializeToString, - ), - "UpdateNotificationConfig": grpc.unary_unary_rpc_method_handler( - servicer.UpdateNotificationConfig, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateNotificationConfigRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.SerializeToString, - ), - "UpdateOrganizationSettings": grpc.unary_unary_rpc_method_handler( - servicer.UpdateOrganizationSettings, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateOrganizationSettingsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.SerializeToString, - ), - "UpdateSource": grpc.unary_unary_rpc_method_handler( - servicer.UpdateSource, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateSourceRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.SerializeToString, - ), - "UpdateSecurityMarks": grpc.unary_unary_rpc_method_handler( - servicer.UpdateSecurityMarks, - request_deserializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateSecurityMarksRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2.SecurityMarks.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.securitycenter.v1.SecurityCenter", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class SecurityCenter(object): - """V1 APIs for Security Center service. - """ - - @staticmethod - def CreateSource( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/CreateSource", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateSourceRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateFinding( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateFindingRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateNotificationConfig( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.CreateNotificationConfigRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteNotificationConfig( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.DeleteNotificationConfigRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetIamPolicy( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy", - google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetNotificationConfig( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetNotificationConfigRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetOrganizationSettings( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetOrganizationSettingsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetSource( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/GetSource", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GetSourceRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GroupAssets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GroupFindings( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListAssets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/ListAssets", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListAssetsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListAssetsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListFindings( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/ListFindings", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListFindingsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListFindingsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListNotificationConfigs( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListSources( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/ListSources", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListSourcesRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.ListSourcesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def RunAssetDiscovery( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.RunAssetDiscoveryRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SetFindingState( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.SetFindingStateRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SetIamPolicy( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy", - google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def TestIamPermissions( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions", - google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateFinding( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateFindingRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_finding__pb2.Finding.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateNotificationConfig( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateNotificationConfigRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateOrganizationSettings( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateOrganizationSettingsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateSource( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateSourceRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_source__pb2.Source.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateSecurityMarks( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks", - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_securitycenter__service__pb2.UpdateSecurityMarksRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1_dot_proto_dot_security__marks__pb2.SecurityMarks.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/securitycenter_v1/proto/source_pb2.py b/google/cloud/securitycenter_v1/proto/source_pb2.py deleted file mode 100644 index 4d5792d1..00000000 --- a/google/cloud/securitycenter_v1/proto/source_pb2.py +++ /dev/null @@ -1,152 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1/proto/source.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1/proto/source.proto", - package="google.cloud.securitycenter.v1", - syntax="proto3", - serialized_options=b'\n"com.google.cloud.securitycenter.v1P\001ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\252\002\036Google.Cloud.SecurityCenter.V1\312\002\036Google\\Cloud\\SecurityCenter\\V1\352\002!Google::Cloud::SecurityCenter::V1', - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n1google/cloud/securitycenter_v1/proto/source.proto\x12\x1egoogle.cloud.securitycenter.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto"\x9b\x01\n\x06Source\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t:X\xea\x41U\n$securitycenter.googleapis.com/Source\x12-organizations/{organization}/sources/{source}B\xda\x01\n"com.google.cloud.securitycenter.v1P\x01ZLgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1;securitycenter\xaa\x02\x1eGoogle.Cloud.SecurityCenter.V1\xca\x02\x1eGoogle\\Cloud\\SecurityCenter\\V1\xea\x02!Google::Cloud::SecurityCenter::V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_SOURCE = _descriptor.Descriptor( - name="Source", - full_name="google.cloud.securitycenter.v1.Source", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1.Source.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.securitycenter.v1.Source.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.securitycenter.v1.Source.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352AU\n$securitycenter.googleapis.com/Source\022-organizations/{organization}/sources/{source}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=143, - serialized_end=298, -) - -DESCRIPTOR.message_types_by_name["Source"] = _SOURCE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Source = _reflection.GeneratedProtocolMessageType( - "Source", - (_message.Message,), - { - "DESCRIPTOR": _SOURCE, - "__module__": "google.cloud.securitycenter_v1.proto.source_pb2", - "__doc__": """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: - 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: - 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: - 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.” - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.Source) - }, -) -_sym_db.RegisterMessage(Source) - - -DESCRIPTOR._options = None -_SOURCE._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1/proto/source_pb2_grpc.py b/google/cloud/securitycenter_v1/proto/source_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1/proto/source_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1/py.typed b/google/cloud/securitycenter_v1/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/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/google/cloud/securitycenter_v1/services/__init__.py b/google/cloud/securitycenter_v1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/securitycenter_v1/services/__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/google/cloud/securitycenter.py b/google/cloud/securitycenter_v1/services/security_center/__init__.py similarity index 68% rename from google/cloud/securitycenter.py rename to google/cloud/securitycenter_v1/services/security_center/__init__.py index 44fb7b3e..6250349b 100644 --- a/google/cloud/securitycenter.py +++ b/google/cloud/securitycenter_v1/services/security_center/__init__.py @@ -1,29 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 __future__ import absolute_import - -from google.cloud.securitycenter_v1 import SecurityCenterClient -from google.cloud.securitycenter_v1 import enums -from google.cloud.securitycenter_v1 import types - +from .client import SecurityCenterClient +from .async_client import SecurityCenterAsyncClient __all__ = ( - "enums", - "types", "SecurityCenterClient", + "SecurityCenterAsyncClient", ) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py new file mode 100644 index 00000000..4e9b54d7 --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -0,0 +1,2242 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # 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 # 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 + + 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) + + from_service_account_file = SecurityCenterClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate 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:`~.securitycenter_service.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:`~.gcs_source.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: + ~.gcs_source.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. + if request is not None and any([parent, source]): + 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:`~.securitycenter_service.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:`~.gcs_finding.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: + ~.gcs_finding.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. + if request is not None and any([parent, finding_id, finding]): + 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:`~.securitycenter_service.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:`~.gcs_notification_config.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: + ~.gcs_notification_config.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. + if request is not None and any([parent, config_id, notification_config]): + 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:`~.securitycenter_service.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. + if request is not None and any([name]): + 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.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + 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.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.notification_config.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. + if request is not None and any([name]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.organization_settings.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. + if request is not None and any([name]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.source.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. + if request is not None and any([name]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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 + + Args: + request (:class:`~.securitycenter_service.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_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 + + + 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: + ~.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. + if request is not None and any([parent, group_by]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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. + if request is not None and any([parent]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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. + if request is not None and any([parent]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.run_asset_discovery_response.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. + if request is not None and any([parent]): + 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.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.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:`~.securitycenter_service.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:`~.finding.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:`~.timestamp.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: + ~.finding.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. + if request is not None and any([name, state, start_time]): + 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.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + 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.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.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.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.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.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: + ~.iam_policy.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. + if request is not None and any([resource, permissions]): + 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.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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 = 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.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: + ~.gcs_finding.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. + if request is not None and any([finding]): + 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.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:`~.securitycenter_service.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`~.gcs_notification_config.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:`~.field_mask.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: + ~.gcs_notification_config.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. + if request is not None and any([notification_config, update_mask]): + 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:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.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: + ~.gcs_organization_settings.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. + if request is not None and any([organization_settings]): + 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:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.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: + ~.gcs_source.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. + if request is not None and any([source]): + 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:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.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: + ~.gcs_security_marks.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. + if request is not None and any([security_marks]): + 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/google/cloud/securitycenter_v1/services/security_center/client.py b/google/cloud/securitycenter_v1/services/security_center/client.py new file mode 100644 index 00000000..b7d715fb --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/client.py @@ -0,0 +1,2411 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # 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 # 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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]: + """Return 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): + """Convert 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_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: + {@api.name}: 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 + + @staticmethod + def finding_path(organization: str, source: str, finding: str,) -> str: + """Return 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]: + """Parse 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: + """Return 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]: + """Parse 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: + """Return a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str, str]: + """Parse 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: + """Return 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]: + """Parse 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: + """Return 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]: + """Parse a source path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[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: + """Instantiate 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 (client_options_lib.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")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else 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": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else 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, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + 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:`~.securitycenter_service.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:`~.gcs_source.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: + ~.gcs_source.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 (:class:`~.securitycenter_service.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:`~.gcs_finding.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: + ~.gcs_finding.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 (:class:`~.securitycenter_service.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:`~.gcs_notification_config.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: + ~.gcs_notification_config.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 (:class:`~.securitycenter_service.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." + ) + + # 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.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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 (:class:`~.securitycenter_service.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: + ~.notification_config.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 (:class:`~.securitycenter_service.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: + ~.organization_settings.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 (:class:`~.securitycenter_service.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: + ~.source.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 (:class:`~.securitycenter_service.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: + ~.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 + + Args: + request (:class:`~.securitycenter_service.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_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 + + + 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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.run_asset_discovery_response.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.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.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:`~.securitycenter_service.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:`~.finding.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:`~.timestamp.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: + ~.finding.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.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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.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.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.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: + ~.iam_policy.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.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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 (:class:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.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: + ~.gcs_finding.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.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:`~.securitycenter_service.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`~.gcs_notification_config.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:`~.field_mask.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: + ~.gcs_notification_config.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 (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.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: + ~.gcs_organization_settings.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 (:class:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.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: + ~.gcs_source.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 (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.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: + ~.gcs_security_marks.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/google/cloud/securitycenter_v1/services/security_center/pagers.py b/google/cloud/securitycenter_v1/services/security_center/pagers.py new file mode 100644 index 00000000..98a0cc03 --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/pagers.py @@ -0,0 +1,804 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..20423f2a --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1/services/security_center/transports/base.py new file mode 100644 index 00000000..9bd2b417 --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -0,0 +1,571 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import 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 retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # 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() + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **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. + scope (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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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, + ) -> typing.Callable[ + [securitycenter_service.CreateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def create_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def create_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + typing.Union[ + gcs_notification_config.NotificationConfig, + typing.Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def delete_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.GetNotificationConfigRequest], + typing.Union[ + notification_config.NotificationConfig, + typing.Awaitable[notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + typing.Union[ + organization_settings.OrganizationSettings, + typing.Awaitable[organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def get_source( + self, + ) -> typing.Callable[ + [securitycenter_service.GetSourceRequest], + typing.Union[source.Source, typing.Awaitable[source.Source]], + ]: + raise NotImplementedError() + + @property + def group_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupAssetsRequest], + typing.Union[ + securitycenter_service.GroupAssetsResponse, + typing.Awaitable[securitycenter_service.GroupAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def group_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupFindingsRequest], + typing.Union[ + securitycenter_service.GroupFindingsResponse, + typing.Awaitable[securitycenter_service.GroupFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.ListAssetsRequest], + typing.Union[ + securitycenter_service.ListAssetsResponse, + typing.Awaitable[securitycenter_service.ListAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.ListFindingsRequest], + typing.Union[ + securitycenter_service.ListFindingsResponse, + typing.Awaitable[securitycenter_service.ListFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_notification_configs( + self, + ) -> typing.Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + typing.Union[ + securitycenter_service.ListNotificationConfigsResponse, + typing.Awaitable[securitycenter_service.ListNotificationConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_sources( + self, + ) -> typing.Callable[ + [securitycenter_service.ListSourcesRequest], + typing.Union[ + securitycenter_service.ListSourcesResponse, + typing.Awaitable[securitycenter_service.ListSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def run_asset_discovery( + self, + ) -> typing.Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def set_finding_state( + self, + ) -> typing.Callable[ + [securitycenter_service.SetFindingStateRequest], + typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def update_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + typing.Union[ + gcs_notification_config.NotificationConfig, + typing.Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + typing.Union[ + gcs_organization_settings.OrganizationSettings, + typing.Awaitable[gcs_organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def update_source( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def update_security_marks( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + typing.Union[ + gcs_security_marks.SecurityMarks, + typing.Awaitable[gcs_security_marks.SecurityMarks], + ], + ]: + raise NotImplementedError() + + +__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..d114c5e9 --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py @@ -0,0 +1,926 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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 +from google import auth # type: ignore +from google.auth import 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # 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: 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, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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. + 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. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "securitycenter.googleapis.com", + credentials: 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: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.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.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 "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["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.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.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.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.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.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 + + 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.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.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.SetIamPolicyRequest], policy.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.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.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.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.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/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..4b036ee5 --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,938 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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 import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # 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: 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: + address (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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: 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, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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. + 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. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @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 "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["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.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.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.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.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.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 + + 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.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.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.SetIamPolicyRequest], Awaitable[policy.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.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.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.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.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/google/cloud/securitycenter_v1/types.py b/google/cloud/securitycenter_v1/types.py deleted file mode 100644 index 5a52cafa..00000000 --- a/google/cloud/securitycenter_v1/types.py +++ /dev/null @@ -1,88 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.securitycenter_v1.proto import asset_pb2 -from google.cloud.securitycenter_v1.proto import finding_pb2 -from google.cloud.securitycenter_v1.proto import notification_config_pb2 -from google.cloud.securitycenter_v1.proto import notification_message_pb2 -from google.cloud.securitycenter_v1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1.proto import resource_pb2 -from google.cloud.securitycenter_v1.proto import run_asset_discovery_response_pb2 -from google.cloud.securitycenter_v1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import struct_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - iam_policy_pb2, - options_pb2, - policy_pb2, - operations_pb2, - any_pb2, - duration_pb2, - empty_pb2, - field_mask_pb2, - struct_pb2, - timestamp_pb2, - status_pb2, - expr_pb2, -] - -_local_modules = [ - asset_pb2, - finding_pb2, - notification_config_pb2, - notification_message_pb2, - organization_settings_pb2, - resource_pb2, - run_asset_discovery_response_pb2, - security_marks_pb2, - securitycenter_service_pb2, - source_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.securitycenter_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/securitycenter_v1/types/__init__.py b/google/cloud/securitycenter_v1/types/__init__.py new file mode 100644 index 00000000..c65c45b8 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/__init__.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .security_marks import SecurityMarks +from .asset import Asset +from .finding import Finding +from .notification_config import NotificationConfig +from .resource import Resource +from .notification_message import NotificationMessage +from .organization_settings import OrganizationSettings +from .run_asset_discovery_response import RunAssetDiscoveryResponse +from .source import Source +from .securitycenter_service import ( + 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, +) + + +__all__ = ( + "SecurityMarks", + "Asset", + "Finding", + "NotificationConfig", + "Resource", + "NotificationMessage", + "OrganizationSettings", + "RunAssetDiscoveryResponse", + "Source", + "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", +) diff --git a/google/cloud/securitycenter_v1/types/asset.py b/google/cloud/securitycenter_v1/types/asset.py new file mode 100644 index 00000000..d1992e53 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/asset.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.asset.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[~.asset.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 (~.gcs_security_marks.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 (~.timestamp.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (~.timestamp.Timestamp): + The time at which the asset was last updated, + added, or deleted in Security Command Center. + iam_policy (~.asset.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. + """ + + 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. + """ + + 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) + + 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.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + iam_policy = proto.Field(proto.MESSAGE, number=11, message=IamPolicy,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/finding.py b/google/cloud/securitycenter_v1/types/finding.py new file mode 100644 index 00000000..aff349c6 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/finding.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 + + +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.finding.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[~.finding.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 (~.gcs_security_marks.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 (~.timestamp.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 (~.timestamp.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.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/notification_config.py b/google/cloud/securitycenter_v1/types/notification_config.py new file mode 100644 index 00000000..87e4d654 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/notification_config.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 PubSub 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 PubSub topic. + streaming_config (~.notification_config.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/google/cloud/securitycenter_v1/types/notification_message.py b/google/cloud/securitycenter_v1/types/notification_message.py new file mode 100644 index 00000000..c836cad9 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/notification_message.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 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 (~.gcs_finding.Finding): + If it's a Finding based notification config, + this field will be populated. + resource (~.gcs_resource.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/google/cloud/securitycenter_v1/types/organization_settings.py b/google/cloud/securitycenter_v1/types/organization_settings.py new file mode 100644 index 00000000..ad4bc9f8 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/organization_settings.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 (~.organization_settings.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 (~.organization_settings.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/google/cloud/securitycenter_v1/types/resource.py b/google/cloud/securitycenter_v1/types/resource.py new file mode 100644 index 00000000..49c709fa --- /dev/null +++ b/google/cloud/securitycenter_v1/types/resource.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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={"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. + """ + + 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) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..eeed56ef --- /dev/null +++ b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as gp_duration # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"RunAssetDiscoveryResponse",}, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (~.gp_duration.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=gp_duration.Duration,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/security_marks.py b/google/cloud/securitycenter_v1/types/security_marks.py new file mode 100644 index 00000000..21bf0b0a --- /dev/null +++ b/google/cloud/securitycenter_v1/types/security_marks.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 + + +__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[~.security_marks.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/google/cloud/securitycenter_v1/types/securitycenter_service.py b/google/cloud/securitycenter_v1/types/securitycenter_service.py new file mode 100644 index 00000000..150917f4 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/securitycenter_service.py @@ -0,0 +1,1354 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ( + 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 as duration # type: ignore +from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.gcs_finding.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 (~.gcs_notification_config.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 (~.gcs_source.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]". + 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 (~.duration.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 (~.timestamp.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.Duration,) + + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.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[~.securitycenter_service.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 (~.timestamp.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.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]". 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 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`` + + - 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 + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (~.timestamp.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 (~.duration.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.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.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[~.securitycenter_service.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 (~.timestamp.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.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[~.securitycenter_service.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.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[~.gcs_notification_config.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]". + 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[~.gcs_source.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 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 (~.timestamp.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 (~.duration.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 (~.gp_field_mask.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.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.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[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (~.timestamp.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 (~.gcs_asset.Asset): + Asset matching the search request. + state_change (~.securitycenter_service.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.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 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`` + + 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 (~.timestamp.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 (~.duration.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 (~.gp_field_mask.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.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.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[~.securitycenter_service.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (~.timestamp.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 (~.gcs_finding.Finding): + Finding matching the search request. + state_change (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (~.securitycenter_service.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. + """ + + 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) + + 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.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 (~.gcs_finding.Finding.State): + Required. The desired State of the finding. + start_time (~.timestamp.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.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 (~.gcs_finding.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 (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (~.gcs_notification_config.NotificationConfig): + Required. The notification config to update. + update_mask (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (~.gcs_organization_settings.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (~.gcs_source.Source): + Required. The source resource to update. + update_mask (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (~.gcs_security_marks.SecurityMarks): + Required. The security marks resource to + update. + update_mask (~.gp_field_mask.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 (~.timestamp.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=gp_field_mask.FieldMask,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/source.py b/google/cloud/securitycenter_v1/types/source.py new file mode 100644 index 00000000..ce412d1c --- /dev/null +++ b/google/cloud/securitycenter_v1/types/source.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.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.". + """ + + 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/google/cloud/securitycenter_v1beta1/__init__.py b/google/cloud/securitycenter_v1beta1/__init__.py index 6944ab92..55c3ce49 100644 --- a/google/cloud/securitycenter_v1beta1/__init__.py +++ b/google/cloud/securitycenter_v1beta1/__init__.py @@ -1,45 +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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.securitycenter_v1beta1 import types -from google.cloud.securitycenter_v1beta1.gapic import enums -from google.cloud.securitycenter_v1beta1.gapic import security_center_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class SecurityCenterClient(security_center_client.SecurityCenterClient): - __doc__ = security_center_client.SecurityCenterClient.__doc__ - enums = enums +from .services.security_center import SecurityCenterClient +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__ = ( - "enums", - "types", + "Asset", + "CreateFindingRequest", + "CreateSourceRequest", + "Finding", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "OrganizationSettings", + "RunAssetDiscoveryRequest", + "RunAssetDiscoveryResponse", + "SecurityMarks", + "SetFindingStateRequest", + "Source", + "UpdateFindingRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1beta1/gapic/__init__.py b/google/cloud/securitycenter_v1beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1beta1/gapic/enums.py b/google/cloud/securitycenter_v1beta1/gapic/enums.py deleted file mode 100644 index f82dd6da..00000000 --- a/google/cloud/securitycenter_v1beta1/gapic/enums.py +++ /dev/null @@ -1,120 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class NullValue(enum.IntEnum): - """ - ``NullValue`` is a singleton enumeration to represent the null value - for the ``Value`` type union. - - The JSON representation for ``NullValue`` is JSON ``null``. - - Attributes: - NULL_VALUE (int): Null value. - """ - - NULL_VALUE = 0 - - -class Finding(object): - class State(enum.IntEnum): - """ - The state of the finding. - - Attributes: - STATE_UNSPECIFIED (int): Unspecified state. - ACTIVE (int): The finding requires attention and has not been addressed yet. - INACTIVE (int): The finding has been fixed, triaged as a non-issue or otherwise addressed - and is no longer active. - """ - - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - -class ListAssetsResponse(object): - class ListAssetsResult(object): - class State(enum.IntEnum): - """ - 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 - - Attributes: - STATE_UNSPECIFIED (int): Unspecified state. - UNUSED (int): Request did not specify use of this field in the result. - ADDED (int): Asset was added between the points in time. - REMOVED (int): Asset was removed between the points in time. - ACTIVE (int): Asset was active at both point(s) in time. - """ - - STATE_UNSPECIFIED = 0 - UNUSED = 1 - ADDED = 2 - REMOVED = 3 - ACTIVE = 4 - - -class OrganizationSettings(object): - class AssetDiscoveryConfig(object): - class InclusionMode(enum.IntEnum): - """ - 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. - - Attributes: - INCLUSION_MODE_UNSPECIFIED (int): Unspecified. Setting the mode with this value will disable - inclusion/exclusion filtering for Asset Discovery. - INCLUDE_ONLY (int): Asset Discovery will capture only the resources within the projects - specified. All other resources will be ignored. - EXCLUDE (int): Asset Discovery will ignore all resources under the projects specified. - All other resources will be retrieved. - """ - - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - -class RunAssetDiscoveryResponse(object): - class State(enum.IntEnum): - """ - The state of an asset discovery run. - - Attributes: - STATE_UNSPECIFIED (int): Asset discovery run state was unspecified. - COMPLETED (int): Asset discovery run completed successfully. - SUPERSEDED (int): Asset discovery run was cancelled with tasks still pending, as another - run for the same organization was started with a higher priority. - TERMINATED (int): Asset discovery run was killed and terminated. - """ - - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py deleted file mode 100644 index 72660006..00000000 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py +++ /dev/null @@ -1,2131 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.securitycenter.v1beta1 SecurityCenter API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.securitycenter_v1beta1.gapic import enums -from google.cloud.securitycenter_v1beta1.gapic import security_center_client_config -from google.cloud.securitycenter_v1beta1.gapic.transports import ( - security_center_grpc_transport, -) -from google.cloud.securitycenter_v1beta1.proto import finding_pb2 -from google.cloud.securitycenter_v1beta1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1beta1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1beta1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1beta1.proto import securitycenter_service_pb2_grpc -from google.cloud.securitycenter_v1beta1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-securitycenter", -).version - - -class SecurityCenterClient(object): - """V1 Beta APIs for Security Center service.""" - - SERVICE_ADDRESS = "securitycenter.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.securitycenter.v1beta1.SecurityCenter" - - @classmethod - def from_service_account_file(cls, filename, *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 - - @classmethod - def asset_security_marks_path(cls, organization, asset): - """Return a fully-qualified asset_security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/assets/{asset}/securityMarks", - organization=organization, - asset=asset, - ) - - @classmethod - def finding_path(cls, organization, source, finding): - """Return a fully-qualified finding string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}/findings/{finding}", - organization=organization, - source=source, - finding=finding, - ) - - @classmethod - def finding_security_marks_path(cls, organization, source, finding): - """Return a fully-qualified finding_security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}/findings/{finding}/securityMarks", - organization=organization, - source=source, - finding=finding, - ) - - @classmethod - def organization_path(cls, organization): - """Return a fully-qualified organization string.""" - return google.api_core.path_template.expand( - "organizations/{organization}", organization=organization, - ) - - @classmethod - def organization_settings_path(cls, organization): - """Return a fully-qualified organization_settings string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/organizationSettings", - organization=organization, - ) - - @classmethod - def source_path(cls, organization, source): - """Return a fully-qualified source string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}", - organization=organization, - source=source, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.SecurityCenterGrpcTransport, - Callable[[~.Credentials, type], ~.SecurityCenterGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = security_center_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=security_center_grpc_transport.SecurityCenterGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = security_center_grpc_transport.SecurityCenterGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def create_source( - self, - parent, - source, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a source. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `source`: - >>> source = {} - >>> - >>> response = client.create_source(parent, source) - - Args: - parent (str): Required. Resource name of the new source's parent. Its format - should be "organizations/[organization_id]". - source (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Source` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_source" not in self._inner_api_calls: - self._inner_api_calls[ - "create_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_source, - default_retry=self._method_configs["CreateSource"].retry, - default_timeout=self._method_configs["CreateSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_finding( - self, - parent, - finding_id, - finding, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a finding. The corresponding source must exist for finding creation - to succeed. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `finding_id`: - >>> finding_id = '' - >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} - >>> - >>> response = client.create_finding(parent, finding_id, finding) - - Args: - 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 (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Finding` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_finding" not in self._inner_api_calls: - self._inner_api_calls[ - "create_finding" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_finding, - default_retry=self._method_configs["CreateFinding"].retry, - default_timeout=self._method_configs["CreateFinding"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_finding"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_iam_policy( - self, - resource, - options_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the access control policy on the specified Source. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> response = client.get_iam_policy(resource) - - Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.securitycenter_v1beta1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.GetPolicyOptions` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "get_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_organization_settings( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the settings for an organization. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> name = client.organization_settings_path('[ORGANIZATION]') - >>> - >>> response = client.get_organization_settings(name) - - Args: - name (str): Required. Name of the organization to get organization settings for. - Its format is "organizations/[organization_id]/organizationSettings". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.OrganizationSettings` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_organization_settings" not in self._inner_api_calls: - self._inner_api_calls[ - "get_organization_settings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_organization_settings, - default_retry=self._method_configs["GetOrganizationSettings"].retry, - default_timeout=self._method_configs["GetOrganizationSettings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_organization_settings"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_source( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a source. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> response = client.get_source(name) - - Args: - name (str): Required. Relative resource name of the source. Its format is - "organizations/[organization_id]/source/[source_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_source" not in self._inner_api_calls: - self._inner_api_calls[ - "get_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_source, - default_retry=self._method_configs["GetSource"].retry, - default_timeout=self._method_configs["GetSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GetSourceRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def group_assets( - self, - parent, - group_by, - filter_=None, - compare_duration=None, - read_time=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Filters an organization's assets and groups them by their specified - properties. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_assets(parent, group_by): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_assets(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - 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 - 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. - compare_duration (Union[dict, ~google.cloud.securitycenter_v1beta1.types.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``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Duration` - read_time (Union[dict, ~google.cloud.securitycenter_v1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1beta1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "group_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "group_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_assets, - default_retry=self._method_configs["GroupAssets"].retry, - default_timeout=self._method_configs["GroupAssets"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - compare_duration=compare_duration, - read_time=read_time, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def group_findings( - self, - parent, - group_by, - filter_=None, - read_time=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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 - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_findings(parent, group_by): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_findings(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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/- - 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 - 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. - read_time (Union[dict, ~google.cloud.securitycenter_v1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1beta1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "group_findings" not in self._inner_api_calls: - self._inner_api_calls[ - "group_findings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_findings, - default_retry=self._method_configs["GroupFindings"].retry, - default_timeout=self._method_configs["GroupFindings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - read_time=read_time, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_assets( - self, - parent, - filter_=None, - order_by=None, - read_time=None, - compare_duration=None, - field_mask=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists an organization's assets. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_assets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_assets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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 (Union[dict, ~google.cloud.securitycenter_v1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Duration` - field_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): Optional. A field mask to specify the ListAssetsResult fields to be listed in the - response. - An empty field mask will list all fields. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1beta1.types.ListAssetsResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_assets, - default_retry=self._method_configs["ListAssets"].retry, - default_timeout=self._method_configs["ListAssets"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListAssetsRequest( - parent=parent, - filter=filter_, - order_by=order_by, - read_time=read_time, - compare_duration=compare_duration, - field_mask=field_mask, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="list_assets_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_findings( - self, - parent, - filter_=None, - order_by=None, - read_time=None, - field_mask=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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 - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # Iterate over all results - >>> for element in client.list_findings(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_findings(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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 (Union[dict, ~google.cloud.securitycenter_v1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp` - field_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): Optional. A field mask to specify the Finding fields to be listed in the response. - An empty field mask will list all fields. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1beta1.types.Finding` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_findings" not in self._inner_api_calls: - self._inner_api_calls[ - "list_findings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_findings, - default_retry=self._method_configs["ListFindings"].retry, - default_timeout=self._method_configs["ListFindings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListFindingsRequest( - parent=parent, - filter=filter_, - order_by=order_by, - read_time=read_time, - field_mask=field_mask, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="findings", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_sources( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists all sources belonging to an organization. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_sources(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_sources(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Resource name of the parent of sources to list. Its format - should be "organizations/[organization_id]". - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1beta1.types.Source` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_sources" not in self._inner_api_calls: - self._inner_api_calls[ - "list_sources" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_sources, - default_retry=self._method_configs["ListSources"].retry, - default_timeout=self._method_configs["ListSources"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListSourcesRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_sources"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="sources", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def run_asset_discovery( - self, - parent, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> response = client.run_asset_discovery(parent) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. Name of the organization to run asset discovery for. Its - format is "organizations/[organization_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "run_asset_discovery" not in self._inner_api_calls: - self._inner_api_calls[ - "run_asset_discovery" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.run_asset_discovery, - default_retry=self._method_configs["RunAssetDiscovery"].retry, - default_timeout=self._method_configs["RunAssetDiscovery"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.RunAssetDiscoveryRequest(parent=parent,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["run_asset_discovery"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=empty_pb2.Empty, - ) - - def set_finding_state( - self, - name, - state, - start_time, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates the state of a finding. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> from google.cloud.securitycenter_v1beta1 import enums - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> name = client.finding_path('[ORGANIZATION]', '[SOURCE]', '[FINDING]') - >>> - >>> # TODO: Initialize `state`: - >>> state = enums.Finding.State.STATE_UNSPECIFIED - >>> - >>> # TODO: Initialize `start_time`: - >>> start_time = {} - >>> - >>> response = client.set_finding_state(name, state, start_time) - - Args: - 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.State): Required. The desired State of the finding. - start_time (Union[dict, ~google.cloud.securitycenter_v1beta1.types.Timestamp]): Required. The time at which the updated state takes effect. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_finding_state" not in self._inner_api_calls: - self._inner_api_calls[ - "set_finding_state" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_finding_state, - default_retry=self._method_configs["SetFindingState"].retry, - default_timeout=self._method_configs["SetFindingState"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.SetFindingStateRequest( - name=name, state=state, start_time=start_time, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_finding_state"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def set_iam_policy( - self, - resource, - policy, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sets the access control policy on the specified Source. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `policy`: - >>> policy = {} - >>> - >>> response = client.set_iam_policy(resource, policy) - - Args: - resource (str): REQUIRED: The resource for which the policy is being specified. - See the operation documentation for the appropriate value for this field. - policy (Union[dict, ~google.cloud.securitycenter_v1beta1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The - size of the policy is limited to a few 10s of KB. An empty policy is a - valid policy but certain Cloud Platform services (such as Projects) - might reject them. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Policy` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "set_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_iam_policy, - default_retry=self._method_configs["SetIamPolicy"].retry, - default_timeout=self._method_configs["SetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def test_iam_permissions( - self, - resource, - permissions, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns the permissions that a caller has on the specified source. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] - >>> - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[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 `__. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.TestIamPermissionsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: - self._inner_api_calls[ - "test_iam_permissions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["test_iam_permissions"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_finding( - self, - finding, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates or updates a finding. The corresponding source must exist for a - finding creation to succeed. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} - >>> - >>> response = client.update_finding(finding) - - Args: - finding (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Finding` - update_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): The FieldMask to use when updating the finding resource. This field should - not be specified when creating a finding. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_finding" not in self._inner_api_calls: - self._inner_api_calls[ - "update_finding" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_finding, - default_retry=self._method_configs["UpdateFinding"].retry, - default_timeout=self._method_configs["UpdateFinding"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateFindingRequest( - finding=finding, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("finding.name", finding.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_finding"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_organization_settings( - self, - organization_settings, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates an organization's settings. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `organization_settings`: - >>> organization_settings = {} - >>> - >>> response = client.update_organization_settings(organization_settings) - - Args: - organization_settings (Union[dict, ~google.cloud.securitycenter_v1beta1.types.OrganizationSettings]): Required. The organization settings resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.OrganizationSettings` - update_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): The FieldMask to use when updating the settings resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.OrganizationSettings` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_organization_settings" not in self._inner_api_calls: - self._inner_api_calls[ - "update_organization_settings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_organization_settings, - default_retry=self._method_configs["UpdateOrganizationSettings"].retry, - default_timeout=self._method_configs[ - "UpdateOrganizationSettings" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateOrganizationSettingsRequest( - organization_settings=organization_settings, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [ - ("organization_settings.name", organization_settings.name) - ] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_organization_settings"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_source( - self, - source, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a source. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `source`: - >>> source = {} - >>> - >>> response = client.update_source(source) - - Args: - source (Union[dict, ~google.cloud.securitycenter_v1beta1.types.Source]): Required. The source resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Source` - update_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): The FieldMask to use when updating the source resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_source" not in self._inner_api_calls: - self._inner_api_calls[ - "update_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_source, - default_retry=self._method_configs["UpdateSource"].retry, - default_timeout=self._method_configs["UpdateSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateSourceRequest( - source=source, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("source.name", source.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_security_marks( - self, - security_marks, - update_mask=None, - start_time=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates security marks. - - Example: - >>> from google.cloud import securitycenter_v1beta1 - >>> - >>> client = securitycenter_v1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `security_marks`: - >>> security_marks = {} - >>> - >>> response = client.update_security_marks(security_marks) - - Args: - security_marks (Union[dict, ~google.cloud.securitycenter_v1beta1.types.SecurityMarks]): Required. The security marks resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.SecurityMarks` - update_mask (Union[dict, ~google.cloud.securitycenter_v1beta1.types.FieldMask]): The FieldMask to use when updating the security marks resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.FieldMask` - start_time (Union[dict, ~google.cloud.securitycenter_v1beta1.types.Timestamp]): The time at which the updated SecurityMarks take effect. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1beta1.types.Timestamp` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1beta1.types.SecurityMarks` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_security_marks" not in self._inner_api_calls: - self._inner_api_calls[ - "update_security_marks" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_security_marks, - default_retry=self._method_configs["UpdateSecurityMarks"].retry, - default_timeout=self._method_configs["UpdateSecurityMarks"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateSecurityMarksRequest( - security_marks=security_marks, - update_mask=update_mask, - start_time=start_time, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("security_marks.name", security_marks.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_security_marks"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py deleted file mode 100644 index 6d6b421b..00000000 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py +++ /dev/null @@ -1,152 +0,0 @@ -config = { - "interfaces": { - "google.cloud.securitycenter.v1beta1.SecurityCenter": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_2_codes": [], - "no_retry_codes": [], - "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_2_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, - }, - "methods": { - "CreateSource": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateFinding": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetOrganizationSettings": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetSource": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GroupAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "GroupFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListSources": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "RunAssetDiscovery": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "SetFindingState": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "SetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "UpdateFinding": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateOrganizationSettings": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateSource": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateSecurityMarks": { - "timeout_millis": 480000, - "retry_codes_name": "no_retry_2_codes", - "retry_params_name": "no_retry_2_params", - }, - }, - } - } -} diff --git a/google/cloud/securitycenter_v1beta1/gapic/transports/__init__.py b/google/cloud/securitycenter_v1beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1beta1/gapic/transports/security_center_grpc_transport.py b/google/cloud/securitycenter_v1beta1/gapic/transports/security_center_grpc_transport.py deleted file mode 100644 index a18012db..00000000 --- a/google/cloud/securitycenter_v1beta1/gapic/transports/security_center_grpc_transport.py +++ /dev/null @@ -1,370 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.securitycenter_v1beta1.proto import securitycenter_service_pb2_grpc - - -class SecurityCenterGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.securitycenter.v1beta1 SecurityCenter API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - channel=None, - credentials=None, - address="securitycenter.googleapis.com:443", - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "security_center_stub": securitycenter_service_pb2_grpc.SecurityCenterStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="securitycenter.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def create_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.create_source`. - - Creates a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].CreateSource - - @property - def create_finding(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.create_finding`. - - Creates a finding. The corresponding source must exist for finding creation - to succeed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].CreateFinding - - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. - - Gets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetIamPolicy - - @property - def get_organization_settings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_organization_settings`. - - Gets the settings for an organization. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetOrganizationSettings - - @property - def get_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_source`. - - Gets a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetSource - - @property - def group_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. - - Filters an organization's assets and groups them by their specified - properties. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupAssets - - @property - def group_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. - - 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: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupFindings - - @property - def list_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_assets`. - - Lists an organization's assets. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListAssets - - @property - def list_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_findings`. - - 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: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListFindings - - @property - def list_sources(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_sources`. - - Lists all sources belonging to an organization. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListSources - - @property - def run_asset_discovery(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.run_asset_discovery`. - - 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: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].RunAssetDiscovery - - @property - def set_finding_state(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.set_finding_state`. - - Updates the state of a finding. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].SetFindingState - - @property - def set_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.set_iam_policy`. - - Sets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].SetIamPolicy - - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. - - Returns the permissions that a caller has on the specified source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].TestIamPermissions - - @property - def update_finding(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_finding`. - - Creates or updates a finding. The corresponding source must exist for a - finding creation to succeed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateFinding - - @property - def update_organization_settings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_organization_settings`. - - Updates an organization's settings. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateOrganizationSettings - - @property - def update_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_source`. - - Updates a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateSource - - @property - def update_security_marks(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_security_marks`. - - Updates security marks. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateSecurityMarks diff --git a/google/cloud/securitycenter_v1beta1/proto/__init__.py b/google/cloud/securitycenter_v1beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py b/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py deleted file mode 100644 index ecef17ea..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py +++ /dev/null @@ -1,470 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1beta1/proto/asset.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1beta1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2, -) -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1beta1/proto/asset.proto", - package="google.cloud.securitycenter.v1beta1", - syntax="proto3", - serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", - create_key=_descriptor._internal_create_key, - serialized_pb=b"\n5google/cloud/securitycenter_v1beta1/proto/asset.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto\"\xd3\x05\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12g\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32\x43.google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties\x12_\n\x13resource_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry\x12J\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x99\x01\n\x18SecurityCenterProperties\x12\x1a\n\rresource_name\x18\x01 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01:U\xea\x41R\n#securitycenter.googleapis.com/Asset\x12+organizations/{organization}/assets/{asset}B~\n'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3", - dependencies=[ - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_ASSET_SECURITYCENTERPROPERTIES = _descriptor.Descriptor( - name="SecurityCenterProperties", - full_name="google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="resource_name", - full_name="google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties.resource_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\005", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_type", - full_name="google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties.resource_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_parent", - full_name="google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties.resource_parent", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_project", - full_name="google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties.resource_project", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_owners", - full_name="google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties.resource_owners", - index=4, - number=5, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=712, - serialized_end=865, -) - -_ASSET_RESOURCEPROPERTIESENTRY = _descriptor.Descriptor( - name="ResourcePropertiesEntry", - full_name="google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=867, - serialized_end=948, -) - -_ASSET = _descriptor.Descriptor( - name="Asset", - full_name="google.cloud.securitycenter.v1beta1.Asset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1beta1.Asset.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_center_properties", - full_name="google.cloud.securitycenter.v1beta1.Asset.security_center_properties", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_properties", - full_name="google.cloud.securitycenter.v1beta1.Asset.resource_properties", - index=2, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_marks", - full_name="google.cloud.securitycenter.v1beta1.Asset.security_marks", - index=3, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.securitycenter.v1beta1.Asset.create_time", - index=4, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_time", - full_name="google.cloud.securitycenter.v1beta1.Asset.update_time", - index=5, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_ASSET_SECURITYCENTERPROPERTIES, _ASSET_RESOURCEPROPERTIESENTRY,], - enum_types=[], - serialized_options=b"\352AR\n#securitycenter.googleapis.com/Asset\022+organizations/{organization}/assets/{asset}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=312, - serialized_end=1035, -) - -_ASSET_SECURITYCENTERPROPERTIES.containing_type = _ASSET -_ASSET_RESOURCEPROPERTIESENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_ASSET_RESOURCEPROPERTIESENTRY.containing_type = _ASSET -_ASSET.fields_by_name[ - "security_center_properties" -].message_type = _ASSET_SECURITYCENTERPROPERTIES -_ASSET.fields_by_name[ - "resource_properties" -].message_type = _ASSET_RESOURCEPROPERTIESENTRY -_ASSET.fields_by_name[ - "security_marks" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2._SECURITYMARKS -) -_ASSET.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name[ - "update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -DESCRIPTOR.message_types_by_name["Asset"] = _ASSET -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Asset = _reflection.GeneratedProtocolMessageType( - "Asset", - (_message.Message,), - { - "SecurityCenterProperties": _reflection.GeneratedProtocolMessageType( - "SecurityCenterProperties", - (_message.Message,), - { - "DESCRIPTOR": _ASSET_SECURITYCENTERPROPERTIES, - "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2", - "__doc__": """Security Command Center managed properties. These properties are - managed by Security Command Center and cannot be modified by the user. - - Attributes: - resource_name: - 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: - 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: - The full resource name of the immediate parent of the - resource. See: https://cloud.google.com/apis/design/resource_n - ames#full_resource_name - resource_project: - 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: - Owners of the Google Cloud resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties) - }, - ), - "ResourcePropertiesEntry": _reflection.GeneratedProtocolMessageType( - "ResourcePropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _ASSET_RESOURCEPROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry) - }, - ), - "DESCRIPTOR": _ASSET, - "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2", - "__doc__": """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: - The relative resource name of this asset. See: https://cloud.g - oogle.com/apis/design/resource_names#relative_resource_name - Example: “organizations/{organization_id}/assets/{asset_id}”. - security_center_properties: - Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified - by the user. - resource_properties: - Resource managed properties. These properties are managed and - defined by the Google Cloud resource and cannot be modified by - the user. - security_marks: - 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: - The time at which the asset was created in Security Command - Center. - update_time: - The time at which the asset was last updated, added, or - deleted in Security Command Center. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Asset) - }, -) -_sym_db.RegisterMessage(Asset) -_sym_db.RegisterMessage(Asset.SecurityCenterProperties) -_sym_db.RegisterMessage(Asset.ResourcePropertiesEntry) - - -DESCRIPTOR._options = None -_ASSET_SECURITYCENTERPROPERTIES.fields_by_name["resource_name"]._options = None -_ASSET_RESOURCEPROPERTIESENTRY._options = None -_ASSET._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1beta1/proto/asset_pb2_grpc.py b/google/cloud/securitycenter_v1beta1/proto/asset_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/asset_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py b/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py deleted file mode 100644 index b62cd8a8..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py +++ /dev/null @@ -1,460 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1beta1/proto/finding.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1beta1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2, -) -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1beta1/proto/finding.proto", - package="google.cloud.securitycenter.v1beta1", - syntax="proto3", - serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n7google/cloud/securitycenter_v1beta1/proto/finding.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb8\x05\n\x07\x46inding\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x06parent\x18\x02 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_name\x18\x03 \x01(\t\x12\x41\n\x05state\x18\x04 \x01(\x0e\x32\x32.google.cloud.securitycenter.v1beta1.Finding.State\x12\x10\n\x08\x63\x61tegory\x18\x05 \x01(\t\x12\x14\n\x0c\x65xternal_uri\x18\x06 \x01(\t\x12]\n\x11source_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Finding.SourcePropertiesEntry\x12O\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarksB\x03\xe0\x41\x03\x12.\n\nevent_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63reate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1aO\n\x15SourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"8\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08INACTIVE\x10\x02:l\xea\x41i\n%securitycenter.googleapis.com/Finding\x12@organizations/{organization}/sources/{source}/findings/{finding}B~\n\'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_FINDING_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.securitycenter.v1beta1.Finding.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INACTIVE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=844, - serialized_end=900, -) -_sym_db.RegisterEnumDescriptor(_FINDING_STATE) - - -_FINDING_SOURCEPROPERTIESENTRY = _descriptor.Descriptor( - name="SourcePropertiesEntry", - full_name="google.cloud.securitycenter.v1beta1.Finding.SourcePropertiesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1beta1.Finding.SourcePropertiesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1beta1.Finding.SourcePropertiesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=763, - serialized_end=842, -) - -_FINDING = _descriptor.Descriptor( - name="Finding", - full_name="google.cloud.securitycenter.v1beta1.Finding", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1beta1.Finding.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1beta1.Finding.parent", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\005", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_name", - full_name="google.cloud.securitycenter.v1beta1.Finding.resource_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.securitycenter.v1beta1.Finding.state", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.securitycenter.v1beta1.Finding.category", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="external_uri", - full_name="google.cloud.securitycenter.v1beta1.Finding.external_uri", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_properties", - full_name="google.cloud.securitycenter.v1beta1.Finding.source_properties", - index=6, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_marks", - full_name="google.cloud.securitycenter.v1beta1.Finding.security_marks", - index=7, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="event_time", - full_name="google.cloud.securitycenter.v1beta1.Finding.event_time", - index=8, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.securitycenter.v1beta1.Finding.create_time", - index=9, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_FINDING_SOURCEPROPERTIESENTRY,], - enum_types=[_FINDING_STATE,], - serialized_options=b"\352Ai\n%securitycenter.googleapis.com/Finding\022@organizations/{organization}/sources/{source}/findings/{finding}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=314, - serialized_end=1010, -) - -_FINDING_SOURCEPROPERTIESENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_FINDING_SOURCEPROPERTIESENTRY.containing_type = _FINDING -_FINDING.fields_by_name["state"].enum_type = _FINDING_STATE -_FINDING.fields_by_name[ - "source_properties" -].message_type = _FINDING_SOURCEPROPERTIESENTRY -_FINDING.fields_by_name[ - "security_marks" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2._SECURITYMARKS -) -_FINDING.fields_by_name[ - "event_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_FINDING.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_FINDING_STATE.containing_type = _FINDING -DESCRIPTOR.message_types_by_name["Finding"] = _FINDING -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Finding = _reflection.GeneratedProtocolMessageType( - "Finding", - (_message.Message,), - { - "SourcePropertiesEntry": _reflection.GeneratedProtocolMessageType( - "SourcePropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _FINDING_SOURCEPROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1beta1.proto.finding_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Finding.SourcePropertiesEntry) - }, - ), - "DESCRIPTOR": _FINDING, - "__module__": "google.cloud.securitycenter_v1beta1.proto.finding_pb2", - "__doc__": """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: - 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: - 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: - 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_nam - e 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: - The state of the finding. - category: - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. Example: - “XSS_FLASH_INJECTION” - external_uri: - 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: - 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: - 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: - 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: - The time at which the finding was created in Security Command - Center. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Finding) - }, -) -_sym_db.RegisterMessage(Finding) -_sym_db.RegisterMessage(Finding.SourcePropertiesEntry) - - -DESCRIPTOR._options = None -_FINDING_SOURCEPROPERTIESENTRY._options = None -_FINDING.fields_by_name["parent"]._options = None -_FINDING.fields_by_name["security_marks"]._options = None -_FINDING._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1beta1/proto/finding_pb2_grpc.py b/google/cloud/securitycenter_v1beta1/proto/finding_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/finding_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py b/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py deleted file mode 100644 index 0482472a..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py +++ /dev/null @@ -1,272 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1beta1/proto/organization_settings.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1beta1/proto/organization_settings.proto", - package="google.cloud.securitycenter.v1beta1", - syntax="proto3", - serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nEgoogle/cloud/securitycenter_v1beta1/proto/organization_settings.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x19google/api/resource.proto\x1a\x1cgoogle/api/annotations.proto"\x94\x04\n\x14OrganizationSettings\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1e\n\x16\x65nable_asset_discovery\x18\x02 \x01(\x08\x12n\n\x16\x61sset_discovery_config\x18\x03 \x01(\x0b\x32N.google.cloud.securitycenter.v1beta1.OrganizationSettings.AssetDiscoveryConfig\x1a\xf1\x01\n\x14\x41ssetDiscoveryConfig\x12\x13\n\x0bproject_ids\x18\x01 \x03(\t\x12t\n\x0einclusion_mode\x18\x02 \x01(\x0e\x32\\.google.cloud.securitycenter.v1beta1.OrganizationSettings.AssetDiscoveryConfig.InclusionMode"N\n\rInclusionMode\x12\x1e\n\x1aINCLUSION_MODE_UNSPECIFIED\x10\x00\x12\x10\n\x0cINCLUDE_ONLY\x10\x01\x12\x0b\n\x07\x45XCLUDE\x10\x02:j\xea\x41g\n2securitycenter.googleapis.com/OrganizationSettings\x12\x31organizations/{organization}/organizationSettingsB~\n\'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3', - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE = _descriptor.EnumDescriptor( - name="InclusionMode", - full_name="google.cloud.securitycenter.v1beta1.OrganizationSettings.AssetDiscoveryConfig.InclusionMode", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="INCLUSION_MODE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INCLUDE_ONLY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="EXCLUDE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=514, - serialized_end=592, -) -_sym_db.RegisterEnumDescriptor(_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE) - - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG = _descriptor.Descriptor( - name="AssetDiscoveryConfig", - full_name="google.cloud.securitycenter.v1beta1.OrganizationSettings.AssetDiscoveryConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="project_ids", - full_name="google.cloud.securitycenter.v1beta1.OrganizationSettings.AssetDiscoveryConfig.project_ids", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="inclusion_mode", - full_name="google.cloud.securitycenter.v1beta1.OrganizationSettings.AssetDiscoveryConfig.inclusion_mode", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=351, - serialized_end=592, -) - -_ORGANIZATIONSETTINGS = _descriptor.Descriptor( - name="OrganizationSettings", - full_name="google.cloud.securitycenter.v1beta1.OrganizationSettings", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1beta1.OrganizationSettings.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="enable_asset_discovery", - full_name="google.cloud.securitycenter.v1beta1.OrganizationSettings.enable_asset_discovery", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_discovery_config", - full_name="google.cloud.securitycenter.v1beta1.OrganizationSettings.asset_discovery_config", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG,], - enum_types=[], - serialized_options=b"\352Ag\n2securitycenter.googleapis.com/OrganizationSettings\0221organizations/{organization}/organizationSettings", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=168, - serialized_end=700, -) - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG.fields_by_name[ - "inclusion_mode" -].enum_type = _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG.containing_type = _ORGANIZATIONSETTINGS -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE.containing_type = ( - _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG -) -_ORGANIZATIONSETTINGS.fields_by_name[ - "asset_discovery_config" -].message_type = _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG -DESCRIPTOR.message_types_by_name["OrganizationSettings"] = _ORGANIZATIONSETTINGS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -OrganizationSettings = _reflection.GeneratedProtocolMessageType( - "OrganizationSettings", - (_message.Message,), - { - "AssetDiscoveryConfig": _reflection.GeneratedProtocolMessageType( - "AssetDiscoveryConfig", - (_message.Message,), - { - "DESCRIPTOR": _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG, - "__module__": "google.cloud.securitycenter_v1beta1.proto.organization_settings_pb2", - "__doc__": """The configuration used for Asset Discovery runs. - - Attributes: - project_ids: - The project ids to use for filtering asset discovery. - inclusion_mode: - The mode to use for filtering asset discovery. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.OrganizationSettings.AssetDiscoveryConfig) - }, - ), - "DESCRIPTOR": _ORGANIZATIONSETTINGS, - "__module__": "google.cloud.securitycenter_v1beta1.proto.organization_settings_pb2", - "__doc__": """User specified settings that are attached to the Security Command - Center organization. - - Attributes: - name: - 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: - 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: - The configuration used for Asset Discovery runs. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.OrganizationSettings) - }, -) -_sym_db.RegisterMessage(OrganizationSettings) -_sym_db.RegisterMessage(OrganizationSettings.AssetDiscoveryConfig) - - -DESCRIPTOR._options = None -_ORGANIZATIONSETTINGS._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2_grpc.py b/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2.py b/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2.py deleted file mode 100644 index 6084afdf..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2.py +++ /dev/null @@ -1,173 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto", - package="google.cloud.securitycenter.v1beta1", - syntax="proto3", - serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nLgoogle/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/api/annotations.proto"\xec\x01\n\x19RunAssetDiscoveryResponse\x12S\n\x05state\x18\x01 \x01(\x0e\x32\x44.google.cloud.securitycenter.v1beta1.RunAssetDiscoveryResponse.State\x12+\n\x08\x64uration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"M\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\r\n\tCOMPLETED\x10\x01\x12\x0e\n\nSUPERSEDED\x10\x02\x12\x0e\n\nTERMINATED\x10\x03\x42~\n\'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3', - dependencies=[ - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_RUNASSETDISCOVERYRESPONSE_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.securitycenter.v1beta1.RunAssetDiscoveryResponse.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="COMPLETED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUPERSEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TERMINATED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=339, - serialized_end=416, -) -_sym_db.RegisterEnumDescriptor(_RUNASSETDISCOVERYRESPONSE_STATE) - - -_RUNASSETDISCOVERYRESPONSE = _descriptor.Descriptor( - name="RunAssetDiscoveryResponse", - full_name="google.cloud.securitycenter.v1beta1.RunAssetDiscoveryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.securitycenter.v1beta1.RunAssetDiscoveryResponse.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="duration", - full_name="google.cloud.securitycenter.v1beta1.RunAssetDiscoveryResponse.duration", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_RUNASSETDISCOVERYRESPONSE_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=180, - serialized_end=416, -) - -_RUNASSETDISCOVERYRESPONSE.fields_by_name[ - "state" -].enum_type = _RUNASSETDISCOVERYRESPONSE_STATE -_RUNASSETDISCOVERYRESPONSE.fields_by_name[ - "duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_RUNASSETDISCOVERYRESPONSE_STATE.containing_type = _RUNASSETDISCOVERYRESPONSE -DESCRIPTOR.message_types_by_name[ - "RunAssetDiscoveryResponse" -] = _RUNASSETDISCOVERYRESPONSE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -RunAssetDiscoveryResponse = _reflection.GeneratedProtocolMessageType( - "RunAssetDiscoveryResponse", - (_message.Message,), - { - "DESCRIPTOR": _RUNASSETDISCOVERYRESPONSE, - "__module__": "google.cloud.securitycenter_v1beta1.proto.run_asset_discovery_response_pb2", - "__doc__": """Response of asset discovery run - - Attributes: - state: - The state of an asset discovery run. - duration: - The duration between asset discovery run start and end - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.RunAssetDiscoveryResponse) - }, -) -_sym_db.RegisterMessage(RunAssetDiscoveryResponse) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2_grpc.py b/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py b/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py deleted file mode 100644 index 144c51d3..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py +++ /dev/null @@ -1,201 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1beta1/proto/security_marks.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1beta1/proto/security_marks.proto", - package="google.cloud.securitycenter.v1beta1", - syntax="proto3", - serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", - create_key=_descriptor._internal_create_key, - serialized_pb=b"\n>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x19google/api/resource.proto\x1a\x1cgoogle/api/annotations.proto\"\xd8\x02\n\rSecurityMarks\x12\x0c\n\x04name\x18\x01 \x01(\t\x12L\n\x05marks\x18\x02 \x03(\x0b\x32=.google.cloud.securitycenter.v1beta1.SecurityMarks.MarksEntry\x1a,\n\nMarksEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01:\xbc\x01\xea\x41\xb8\x01\n+securitycenter.googleapis.com/SecurityMarks\x12\x39organizations/{organization}/assets/{asset}/securityMarks\x12Norganizations/{organization}/sources/{source}/findings/{finding}/securityMarksB~\n'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3", - dependencies=[ - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_SECURITYMARKS_MARKSENTRY = _descriptor.Descriptor( - name="MarksEntry", - full_name="google.cloud.securitycenter.v1beta1.SecurityMarks.MarksEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1beta1.SecurityMarks.MarksEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1beta1.SecurityMarks.MarksEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=270, - serialized_end=314, -) - -_SECURITYMARKS = _descriptor.Descriptor( - name="SecurityMarks", - full_name="google.cloud.securitycenter.v1beta1.SecurityMarks", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1beta1.SecurityMarks.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="marks", - full_name="google.cloud.securitycenter.v1beta1.SecurityMarks.marks", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_SECURITYMARKS_MARKSENTRY,], - enum_types=[], - serialized_options=b"\352A\270\001\n+securitycenter.googleapis.com/SecurityMarks\0229organizations/{organization}/assets/{asset}/securityMarks\022Norganizations/{organization}/sources/{source}/findings/{finding}/securityMarks", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=161, - serialized_end=505, -) - -_SECURITYMARKS_MARKSENTRY.containing_type = _SECURITYMARKS -_SECURITYMARKS.fields_by_name["marks"].message_type = _SECURITYMARKS_MARKSENTRY -DESCRIPTOR.message_types_by_name["SecurityMarks"] = _SECURITYMARKS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -SecurityMarks = _reflection.GeneratedProtocolMessageType( - "SecurityMarks", - (_message.Message,), - { - "MarksEntry": _reflection.GeneratedProtocolMessageType( - "MarksEntry", - (_message.Message,), - { - "DESCRIPTOR": _SECURITYMARKS_MARKSENTRY, - "__module__": "google.cloud.securitycenter_v1beta1.proto.security_marks_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.SecurityMarks.MarksEntry) - }, - ), - "DESCRIPTOR": _SECURITYMARKS, - "__module__": "google.cloud.securitycenter_v1beta1.proto.security_marks_pb2", - "__doc__": """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: - 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: - 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) - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.SecurityMarks) - }, -) -_sym_db.RegisterMessage(SecurityMarks) -_sym_db.RegisterMessage(SecurityMarks.MarksEntry) - - -DESCRIPTOR._options = None -_SECURITYMARKS_MARKSENTRY._options = None -_SECURITYMARKS._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2_grpc.py b/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1beta1/proto/securitycenter_service_pb2.py b/google/cloud/securitycenter_v1beta1/proto/securitycenter_service_pb2.py deleted file mode 100644 index 8616e6cb..00000000 --- a/google/cloud/securitycenter_v1beta1/proto/securitycenter_service_pb2.py +++ /dev/null @@ -1,3082 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1beta1.proto import ( - asset_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_asset__pb2, -) -from google.cloud.securitycenter_v1beta1.proto import ( - finding_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_finding__pb2, -) -from google.cloud.securitycenter_v1beta1.proto import ( - organization_settings_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_organization__settings__pb2, -) -from google.cloud.securitycenter_v1beta1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2, -) -from google.cloud.securitycenter_v1beta1.proto import ( - source_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_source__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto", - package="google.cloud.securitycenter.v1beta1", - syntax="proto3", - serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nFgoogle/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x35google/cloud/securitycenter_v1beta1/proto/asset.proto\x1a\x37google/cloud/securitycenter_v1beta1/proto/finding.proto\x1a\x45google/cloud/securitycenter_v1beta1/proto/organization_settings.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x36google/cloud/securitycenter_v1beta1/proto/source.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a#google/longrunning/operations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb1\x01\n\x14\x43reateFindingRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x17\n\nfinding_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x42\n\x07\x66inding\x18\x03 \x01(\x0b\x32,.google.cloud.securitycenter.v1beta1.FindingB\x03\xe0\x41\x02"\xa1\x01\n\x13\x43reateSourceRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12@\n\x06source\x18\x02 \x01(\x0b\x32+.google.cloud.securitycenter.v1beta1.SourceB\x03\xe0\x41\x02"j\n\x1eGetOrganizationSettingsRequest\x12H\n\x04name\x18\x01 \x01(\tB:\xe0\x41\x02\xfa\x41\x34\n2securitycenter.googleapis.com/OrganizationSettings"N\n\x10GetSourceRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source"\x90\x02\n\x12GroupAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12\x33\n\x10\x63ompare_duration\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12-\n\tread_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xa9\x01\n\x13GroupAssetsResponse\x12J\n\x10group_by_results\x18\x01 \x03(\x0b\x32\x30.google.cloud.securitycenter.v1beta1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t"\xd1\x01\n\x14GroupFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\npage_token\x18\x05 \x01(\t\x12\x11\n\tpage_size\x18\x06 \x01(\x05"\xab\x01\n\x15GroupFindingsResponse\x12J\n\x10group_by_results\x18\x01 \x03(\x0b\x32\x30.google.cloud.securitycenter.v1beta1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t"\xbd\x01\n\x0bGroupResult\x12T\n\nproperties\x18\x01 \x03(\x0b\x32@.google.cloud.securitycenter.v1beta1.GroupResult.PropertiesEntry\x12\r\n\x05\x63ount\x18\x02 \x01(\x03\x1aI\n\x0fPropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"\x85\x01\n\x12ListSourcesRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x07 \x01(\x05"l\n\x13ListSourcesResponse\x12<\n\x07sources\x18\x01 \x03(\x0b\x32+.google.cloud.securitycenter.v1beta1.Source\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\xbf\x02\n\x11ListAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x33\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x01\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xd6\x03\n\x12ListAssetsResponse\x12\x65\n\x13list_assets_results\x18\x01 \x03(\x0b\x32H.google.cloud.securitycenter.v1beta1.ListAssetsResponse.ListAssetsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\xfc\x01\n\x10ListAssetsResult\x12\x39\n\x05\x61sset\x18\x01 \x01(\x0b\x32*.google.cloud.securitycenter.v1beta1.Asset\x12]\n\x05state\x18\x02 \x01(\x0e\x32N.google.cloud.securitycenter.v1beta1.ListAssetsResponse.ListAssetsResult.State"N\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06UNUSED\x10\x01\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x02\x12\x0b\n\x07REMOVED\x10\x03\x12\n\n\x06\x41\x43TIVE\x10\x04"\x80\x02\n\x13ListFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\nfield_mask\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x01\x12\x12\n\npage_token\x18\x06 \x01(\t\x12\x11\n\tpage_size\x18\x07 \x01(\x05"\xb2\x01\n\x14ListFindingsResponse\x12>\n\x08\x66indings\x18\x01 \x03(\x0b\x32,.google.cloud.securitycenter.v1beta1.Finding\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\xd2\x01\n\x16SetFindingStateRequest\x12;\n\x04name\x18\x01 \x01(\tB-\xe0\x41\x02\xfa\x41\'\n%securitycenter.googleapis.com/Finding\x12\x46\n\x05state\x18\x02 \x01(\x0e\x32\x32.google.cloud.securitycenter.v1beta1.Finding.StateB\x03\xe0\x41\x02\x12\x33\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x02"d\n\x18RunAssetDiscoveryRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization"\x8b\x01\n\x14UpdateFindingRequest\x12\x42\n\x07\x66inding\x18\x01 \x01(\x0b\x32,.google.cloud.securitycenter.v1beta1.FindingB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xb3\x01\n!UpdateOrganizationSettingsRequest\x12]\n\x15organization_settings\x18\x01 \x01(\x0b\x32\x39.google.cloud.securitycenter.v1beta1.OrganizationSettingsB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\x88\x01\n\x13UpdateSourceRequest\x12@\n\x06source\x18\x01 \x01(\x0b\x32+.google.cloud.securitycenter.v1beta1.SourceB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xce\x01\n\x1aUpdateSecurityMarksRequest\x12O\n\x0esecurity_marks\x18\x01 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarksB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12.\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\xeb\x1e\n\x0eSecurityCenter\x12\xc0\x01\n\x0c\x43reateSource\x12\x38.google.cloud.securitycenter.v1beta1.CreateSourceRequest\x1a+.google.cloud.securitycenter.v1beta1.Source"I\x82\xd3\xe4\x93\x02\x33")/v1beta1/{parent=organizations/*}/sources:\x06source\xda\x41\rparent,source\x12\xdb\x01\n\rCreateFinding\x12\x39.google.cloud.securitycenter.v1beta1.CreateFindingRequest\x1a,.google.cloud.securitycenter.v1beta1.Finding"a\x82\xd3\xe4\x93\x02?"4/v1beta1/{parent=organizations/*/sources/*}/findings:\x07\x66inding\xda\x41\x19parent,finding_id,finding\x12\x9b\x01\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"P\x82\xd3\xe4\x93\x02?":/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy:\x01*\xda\x41\x08resource\x12\xde\x01\n\x17GetOrganizationSettings\x12\x43.google.cloud.securitycenter.v1beta1.GetOrganizationSettingsRequest\x1a\x39.google.cloud.securitycenter.v1beta1.OrganizationSettings"C\x82\xd3\xe4\x93\x02\x36\x12\x34/v1beta1/{name=organizations/*/organizationSettings}\xda\x41\x04name\x12\xa9\x01\n\tGetSource\x12\x35.google.cloud.securitycenter.v1beta1.GetSourceRequest\x1a+.google.cloud.securitycenter.v1beta1.Source"8\x82\xd3\xe4\x93\x02+\x12)/v1beta1/{name=organizations/*/sources/*}\xda\x41\x04name\x12\xbb\x01\n\x0bGroupAssets\x12\x37.google.cloud.securitycenter.v1beta1.GroupAssetsRequest\x1a\x38.google.cloud.securitycenter.v1beta1.GroupAssetsResponse"9\x82\xd3\xe4\x93\x02\x33"./v1beta1/{parent=organizations/*}/assets:group:\x01*\x12\xdf\x01\n\rGroupFindings\x12\x39.google.cloud.securitycenter.v1beta1.GroupFindingsRequest\x1a:.google.cloud.securitycenter.v1beta1.GroupFindingsResponse"W\x82\xd3\xe4\x93\x02?":/v1beta1/{parent=organizations/*/sources/*}/findings:group:\x01*\xda\x41\x0fparent,group_by\x12\xaf\x01\n\nListAssets\x12\x36.google.cloud.securitycenter.v1beta1.ListAssetsRequest\x1a\x37.google.cloud.securitycenter.v1beta1.ListAssetsResponse"0\x82\xd3\xe4\x93\x02*\x12(/v1beta1/{parent=organizations/*}/assets\x12\xc1\x01\n\x0cListFindings\x12\x38.google.cloud.securitycenter.v1beta1.ListFindingsRequest\x1a\x39.google.cloud.securitycenter.v1beta1.ListFindingsResponse"<\x82\xd3\xe4\x93\x02\x36\x12\x34/v1beta1/{parent=organizations/*/sources/*}/findings\x12\xbc\x01\n\x0bListSources\x12\x37.google.cloud.securitycenter.v1beta1.ListSourcesRequest\x1a\x38.google.cloud.securitycenter.v1beta1.ListSourcesResponse":\x82\xd3\xe4\x93\x02+\x12)/v1beta1/{parent=organizations/*}/sources\xda\x41\x06parent\x12\xed\x01\n\x11RunAssetDiscovery\x12=.google.cloud.securitycenter.v1beta1.RunAssetDiscoveryRequest\x1a\x1d.google.longrunning.Operation"z\x82\xd3\xe4\x93\x02:"5/v1beta1/{parent=organizations/*}/assets:runDiscovery:\x01*\xda\x41\x06parent\xca\x41.\n\x15google.protobuf.Empty\x12\x15google.protobuf.Empty\x12\xde\x01\n\x0fSetFindingState\x12;.google.cloud.securitycenter.v1beta1.SetFindingStateRequest\x1a,.google.cloud.securitycenter.v1beta1.Finding"`\x82\xd3\xe4\x93\x02\x42"=/v1beta1/{name=organizations/*/sources/*/findings/*}:setState:\x01*\xda\x41\x15name,state,start_time\x12\xa2\x01\n\x0cSetIamPolicy\x12".google.iam.v1.SetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"W\x82\xd3\xe4\x93\x02?":/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy:\x01*\xda\x41\x0fresource,policy\x12\xcd\x01\n\x12TestIamPermissions\x12(.google.iam.v1.TestIamPermissionsRequest\x1a).google.iam.v1.TestIamPermissionsResponse"b\x82\xd3\xe4\x93\x02\x45"@/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions:\x01*\xda\x41\x14resource,permissions\x12\xd1\x01\n\rUpdateFinding\x12\x39.google.cloud.securitycenter.v1beta1.UpdateFindingRequest\x1a,.google.cloud.securitycenter.v1beta1.Finding"W\x82\xd3\xe4\x93\x02G2 `` 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: - 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_proper - ties.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: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.GroupAssetsRequest) - }, -) -_sym_db.RegisterMessage(GroupAssetsRequest) - -GroupAssetsResponse = _reflection.GeneratedProtocolMessageType( - "GroupAssetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _GROUPASSETSRESPONSE, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for grouping by assets. - - Attributes: - group_by_results: - 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: - Time used for executing the groupBy request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.GroupAssetsResponse) - }, -) -_sym_db.RegisterMessage(GroupAssetsResponse) - -GroupFindingsRequest = _reflection.GeneratedProtocolMessageType( - "GroupFindingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _GROUPFINDINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for grouping by findings. - - Attributes: - parent: - 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: - 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: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.GroupFindingsRequest) - }, -) -_sym_db.RegisterMessage(GroupFindingsRequest) - -GroupFindingsResponse = _reflection.GeneratedProtocolMessageType( - "GroupFindingsResponse", - (_message.Message,), - { - "DESCRIPTOR": _GROUPFINDINGSRESPONSE, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for group by findings. - - Attributes: - group_by_results: - 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: - Time used for executing the groupBy request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.GroupFindingsResponse) - }, -) -_sym_db.RegisterMessage(GroupFindingsResponse) - -GroupResult = _reflection.GeneratedProtocolMessageType( - "GroupResult", - (_message.Message,), - { - "PropertiesEntry": _reflection.GeneratedProtocolMessageType( - "PropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _GROUPRESULT_PROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.GroupResult.PropertiesEntry) - }, - ), - "DESCRIPTOR": _GROUPRESULT, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Result containing the properties and count of a groupBy request. - - Attributes: - properties: - Properties matching the groupBy fields in the request. - count: - Total count of resources for the given properties. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.GroupResult) - }, -) -_sym_db.RegisterMessage(GroupResult) -_sym_db.RegisterMessage(GroupResult.PropertiesEntry) - -ListSourcesRequest = _reflection.GeneratedProtocolMessageType( - "ListSourcesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTSOURCESREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing sources. - - Attributes: - parent: - Required. Resource name of the parent of sources to list. Its - format should be “organizations/[organization_id]”. - page_token: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.ListSourcesRequest) - }, -) -_sym_db.RegisterMessage(ListSourcesRequest) - -ListSourcesResponse = _reflection.GeneratedProtocolMessageType( - "ListSourcesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTSOURCESRESPONSE, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing sources. - - Attributes: - sources: - Sources belonging to the requested parent. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.ListSourcesResponse) - }, -) -_sym_db.RegisterMessage(ListSourcesResponse) - -ListAssetsRequest = _reflection.GeneratedProtocolMessageType( - "ListAssetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTASSETSREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing assets. - - Attributes: - parent: - Required. Name of the organization assets should belong to. - Its format is “organizations/[organization_id]”. - filter: - 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: - 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: - 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: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.ListAssetsRequest) - }, -) -_sym_db.RegisterMessage(ListAssetsRequest) - -ListAssetsResponse = _reflection.GeneratedProtocolMessageType( - "ListAssetsResponse", - (_message.Message,), - { - "ListAssetsResult": _reflection.GeneratedProtocolMessageType( - "ListAssetsResult", - (_message.Message,), - { - "DESCRIPTOR": _LISTASSETSRESPONSE_LISTASSETSRESULT, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Result containing the Asset and its State. - - Attributes: - asset: - Asset matching the search request. - state: - State of the asset. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.ListAssetsResponse.ListAssetsResult) - }, - ), - "DESCRIPTOR": _LISTASSETSRESPONSE, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing assets. - - Attributes: - list_assets_results: - Assets matching the list request. - read_time: - Time used for executing the list request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of assets matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.ListAssetsResponse) - }, -) -_sym_db.RegisterMessage(ListAssetsResponse) -_sym_db.RegisterMessage(ListAssetsResponse.ListAssetsResult) - -ListFindingsRequest = _reflection.GeneratedProtocolMessageType( - "ListFindingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTFINDINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing findings. - - Attributes: - parent: - 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: - 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: - 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: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.ListFindingsRequest) - }, -) -_sym_db.RegisterMessage(ListFindingsRequest) - -ListFindingsResponse = _reflection.GeneratedProtocolMessageType( - "ListFindingsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTFINDINGSRESPONSE, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing findings. - - Attributes: - findings: - Findings matching the list request. - read_time: - Time used for executing the list request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of findings matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.ListFindingsResponse) - }, -) -_sym_db.RegisterMessage(ListFindingsResponse) - -SetFindingStateRequest = _reflection.GeneratedProtocolMessageType( - "SetFindingStateRequest", - (_message.Message,), - { - "DESCRIPTOR": _SETFINDINGSTATEREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a finding’s state. - - Attributes: - name: - Required. The relative resource name of the finding. See: http - s://cloud.google.com/apis/design/resource_names#relative_resou - rce_name Example: “organizations/{organization_id}/sources/{so - urce_id}/finding/{finding_id}”. - state: - Required. The desired State of the finding. - start_time: - Required. The time at which the updated state takes effect. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.SetFindingStateRequest) - }, -) -_sym_db.RegisterMessage(SetFindingStateRequest) - -RunAssetDiscoveryRequest = _reflection.GeneratedProtocolMessageType( - "RunAssetDiscoveryRequest", - (_message.Message,), - { - "DESCRIPTOR": _RUNASSETDISCOVERYREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for running asset discovery for an organization. - - Attributes: - parent: - Required. Name of the organization to run asset discovery for. - Its format is “organizations/[organization_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.RunAssetDiscoveryRequest) - }, -) -_sym_db.RegisterMessage(RunAssetDiscoveryRequest) - -UpdateFindingRequest = _reflection.GeneratedProtocolMessageType( - "UpdateFindingRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEFINDINGREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating or creating a finding. - - Attributes: - 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: - The FieldMask to use when updating the finding resource. This - field should not be specified when creating a finding. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.UpdateFindingRequest) - }, -) -_sym_db.RegisterMessage(UpdateFindingRequest) - -UpdateOrganizationSettingsRequest = _reflection.GeneratedProtocolMessageType( - "UpdateOrganizationSettingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEORGANIZATIONSETTINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating an organization’s settings. - - Attributes: - organization_settings: - Required. The organization settings resource to update. - update_mask: - The FieldMask to use when updating the settings resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.UpdateOrganizationSettingsRequest) - }, -) -_sym_db.RegisterMessage(UpdateOrganizationSettingsRequest) - -UpdateSourceRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSourceRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESOURCEREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a source. - - Attributes: - source: - Required. The source resource to update. - update_mask: - The FieldMask to use when updating the source resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.UpdateSourceRequest) - }, -) -_sym_db.RegisterMessage(UpdateSourceRequest) - -UpdateSecurityMarksRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSecurityMarksRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESECURITYMARKSREQUEST, - "__module__": "google.cloud.securitycenter_v1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a SecurityMarks resource. - - Attributes: - security_marks: - Required. The security marks resource to update. - update_mask: - The FieldMask to use when updating the security marks - resource. - start_time: - The time at which the updated SecurityMarks take effect. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.UpdateSecurityMarksRequest) - }, -) -_sym_db.RegisterMessage(UpdateSecurityMarksRequest) - - -DESCRIPTOR._options = None -_CREATEFINDINGREQUEST.fields_by_name["parent"]._options = None -_CREATEFINDINGREQUEST.fields_by_name["finding_id"]._options = None -_CREATEFINDINGREQUEST.fields_by_name["finding"]._options = None -_CREATESOURCEREQUEST.fields_by_name["parent"]._options = None -_CREATESOURCEREQUEST.fields_by_name["source"]._options = None -_GETORGANIZATIONSETTINGSREQUEST.fields_by_name["name"]._options = None -_GETSOURCEREQUEST.fields_by_name["name"]._options = None -_GROUPASSETSREQUEST.fields_by_name["parent"]._options = None -_GROUPASSETSREQUEST.fields_by_name["group_by"]._options = None -_GROUPFINDINGSREQUEST.fields_by_name["parent"]._options = None -_GROUPFINDINGSREQUEST.fields_by_name["group_by"]._options = None -_GROUPRESULT_PROPERTIESENTRY._options = None -_LISTSOURCESREQUEST.fields_by_name["parent"]._options = None -_LISTASSETSREQUEST.fields_by_name["parent"]._options = None -_LISTASSETSREQUEST.fields_by_name["field_mask"]._options = None -_LISTFINDINGSREQUEST.fields_by_name["parent"]._options = None -_LISTFINDINGSREQUEST.fields_by_name["field_mask"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["name"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["state"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["start_time"]._options = None -_RUNASSETDISCOVERYREQUEST.fields_by_name["parent"]._options = None -_UPDATEFINDINGREQUEST.fields_by_name["finding"]._options = None -_UPDATEORGANIZATIONSETTINGSREQUEST.fields_by_name[ - "organization_settings" -]._options = None -_UPDATESOURCEREQUEST.fields_by_name["source"]._options = None -_UPDATESECURITYMARKSREQUEST.fields_by_name["security_marks"]._options = None - -_SECURITYCENTER = _descriptor.ServiceDescriptor( - name="SecurityCenter", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\035securitycenter.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=4810, - serialized_end=8757, - methods=[ - _descriptor.MethodDescriptor( - name="CreateSource", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.CreateSource", - index=0, - containing_service=None, - input_type=_CREATESOURCEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_source__pb2._SOURCE, - serialized_options=b'\202\323\344\223\0023")/v1beta1/{parent=organizations/*}/sources:\006source\332A\rparent,source', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateFinding", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.CreateFinding", - index=1, - containing_service=None, - input_type=_CREATEFINDINGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_finding__pb2._FINDING, - serialized_options=b'\202\323\344\223\002?"4/v1beta1/{parent=organizations/*/sources/*}/findings:\007finding\332A\031parent,finding_id,finding', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetIamPolicy", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.GetIamPolicy", - index=2, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._GETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\002?":/v1beta1/{resource=organizations/*/sources/*}:getIamPolicy:\001*\332A\010resource', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetOrganizationSettings", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.GetOrganizationSettings", - index=3, - containing_service=None, - input_type=_GETORGANIZATIONSETTINGSREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_organization__settings__pb2._ORGANIZATIONSETTINGS, - serialized_options=b"\202\323\344\223\0026\0224/v1beta1/{name=organizations/*/organizationSettings}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetSource", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.GetSource", - index=4, - containing_service=None, - input_type=_GETSOURCEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_source__pb2._SOURCE, - serialized_options=b"\202\323\344\223\002+\022)/v1beta1/{name=organizations/*/sources/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GroupAssets", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.GroupAssets", - index=5, - containing_service=None, - input_type=_GROUPASSETSREQUEST, - output_type=_GROUPASSETSRESPONSE, - serialized_options=b'\202\323\344\223\0023"./v1beta1/{parent=organizations/*}/assets:group:\001*', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GroupFindings", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.GroupFindings", - index=6, - containing_service=None, - input_type=_GROUPFINDINGSREQUEST, - output_type=_GROUPFINDINGSRESPONSE, - serialized_options=b'\202\323\344\223\002?":/v1beta1/{parent=organizations/*/sources/*}/findings:group:\001*\332A\017parent,group_by', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListAssets", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.ListAssets", - index=7, - containing_service=None, - input_type=_LISTASSETSREQUEST, - output_type=_LISTASSETSRESPONSE, - serialized_options=b"\202\323\344\223\002*\022(/v1beta1/{parent=organizations/*}/assets", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListFindings", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.ListFindings", - index=8, - containing_service=None, - input_type=_LISTFINDINGSREQUEST, - output_type=_LISTFINDINGSRESPONSE, - serialized_options=b"\202\323\344\223\0026\0224/v1beta1/{parent=organizations/*/sources/*}/findings", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListSources", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.ListSources", - index=9, - containing_service=None, - input_type=_LISTSOURCESREQUEST, - output_type=_LISTSOURCESRESPONSE, - serialized_options=b"\202\323\344\223\002+\022)/v1beta1/{parent=organizations/*}/sources\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="RunAssetDiscovery", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.RunAssetDiscovery", - index=10, - containing_service=None, - input_type=_RUNASSETDISCOVERYREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002:"5/v1beta1/{parent=organizations/*}/assets:runDiscovery:\001*\332A\006parent\312A.\n\025google.protobuf.Empty\022\025google.protobuf.Empty', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SetFindingState", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.SetFindingState", - index=11, - containing_service=None, - input_type=_SETFINDINGSTATEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_finding__pb2._FINDING, - serialized_options=b'\202\323\344\223\002B"=/v1beta1/{name=organizations/*/sources/*/findings/*}:setState:\001*\332A\025name,state,start_time', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SetIamPolicy", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.SetIamPolicy", - index=12, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._SETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\002?":/v1beta1/{resource=organizations/*/sources/*}:setIamPolicy:\001*\332A\017resource,policy', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="TestIamPermissions", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.TestIamPermissions", - index=13, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSREQUEST, - output_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._TESTIAMPERMISSIONSRESPONSE, - serialized_options=b'\202\323\344\223\002E"@/v1beta1/{resource=organizations/*/sources/*}:testIamPermissions:\001*\332A\024resource,permissions', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateFinding", - full_name="google.cloud.securitycenter.v1beta1.SecurityCenter.UpdateFinding", - index=14, - containing_service=None, - input_type=_UPDATEFINDINGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_finding__pb2._FINDING, - serialized_options=b"\202\323\344\223\002G2 None: + """Instantiate 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:`~.securitycenter_service.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:`~.gcs_source.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: + ~.gcs_source.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. + if request is not None and any([parent, source]): + 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:`~.securitycenter_service.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:`~.gcs_finding.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: + ~.gcs_finding.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. + if request is not None and any([parent, finding_id, finding]): + 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.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + 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.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.organization_settings.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. + if request is not None and any([name]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.source.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. + if request is not None and any([name]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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. + if request is not None and any([parent, group_by]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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. + if request is not None and any([parent]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.empty.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. + if request is not None and any([parent]): + 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.Empty, + metadata_type=empty.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.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:`~.securitycenter_service.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:`~.finding.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:`~.timestamp.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: + ~.finding.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. + if request is not None and any([name, state, start_time]): + 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.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + 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.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.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.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.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.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: + ~.iam_policy.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. + if request is not None and any([resource, permissions]): + 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.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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 = 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.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: + ~.gcs_finding.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. + if request is not None and any([finding]): + 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:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.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: + ~.gcs_organization_settings.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. + if request is not None and any([organization_settings]): + 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:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.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: + ~.gcs_source.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. + if request is not None and any([source]): + 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:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.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: + ~.gcs_security_marks.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. + if request is not None and any([security_marks]): + 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/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1beta1/services/security_center/client.py new file mode 100644 index 00000000..7aa7cdce --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -0,0 +1,1963 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # 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 # 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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]: + """Return 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): + """Convert 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_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: + {@api.name}: 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 + + @staticmethod + def finding_path(organization: str, source: str, finding: str,) -> str: + """Return 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]: + """Parse 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: + """Return a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str, str]: + """Parse 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: + """Return 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]: + """Parse 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: + """Return 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]: + """Parse a source path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[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: + """Instantiate 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 (client_options_lib.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")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else 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": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else 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, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + 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:`~.securitycenter_service.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:`~.gcs_source.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: + ~.gcs_source.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 (:class:`~.securitycenter_service.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:`~.gcs_finding.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: + ~.gcs_finding.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.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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 (:class:`~.securitycenter_service.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: + ~.organization_settings.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 (:class:`~.securitycenter_service.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: + ~.source.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.empty.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.Empty, + metadata_type=empty.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.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:`~.securitycenter_service.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:`~.finding.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:`~.timestamp.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: + ~.finding.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.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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.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.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.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: + ~.iam_policy.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.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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 (:class:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.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: + ~.gcs_finding.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 (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.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: + ~.gcs_organization_settings.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 (:class:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.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: + ~.gcs_source.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 (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.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: + ~.gcs_security_marks.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/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py new file mode 100644 index 00000000..64ef79bd --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py @@ -0,0 +1,668 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..20423f2a --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py new file mode 100644 index 00000000..af81a632 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py @@ -0,0 +1,470 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import 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 retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # 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() + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **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. + scope (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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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, + ) -> typing.Callable[ + [securitycenter_service.CreateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def create_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + typing.Union[ + organization_settings.OrganizationSettings, + typing.Awaitable[organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def get_source( + self, + ) -> typing.Callable[ + [securitycenter_service.GetSourceRequest], + typing.Union[source.Source, typing.Awaitable[source.Source]], + ]: + raise NotImplementedError() + + @property + def group_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupAssetsRequest], + typing.Union[ + securitycenter_service.GroupAssetsResponse, + typing.Awaitable[securitycenter_service.GroupAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def group_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupFindingsRequest], + typing.Union[ + securitycenter_service.GroupFindingsResponse, + typing.Awaitable[securitycenter_service.GroupFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.ListAssetsRequest], + typing.Union[ + securitycenter_service.ListAssetsResponse, + typing.Awaitable[securitycenter_service.ListAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.ListFindingsRequest], + typing.Union[ + securitycenter_service.ListFindingsResponse, + typing.Awaitable[securitycenter_service.ListFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_sources( + self, + ) -> typing.Callable[ + [securitycenter_service.ListSourcesRequest], + typing.Union[ + securitycenter_service.ListSourcesResponse, + typing.Awaitable[securitycenter_service.ListSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def run_asset_discovery( + self, + ) -> typing.Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def set_finding_state( + self, + ) -> typing.Callable[ + [securitycenter_service.SetFindingStateRequest], + typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def update_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + typing.Union[ + gcs_organization_settings.OrganizationSettings, + typing.Awaitable[gcs_organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def update_source( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def update_security_marks( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + typing.Union[ + gcs_security_marks.SecurityMarks, + typing.Awaitable[gcs_security_marks.SecurityMarks], + ], + ]: + raise NotImplementedError() + + +__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..5291388d --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py @@ -0,0 +1,780 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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 +from google import auth # type: ignore +from google.auth import 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # 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: 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, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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. + 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. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "securitycenter.googleapis.com", + credentials: 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: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.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.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 "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["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.GetIamPolicyRequest], policy.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.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.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.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.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.SetIamPolicyRequest], policy.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.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.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.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.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/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..0ec96a14 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,792 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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 import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # 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: 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: + address (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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: 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, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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. + 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. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @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 "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["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.GetIamPolicyRequest], Awaitable[policy.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.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.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.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.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.SetIamPolicyRequest], Awaitable[policy.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.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.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.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.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/google/cloud/securitycenter_v1beta1/types.py b/google/cloud/securitycenter_v1beta1/types.py deleted file mode 100644 index 27d563fe..00000000 --- a/google/cloud/securitycenter_v1beta1/types.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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.securitycenter_v1beta1.proto import asset_pb2 -from google.cloud.securitycenter_v1beta1.proto import finding_pb2 -from google.cloud.securitycenter_v1beta1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1beta1.proto import run_asset_discovery_response_pb2 -from google.cloud.securitycenter_v1beta1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1beta1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1beta1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import struct_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - iam_policy_pb2, - options_pb2, - policy_pb2, - operations_pb2, - any_pb2, - duration_pb2, - field_mask_pb2, - struct_pb2, - timestamp_pb2, - status_pb2, - expr_pb2, -] - -_local_modules = [ - asset_pb2, - finding_pb2, - organization_settings_pb2, - run_asset_discovery_response_pb2, - security_marks_pb2, - securitycenter_service_pb2, - source_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.securitycenter_v1beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/securitycenter_v1beta1/types/__init__.py b/google/cloud/securitycenter_v1beta1/types/__init__.py new file mode 100644 index 00000000..50ef54be --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/__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 .security_marks import SecurityMarks +from .asset import Asset +from .finding import Finding +from .organization_settings import OrganizationSettings +from .run_asset_discovery_response import RunAssetDiscoveryResponse +from .source import Source +from .securitycenter_service import ( + CreateFindingRequest, + CreateSourceRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListSourcesRequest, + ListSourcesResponse, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + SetFindingStateRequest, + RunAssetDiscoveryRequest, + UpdateFindingRequest, + UpdateOrganizationSettingsRequest, + UpdateSourceRequest, + UpdateSecurityMarksRequest, +) + + +__all__ = ( + "SecurityMarks", + "Asset", + "Finding", + "OrganizationSettings", + "RunAssetDiscoveryResponse", + "Source", + "CreateFindingRequest", + "CreateSourceRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListSourcesRequest", + "ListSourcesResponse", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "SetFindingStateRequest", + "RunAssetDiscoveryRequest", + "UpdateFindingRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSourceRequest", + "UpdateSecurityMarksRequest", +) diff --git a/google/cloud/securitycenter_v1beta1/types/asset.py b/google/cloud/securitycenter_v1beta1/types/asset.py new file mode 100644 index 00000000..80b4082d --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/asset.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.asset.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[~.asset.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 (~.gcs_security_marks.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 (~.timestamp.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (~.timestamp.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.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/finding.py b/google/cloud/securitycenter_v1beta1/types/finding.py new file mode 100644 index 00000000..b2a07a64 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/finding.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.finding.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[~.finding.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 (~.gcs_security_marks.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 (~.timestamp.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 (~.timestamp.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.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1beta1/types/organization_settings.py new file mode 100644 index 00000000..3b3ae0b1 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/organization_settings.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 (~.organization_settings.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 (~.organization_settings.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/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..0b9e9d95 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as gp_duration # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1beta1", + manifest={"RunAssetDiscoveryResponse",}, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (~.gp_duration.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=gp_duration.Duration,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/security_marks.py b/google/cloud/securitycenter_v1beta1/types/security_marks.py new file mode 100644 index 00000000..7964b095 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/security_marks.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 + + +__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[~.security_marks.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/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py new file mode 100644 index 00000000..833f60fc --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py @@ -0,0 +1,862 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as duration # type: ignore +from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.gcs_finding.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 (~.gcs_source.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 (~.duration.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 (~.timestamp.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.Duration,) + + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.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[~.securitycenter_service.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 (~.timestamp.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.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 (~.timestamp.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.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[~.securitycenter_service.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 (~.timestamp.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.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[~.securitycenter_service.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.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[~.gcs_source.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 (~.timestamp.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 (~.duration.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 (~.gp_field_mask.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.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.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[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (~.timestamp.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 (~.gcs_asset.Asset): + Asset matching the search request. + state (~.securitycenter_service.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.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 (~.timestamp.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 (~.gp_field_mask.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.Timestamp,) + + field_mask = proto.Field(proto.MESSAGE, number=5, message=gp_field_mask.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[~.gcs_finding.Finding]): + Findings matching the list request. + read_time (~.timestamp.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.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 (~.gcs_finding.Finding.State): + Required. The desired State of the finding. + start_time (~.timestamp.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.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 (~.gcs_finding.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 (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (~.gcs_organization_settings.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (~.gcs_source.Source): + Required. The source resource to update. + update_mask (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (~.gcs_security_marks.SecurityMarks): + Required. The security marks resource to + update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the + security marks resource. + start_time (~.timestamp.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=gp_field_mask.FieldMask,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/source.py b/google/cloud/securitycenter_v1beta1/types/source.py new file mode 100644 index 00000000..2546454f --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/source.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={"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/google/cloud/securitycenter_v1p1beta1/__init__.py b/google/cloud/securitycenter_v1p1beta1/__init__.py index 5e528124..27c3ed04 100644 --- a/google/cloud/securitycenter_v1p1beta1/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/__init__.py @@ -1,45 +1,95 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.securitycenter_v1p1beta1 import types -from google.cloud.securitycenter_v1p1beta1.gapic import enums -from google.cloud.securitycenter_v1p1beta1.gapic import security_center_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class SecurityCenterClient(security_center_client.SecurityCenterClient): - __doc__ = security_center_client.SecurityCenterClient.__doc__ - enums = enums +from .services.security_center import SecurityCenterClient +from .types.asset import Asset +from .types.finding import Finding +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__ = ( - "enums", - "types", + "Asset", + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "Finding", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "NotificationConfig", + "NotificationMessage", + "OrganizationSettings", + "Resource", + "RunAssetDiscoveryRequest", + "RunAssetDiscoveryResponse", + "SecurityMarks", + "SetFindingStateRequest", + "Source", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/__init__.py b/google/cloud/securitycenter_v1p1beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/enums.py b/google/cloud/securitycenter_v1p1beta1/gapic/enums.py deleted file mode 100644 index 9a308dd5..00000000 --- a/google/cloud/securitycenter_v1p1beta1/gapic/enums.py +++ /dev/null @@ -1,182 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class NullValue(enum.IntEnum): - """ - ``NullValue`` is a singleton enumeration to represent the null value - for the ``Value`` type union. - - The JSON representation for ``NullValue`` is JSON ``null``. - - Attributes: - NULL_VALUE (int): Null value. - """ - - NULL_VALUE = 0 - - -class Finding(object): - class Severity(enum.IntEnum): - """ - The severity of the finding. - - Attributes: - SEVERITY_UNSPECIFIED (int): No severity specified. The default value. - CRITICAL (int): Critical severity. - HIGH (int): High severity. - MEDIUM (int): Medium severity. - LOW (int): Low severity. - """ - - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - HIGH = 2 - MEDIUM = 3 - LOW = 4 - - class State(enum.IntEnum): - """ - The state of the finding. - - Attributes: - STATE_UNSPECIFIED (int): Unspecified state. - ACTIVE (int): The finding requires attention and has not been addressed yet. - INACTIVE (int): The finding has been fixed, triaged as a non-issue or otherwise addressed - and is no longer active. - """ - - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - -class ListAssetsResponse(object): - class ListAssetsResult(object): - class StateChange(enum.IntEnum): - """ - 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 - - Attributes: - UNUSED (int): State change is unused, this is the canonical default for this enum. - ADDED (int): Asset was added between the points in time. - REMOVED (int): Asset was removed between the points in time. - ACTIVE (int): Asset was present at both point(s) in time. - """ - - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - -class ListFindingsResponse(object): - class ListFindingsResult(object): - class StateChange(enum.IntEnum): - """ - 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 - - Attributes: - UNUSED (int): State change is unused, this is the canonical default for this enum. - CHANGED (int): The finding has changed state in some way between the points in time - and existed at both points. - UNCHANGED (int): The finding has not changed state between the points in time and - existed at both points. - ADDED (int): The finding was created between the points in time. - REMOVED (int): The finding at timestamp does not match the filter specified, but it - did at timestamp - compare_duration. - """ - - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - -class NotificationConfig(object): - class EventType(enum.IntEnum): - """ - The type of events. - - Attributes: - EVENT_TYPE_UNSPECIFIED (int): Unspecified event type. - FINDING (int): Events for findings. - """ - - EVENT_TYPE_UNSPECIFIED = 0 - FINDING = 1 - - -class OrganizationSettings(object): - class AssetDiscoveryConfig(object): - class InclusionMode(enum.IntEnum): - """ - 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. - - Attributes: - INCLUSION_MODE_UNSPECIFIED (int): Unspecified. Setting the mode with this value will disable - inclusion/exclusion filtering for Asset Discovery. - INCLUDE_ONLY (int): Asset Discovery will capture only the resources within the projects - specified. All other resources will be ignored. - EXCLUDE (int): Asset Discovery will ignore all resources under the projects specified. - All other resources will be retrieved. - """ - - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - -class RunAssetDiscoveryResponse(object): - class State(enum.IntEnum): - """ - The state of an asset discovery run. - - Attributes: - STATE_UNSPECIFIED (int): Asset discovery run state was unspecified. - COMPLETED (int): Asset discovery run completed successfully. - SUPERSEDED (int): Asset discovery run was cancelled with tasks still pending, as another - run for the same organization was started with a higher priority. - TERMINATED (int): Asset discovery run was killed and terminated. - """ - - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client.py b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client.py deleted file mode 100644 index b236e9f0..00000000 --- a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client.py +++ /dev/null @@ -1,2812 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.securitycenter.v1p1beta1 SecurityCenter API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.securitycenter_v1p1beta1.gapic import enums -from google.cloud.securitycenter_v1p1beta1.gapic import security_center_client_config -from google.cloud.securitycenter_v1p1beta1.gapic.transports import ( - security_center_grpc_transport, -) -from google.cloud.securitycenter_v1p1beta1.proto import finding_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import notification_config_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import run_asset_discovery_response_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import securitycenter_service_pb2_grpc -from google.cloud.securitycenter_v1p1beta1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution( - "google-cloud-securitycenter", -).version - - -class SecurityCenterClient(object): - """V1p1Beta1 APIs for Security Center service.""" - - SERVICE_ADDRESS = "securitycenter.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.securitycenter.v1p1beta1.SecurityCenter" - - @classmethod - def from_service_account_file(cls, filename, *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 - - @classmethod - def finding_path(cls, organization, source, finding): - """Return a fully-qualified finding string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}/findings/{finding}", - organization=organization, - source=source, - finding=finding, - ) - - @classmethod - def notification_config_path(cls, organization, notification_config): - """Return a fully-qualified notification_config string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/notificationConfigs/{notification_config}", - organization=organization, - notification_config=notification_config, - ) - - @classmethod - def organization_path(cls, organization): - """Return a fully-qualified organization string.""" - return google.api_core.path_template.expand( - "organizations/{organization}", organization=organization, - ) - - @classmethod - def organization_settings_path(cls, organization): - """Return a fully-qualified organization_settings string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/organizationSettings", - organization=organization, - ) - - @classmethod - def security_marks_path(cls, organization, asset): - """Return a fully-qualified security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/assets/{asset}/securityMarks", - organization=organization, - asset=asset, - ) - - @classmethod - def source_path(cls, organization, source): - """Return a fully-qualified source string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}", - organization=organization, - source=source, - ) - - @classmethod - def topic_path(cls, project, topic): - """Return a fully-qualified topic string.""" - return google.api_core.path_template.expand( - "projects/{project}/topics/{topic}", project=project, topic=topic, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.SecurityCenterGrpcTransport, - Callable[[~.Credentials, type], ~.SecurityCenterGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = security_center_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=security_center_grpc_transport.SecurityCenterGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = security_center_grpc_transport.SecurityCenterGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def create_source( - self, - parent, - source, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a source. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `source`: - >>> source = {} - >>> - >>> response = client.create_source(parent, source) - - Args: - parent (str): Required. Resource name of the new source's parent. Its format - should be "organizations/[organization_id]". - source (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Source` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_source" not in self._inner_api_calls: - self._inner_api_calls[ - "create_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_source, - default_retry=self._method_configs["CreateSource"].retry, - default_timeout=self._method_configs["CreateSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_finding( - self, - parent, - finding_id, - finding, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a finding. The corresponding source must exist for finding - creation to succeed. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `finding_id`: - >>> finding_id = '' - >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} - >>> - >>> response = client.create_finding(parent, finding_id, finding) - - Args: - 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 (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Finding` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_finding" not in self._inner_api_calls: - self._inner_api_calls[ - "create_finding" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_finding, - default_retry=self._method_configs["CreateFinding"].retry, - default_timeout=self._method_configs["CreateFinding"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_finding"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_notification_config( - self, - parent, - config_id, - notification_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a notification config. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `config_id`: - >>> config_id = '' - >>> - >>> # TODO: Initialize `notification_config`: - >>> notification_config = {} - >>> - >>> response = client.create_notification_config(parent, config_id, notification_config) - - Args: - 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 (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_notification_config" not in self._inner_api_calls: - self._inner_api_calls[ - "create_notification_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_notification_config, - default_retry=self._method_configs["CreateNotificationConfig"].retry, - default_timeout=self._method_configs[ - "CreateNotificationConfig" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.CreateNotificationConfigRequest( - parent=parent, config_id=config_id, notification_config=notification_config, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_notification_config( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes a notification config. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') - >>> - >>> client.delete_notification_config(name) - - Args: - name (str): Required. Name of the notification config to delete. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_notification_config" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_notification_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_notification_config, - default_retry=self._method_configs["DeleteNotificationConfig"].retry, - default_timeout=self._method_configs[ - "DeleteNotificationConfig" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.DeleteNotificationConfigRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_iam_policy( - self, - resource, - options_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the access control policy on the specified Source. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> response = client.get_iam_policy(resource) - - Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.GetPolicyOptions` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "get_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_notification_config( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a notification config. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') - >>> - >>> response = client.get_notification_config(name) - - Args: - name (str): Required. Name of the notification config to get. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_notification_config" not in self._inner_api_calls: - self._inner_api_calls[ - "get_notification_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_notification_config, - default_retry=self._method_configs["GetNotificationConfig"].retry, - default_timeout=self._method_configs["GetNotificationConfig"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GetNotificationConfigRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_organization_settings( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the settings for an organization. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> name = client.organization_settings_path('[ORGANIZATION]') - >>> - >>> response = client.get_organization_settings(name) - - Args: - name (str): Required. Name of the organization to get organization settings for. - Its format is "organizations/[organization_id]/organizationSettings". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_organization_settings" not in self._inner_api_calls: - self._inner_api_calls[ - "get_organization_settings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_organization_settings, - default_retry=self._method_configs["GetOrganizationSettings"].retry, - default_timeout=self._method_configs["GetOrganizationSettings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_organization_settings"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_source( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a source. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> response = client.get_source(name) - - Args: - name (str): Required. Relative resource name of the source. Its format is - "organizations/[organization_id]/source/[source_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_source" not in self._inner_api_calls: - self._inner_api_calls[ - "get_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_source, - default_retry=self._method_configs["GetSource"].retry, - default_timeout=self._method_configs["GetSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GetSourceRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def group_assets( - self, - parent, - group_by, - filter_=None, - compare_duration=None, - read_time=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Filters an organization's assets and groups them by their specified - properties. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_assets(parent, group_by): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_assets(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - 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 - 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 : ""`` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Duration` - read_time (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Timestamp` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1p1beta1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "group_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "group_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_assets, - default_retry=self._method_configs["GroupAssets"].retry, - default_timeout=self._method_configs["GroupAssets"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - compare_duration=compare_duration, - read_time=read_time, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def group_findings( - self, - parent, - group_by, - filter_=None, - read_time=None, - compare_duration=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_findings(parent, group_by): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_findings(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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/- - 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 - - The following fields are supported when compare_duration is set: - - - state_change - 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`` - - - 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 : ""`` - read_time (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Duration` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1p1beta1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "group_findings" not in self._inner_api_calls: - self._inner_api_calls[ - "group_findings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_findings, - default_retry=self._method_configs["GroupFindings"].retry, - default_timeout=self._method_configs["GroupFindings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - read_time=read_time, - compare_duration=compare_duration, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_assets( - self, - parent, - filter_=None, - order_by=None, - read_time=None, - compare_duration=None, - field_mask=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists an organization's assets. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_assets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_assets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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 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 (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Duration` - field_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): A field mask to specify the ListAssetsResult fields to be listed in the - response. - An empty field mask will list all fields. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.FieldMask` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1p1beta1.types.ListAssetsResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_assets, - default_retry=self._method_configs["ListAssets"].retry, - default_timeout=self._method_configs["ListAssets"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListAssetsRequest( - parent=parent, - filter=filter_, - order_by=order_by, - read_time=read_time, - compare_duration=compare_duration, - field_mask=field_mask, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="list_assets_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_findings( - self, - parent, - filter_=None, - order_by=None, - read_time=None, - compare_duration=None, - field_mask=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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 - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # Iterate over all results - >>> for element in client.list_findings(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_findings(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - 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 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`` - - 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 (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Duration` - field_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): A field mask to specify the Finding fields to be listed in the response. - An empty field mask will list all fields. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.FieldMask` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1p1beta1.types.ListFindingsResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_findings" not in self._inner_api_calls: - self._inner_api_calls[ - "list_findings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_findings, - default_retry=self._method_configs["ListFindings"].retry, - default_timeout=self._method_configs["ListFindings"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListFindingsRequest( - parent=parent, - filter=filter_, - order_by=order_by, - read_time=read_time, - compare_duration=compare_duration, - field_mask=field_mask, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="list_findings_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_notification_configs( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists notification configs. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_notification_configs(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_notification_configs(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Name of the organization to list notification configs. Its - format is "organizations/[organization_id]". - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_notification_configs" not in self._inner_api_calls: - self._inner_api_calls[ - "list_notification_configs" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_notification_configs, - default_retry=self._method_configs["ListNotificationConfigs"].retry, - default_timeout=self._method_configs["ListNotificationConfigs"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListNotificationConfigsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_notification_configs"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="notification_configs", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def list_sources( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists all sources belonging to an organization. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_sources(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_sources(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Resource name of the parent of sources to list. Its format - should be "organizations/[organization_id]". - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1p1beta1.types.Source` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_sources" not in self._inner_api_calls: - self._inner_api_calls[ - "list_sources" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_sources, - default_retry=self._method_configs["ListSources"].retry, - default_timeout=self._method_configs["ListSources"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.ListSourcesRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_sources"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="sources", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def run_asset_discovery( - self, - parent, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - 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. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> response = client.run_asset_discovery(parent) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. Name of the organization to run asset discovery for. Its - format is "organizations/[organization_id]". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "run_asset_discovery" not in self._inner_api_calls: - self._inner_api_calls[ - "run_asset_discovery" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.run_asset_discovery, - default_retry=self._method_configs["RunAssetDiscovery"].retry, - default_timeout=self._method_configs["RunAssetDiscovery"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.RunAssetDiscoveryRequest(parent=parent,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["run_asset_discovery"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - run_asset_discovery_response_pb2.RunAssetDiscoveryResponse, - metadata_type=empty_pb2.Empty, - ) - - def set_finding_state( - self, - name, - state, - start_time, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates the state of a finding. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> from google.cloud.securitycenter_v1p1beta1 import enums - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> name = client.finding_path('[ORGANIZATION]', '[SOURCE]', '[FINDING]') - >>> - >>> # TODO: Initialize `state`: - >>> state = enums.Finding.State.STATE_UNSPECIFIED - >>> - >>> # TODO: Initialize `start_time`: - >>> start_time = {} - >>> - >>> response = client.set_finding_state(name, state, start_time) - - Args: - 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.State): Required. The desired State of the finding. - start_time (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.Timestamp]): Required. The time at which the updated state takes effect. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Timestamp` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_finding_state" not in self._inner_api_calls: - self._inner_api_calls[ - "set_finding_state" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_finding_state, - default_retry=self._method_configs["SetFindingState"].retry, - default_timeout=self._method_configs["SetFindingState"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.SetFindingStateRequest( - name=name, state=state, start_time=start_time, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_finding_state"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def set_iam_policy( - self, - resource, - policy, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Sets the access control policy on the specified Source. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `policy`: - >>> policy = {} - >>> - >>> response = client.set_iam_policy(resource, policy) - - Args: - resource (str): REQUIRED: The resource for which the policy is being specified. - See the operation documentation for the appropriate value for this field. - policy (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The - size of the policy is limited to a few 10s of KB. An empty policy is a - valid policy but certain Cloud Platform services (such as Projects) - might reject them. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Policy` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.Policy` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "set_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "set_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.set_iam_policy, - default_retry=self._method_configs["SetIamPolicy"].retry, - default_timeout=self._method_configs["SetIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["set_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def test_iam_permissions( - self, - resource, - permissions, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns the permissions that a caller has on the specified source. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] - >>> - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[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 `__. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.TestIamPermissionsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: - self._inner_api_calls[ - "test_iam_permissions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["test_iam_permissions"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_finding( - self, - finding, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates or updates a finding. The corresponding source must exist for a - finding creation to succeed. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} - >>> - >>> response = client.update_finding(finding) - - Args: - finding (Union[dict, ~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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Finding` - update_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.Finding` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_finding" not in self._inner_api_calls: - self._inner_api_calls[ - "update_finding" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_finding, - default_retry=self._method_configs["UpdateFinding"].retry, - default_timeout=self._method_configs["UpdateFinding"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateFindingRequest( - finding=finding, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("finding.name", finding.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_finding"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_notification_config( - self, - notification_config, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `notification_config`: - >>> notification_config = {} - >>> - >>> response = client.update_notification_config(notification_config) - - Args: - notification_config (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): Required. The notification config to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig` - update_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): The FieldMask to use when updating the notification config. - - If empty all mutable fields will be updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_notification_config" not in self._inner_api_calls: - self._inner_api_calls[ - "update_notification_config" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_notification_config, - default_retry=self._method_configs["UpdateNotificationConfig"].retry, - default_timeout=self._method_configs[ - "UpdateNotificationConfig" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateNotificationConfigRequest( - notification_config=notification_config, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("notification_config.name", notification_config.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_organization_settings( - self, - organization_settings, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates an organization's settings. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `organization_settings`: - >>> organization_settings = {} - >>> - >>> response = client.update_organization_settings(organization_settings) - - Args: - organization_settings (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings]): Required. The organization settings resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings` - update_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): The FieldMask to use when updating the settings resource. - - If empty all mutable fields will be updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.OrganizationSettings` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_organization_settings" not in self._inner_api_calls: - self._inner_api_calls[ - "update_organization_settings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_organization_settings, - default_retry=self._method_configs["UpdateOrganizationSettings"].retry, - default_timeout=self._method_configs[ - "UpdateOrganizationSettings" - ].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateOrganizationSettingsRequest( - organization_settings=organization_settings, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [ - ("organization_settings.name", organization_settings.name) - ] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_organization_settings"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_source( - self, - source, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates a source. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `source`: - >>> source = {} - >>> - >>> response = client.update_source(source) - - Args: - source (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.Source]): Required. The source resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Source` - update_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): The FieldMask to use when updating the source resource. - - If empty all mutable fields will be updated. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.Source` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_source" not in self._inner_api_calls: - self._inner_api_calls[ - "update_source" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_source, - default_retry=self._method_configs["UpdateSource"].retry, - default_timeout=self._method_configs["UpdateSource"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateSourceRequest( - source=source, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("source.name", source.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_source"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_security_marks( - self, - security_marks, - update_mask=None, - start_time=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates security marks. - - Example: - >>> from google.cloud import securitycenter_v1p1beta1 - >>> - >>> client = securitycenter_v1p1beta1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `security_marks`: - >>> security_marks = {} - >>> - >>> response = client.update_security_marks(security_marks) - - Args: - security_marks (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.SecurityMarks]): Required. The security marks resource to update. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.SecurityMarks` - update_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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.". - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.FieldMask` - start_time (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.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. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1p1beta1.types.Timestamp` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1p1beta1.types.SecurityMarks` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_security_marks" not in self._inner_api_calls: - self._inner_api_calls[ - "update_security_marks" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_security_marks, - default_retry=self._method_configs["UpdateSecurityMarks"].retry, - default_timeout=self._method_configs["UpdateSecurityMarks"].timeout, - client_info=self._client_info, - ) - - request = securitycenter_service_pb2.UpdateSecurityMarksRequest( - security_marks=security_marks, - update_mask=update_mask, - start_time=start_time, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("security_marks.name", security_marks.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_security_marks"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py deleted file mode 100644 index 1f6297b6..00000000 --- a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py +++ /dev/null @@ -1,177 +0,0 @@ -config = { - "interfaces": { - "google.cloud.securitycenter.v1p1beta1.SecurityCenter": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_2_codes": [], - "no_retry_codes": [], - "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_2_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, - }, - "methods": { - "CreateSource": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateFinding": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "CreateNotificationConfig": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DeleteNotificationConfig": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetNotificationConfig": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetOrganizationSettings": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GetSource": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GroupAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "GroupFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListNotificationConfigs": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "ListSources": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "RunAssetDiscovery": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "SetFindingState": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "SetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "UpdateFinding": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateNotificationConfig": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateOrganizationSettings": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateSource": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "UpdateSecurityMarks": { - "timeout_millis": 480000, - "retry_codes_name": "no_retry_2_codes", - "retry_params_name": "no_retry_2_params", - }, - }, - } - } -} diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/transports/__init__.py b/google/cloud/securitycenter_v1p1beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/transports/security_center_grpc_transport.py b/google/cloud/securitycenter_v1p1beta1/gapic/transports/security_center_grpc_transport.py deleted file mode 100644 index 55d68e42..00000000 --- a/google/cloud/securitycenter_v1p1beta1/gapic/transports/security_center_grpc_transport.py +++ /dev/null @@ -1,436 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.securitycenter_v1p1beta1.proto import securitycenter_service_pb2_grpc - - -class SecurityCenterGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.securitycenter.v1p1beta1 SecurityCenter API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - channel=None, - credentials=None, - address="securitycenter.googleapis.com:443", - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "security_center_stub": securitycenter_service_pb2_grpc.SecurityCenterStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="securitycenter.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def create_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.create_source`. - - Creates a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].CreateSource - - @property - def create_finding(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.create_finding`. - - Creates a finding. The corresponding source must exist for finding - creation to succeed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].CreateFinding - - @property - def create_notification_config(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.create_notification_config`. - - Creates a notification config. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].CreateNotificationConfig - - @property - def delete_notification_config(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.delete_notification_config`. - - Deletes a notification config. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].DeleteNotificationConfig - - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. - - Gets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetIamPolicy - - @property - def get_notification_config(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_notification_config`. - - Gets a notification config. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetNotificationConfig - - @property - def get_organization_settings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_organization_settings`. - - Gets the settings for an organization. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetOrganizationSettings - - @property - def get_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_source`. - - Gets a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetSource - - @property - def group_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. - - Filters an organization's assets and groups them by their specified - properties. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupAssets - - @property - def group_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. - - 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: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupFindings - - @property - def list_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_assets`. - - Lists an organization's assets. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListAssets - - @property - def list_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_findings`. - - 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: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListFindings - - @property - def list_notification_configs(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_notification_configs`. - - Lists notification configs. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListNotificationConfigs - - @property - def list_sources(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.list_sources`. - - Lists all sources belonging to an organization. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].ListSources - - @property - def run_asset_discovery(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.run_asset_discovery`. - - 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: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].RunAssetDiscovery - - @property - def set_finding_state(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.set_finding_state`. - - Updates the state of a finding. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].SetFindingState - - @property - def set_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.set_iam_policy`. - - Sets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].SetIamPolicy - - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. - - Returns the permissions that a caller has on the specified source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].TestIamPermissions - - @property - def update_finding(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_finding`. - - Creates or updates a finding. The corresponding source must exist for a - finding creation to succeed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateFinding - - @property - def update_notification_config(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_notification_config`. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateNotificationConfig - - @property - def update_organization_settings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_organization_settings`. - - Updates an organization's settings. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateOrganizationSettings - - @property - def update_source(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_source`. - - Updates a source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateSource - - @property - def update_security_marks(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.update_security_marks`. - - Updates security marks. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].UpdateSecurityMarks diff --git a/google/cloud/securitycenter_v1p1beta1/proto/__init__.py b/google/cloud/securitycenter_v1p1beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2.py deleted file mode 100644 index 7279b30b..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2.py +++ /dev/null @@ -1,623 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/asset.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1p1beta1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2, -) -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/asset.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n7google/cloud/securitycenter_v1p1beta1/proto/asset.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto\x1a@google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xae\x07\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12i\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32\x45.google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties\x12\x61\n\x13resource_properties\x18\x07 \x03(\x0b\x32\x44.google.cloud.securitycenter.v1p1beta1.Asset.ResourcePropertiesEntry\x12L\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12J\n\niam_policy\x18\x0b \x01(\x0b\x32\x36.google.cloud.securitycenter.v1p1beta1.Asset.IamPolicy\x1a\x80\x02\n\x18SecurityCenterProperties\x12\x15\n\rresource_name\x18\x01 \x01(\t\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x12\x1d\n\x15resource_display_name\x18\x06 \x01(\t\x12$\n\x1cresource_parent_display_name\x18\x07 \x01(\t\x12%\n\x1dresource_project_display_name\x18\x08 \x01(\t\x1a \n\tIamPolicy\x12\x13\n\x0bpolicy_blob\x18\x01 \x01(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01:U\xea\x41R\n#securitycenter.googleapis.com/Asset\x12+organizations/{organization}/assets/{asset}B\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_ASSET_SECURITYCENTERPROPERTIES = _descriptor.Descriptor( - name="SecurityCenterProperties", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="resource_name", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties.resource_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_type", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties.resource_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_parent", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties.resource_parent", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_project", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties.resource_project", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_owners", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties.resource_owners", - index=4, - number=5, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_display_name", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties.resource_display_name", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_parent_display_name", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties.resource_parent_display_name", - index=6, - number=7, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_project_display_name", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties.resource_project_display_name", - index=7, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=767, - serialized_end=1023, -) - -_ASSET_IAMPOLICY = _descriptor.Descriptor( - name="IamPolicy", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.IamPolicy", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="policy_blob", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.IamPolicy.policy_blob", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1025, - serialized_end=1057, -) - -_ASSET_RESOURCEPROPERTIESENTRY = _descriptor.Descriptor( - name="ResourcePropertiesEntry", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.ResourcePropertiesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.ResourcePropertiesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.ResourcePropertiesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1059, - serialized_end=1140, -) - -_ASSET = _descriptor.Descriptor( - name="Asset", - full_name="google.cloud.securitycenter.v1p1beta1.Asset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_center_properties", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.security_center_properties", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_properties", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.resource_properties", - index=2, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_marks", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.security_marks", - index=3, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.create_time", - index=4, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_time", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.update_time", - index=5, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="iam_policy", - full_name="google.cloud.securitycenter.v1p1beta1.Asset.iam_policy", - index=6, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _ASSET_SECURITYCENTERPROPERTIES, - _ASSET_IAMPOLICY, - _ASSET_RESOURCEPROPERTIESENTRY, - ], - enum_types=[], - serialized_options=b"\352AR\n#securitycenter.googleapis.com/Asset\022+organizations/{organization}/assets/{asset}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=285, - serialized_end=1227, -) - -_ASSET_SECURITYCENTERPROPERTIES.containing_type = _ASSET -_ASSET_IAMPOLICY.containing_type = _ASSET -_ASSET_RESOURCEPROPERTIESENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_ASSET_RESOURCEPROPERTIESENTRY.containing_type = _ASSET -_ASSET.fields_by_name[ - "security_center_properties" -].message_type = _ASSET_SECURITYCENTERPROPERTIES -_ASSET.fields_by_name[ - "resource_properties" -].message_type = _ASSET_RESOURCEPROPERTIESENTRY -_ASSET.fields_by_name[ - "security_marks" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2._SECURITYMARKS -) -_ASSET.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name[ - "update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name["iam_policy"].message_type = _ASSET_IAMPOLICY -DESCRIPTOR.message_types_by_name["Asset"] = _ASSET -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Asset = _reflection.GeneratedProtocolMessageType( - "Asset", - (_message.Message,), - { - "SecurityCenterProperties": _reflection.GeneratedProtocolMessageType( - "SecurityCenterProperties", - (_message.Message,), - { - "DESCRIPTOR": _ASSET_SECURITYCENTERPROPERTIES, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.asset_pb2", - "__doc__": """Security Command Center managed properties. These properties are - managed by Security Command Center and cannot be modified by the user. - - Attributes: - resource_name: - The full resource name of the Google Cloud resource this asset - represents. This field is immutable after create time. See: ht - tps://cloud.google.com/apis/design/resource_names#full_resourc - e_name - resource_type: - 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: - The full resource name of the immediate parent of the - resource. See: https://cloud.google.com/apis/design/resource_n - ames#full_resource_name - resource_project: - 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: - Owners of the Google Cloud resource. - resource_display_name: - The user defined display name for this resource. - resource_parent_display_name: - The user defined display name for the parent of this resource. - resource_project_display_name: - The user defined display name for the project of this - resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Asset.SecurityCenterProperties) - }, - ), - "IamPolicy": _reflection.GeneratedProtocolMessageType( - "IamPolicy", - (_message.Message,), - { - "DESCRIPTOR": _ASSET_IAMPOLICY, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.asset_pb2", - "__doc__": """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: - The JSON representation of the Policy associated with the - asset. See - https://cloud.google.com/iam/docs/reference/rest/v1/Policy for - format details. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Asset.IamPolicy) - }, - ), - "ResourcePropertiesEntry": _reflection.GeneratedProtocolMessageType( - "ResourcePropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _ASSET_RESOURCEPROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.asset_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Asset.ResourcePropertiesEntry) - }, - ), - "DESCRIPTOR": _ASSET, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.asset_pb2", - "__doc__": """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: - The relative resource name of this asset. See: https://cloud.g - oogle.com/apis/design/resource_names#relative_resource_name - Example: “organizations/{organization_id}/assets/{asset_id}”. - security_center_properties: - Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified - by the user. - resource_properties: - Resource managed properties. These properties are managed and - defined by the Google Cloud resource and cannot be modified by - the user. - security_marks: - 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: - The time at which the asset was created in Security Command - Center. - update_time: - The time at which the asset was last updated, added, or - deleted in Cloud SCC. - iam_policy: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Asset) - }, -) -_sym_db.RegisterMessage(Asset) -_sym_db.RegisterMessage(Asset.SecurityCenterProperties) -_sym_db.RegisterMessage(Asset.IamPolicy) -_sym_db.RegisterMessage(Asset.ResourcePropertiesEntry) - - -DESCRIPTOR._options = None -_ASSET_RESOURCEPROPERTIESENTRY._options = None -_ASSET._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2.py deleted file mode 100644 index 97dc7485..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2.py +++ /dev/null @@ -1,537 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/finding.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1p1beta1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2, -) -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/finding.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/securitycenter_v1p1beta1/proto/finding.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a@google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xd7\x06\n\x07\x46inding\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06parent\x18\x02 \x01(\t\x12\x15\n\rresource_name\x18\x03 \x01(\t\x12\x43\n\x05state\x18\x04 \x01(\x0e\x32\x34.google.cloud.securitycenter.v1p1beta1.Finding.State\x12\x10\n\x08\x63\x61tegory\x18\x05 \x01(\t\x12\x14\n\x0c\x65xternal_uri\x18\x06 \x01(\t\x12_\n\x11source_properties\x18\x07 \x03(\x0b\x32\x44.google.cloud.securitycenter.v1p1beta1.Finding.SourcePropertiesEntry\x12Q\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarksB\x03\xe0\x41\x03\x12.\n\nevent_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63reate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12I\n\x08severity\x18\r \x01(\x0e\x32\x37.google.cloud.securitycenter.v1p1beta1.Finding.Severity\x1aO\n\x15SourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"8\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08INACTIVE\x10\x02"Q\n\x08Severity\x12\x18\n\x14SEVERITY_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43RITICAL\x10\x01\x12\x08\n\x04HIGH\x10\x02\x12\n\n\x06MEDIUM\x10\x03\x12\x07\n\x03LOW\x10\x04:l\xea\x41i\n%securitycenter.googleapis.com/Finding\x12@organizations/{organization}/sources/{source}/findings/{finding}B\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_FINDING_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INACTIVE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=926, - serialized_end=982, -) -_sym_db.RegisterEnumDescriptor(_FINDING_STATE) - -_FINDING_SEVERITY = _descriptor.EnumDescriptor( - name="Severity", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.Severity", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="SEVERITY_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CRITICAL", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="HIGH", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MEDIUM", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOW", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=984, - serialized_end=1065, -) -_sym_db.RegisterEnumDescriptor(_FINDING_SEVERITY) - - -_FINDING_SOURCEPROPERTIESENTRY = _descriptor.Descriptor( - name="SourcePropertiesEntry", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.SourcePropertiesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.SourcePropertiesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.SourcePropertiesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=845, - serialized_end=924, -) - -_FINDING = _descriptor.Descriptor( - name="Finding", - full_name="google.cloud.securitycenter.v1p1beta1.Finding", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.parent", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_name", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.resource_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.state", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.category", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="external_uri", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.external_uri", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source_properties", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.source_properties", - index=6, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="security_marks", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.security_marks", - index=7, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="event_time", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.event_time", - index=8, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.create_time", - index=9, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="severity", - full_name="google.cloud.securitycenter.v1p1beta1.Finding.severity", - index=10, - number=13, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_FINDING_SOURCEPROPERTIESENTRY,], - enum_types=[_FINDING_STATE, _FINDING_SEVERITY,], - serialized_options=b"\352Ai\n%securitycenter.googleapis.com/Finding\022@organizations/{organization}/sources/{source}/findings/{finding}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=320, - serialized_end=1175, -) - -_FINDING_SOURCEPROPERTIESENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_FINDING_SOURCEPROPERTIESENTRY.containing_type = _FINDING -_FINDING.fields_by_name["state"].enum_type = _FINDING_STATE -_FINDING.fields_by_name[ - "source_properties" -].message_type = _FINDING_SOURCEPROPERTIESENTRY -_FINDING.fields_by_name[ - "security_marks" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2._SECURITYMARKS -) -_FINDING.fields_by_name[ - "event_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_FINDING.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_FINDING.fields_by_name["severity"].enum_type = _FINDING_SEVERITY -_FINDING_STATE.containing_type = _FINDING -_FINDING_SEVERITY.containing_type = _FINDING -DESCRIPTOR.message_types_by_name["Finding"] = _FINDING -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Finding = _reflection.GeneratedProtocolMessageType( - "Finding", - (_message.Message,), - { - "SourcePropertiesEntry": _reflection.GeneratedProtocolMessageType( - "SourcePropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _FINDING_SOURCEPROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.finding_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Finding.SourcePropertiesEntry) - }, - ), - "DESCRIPTOR": _FINDING, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.finding_pb2", - "__doc__": """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: - 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: - The relative resource name of the source the finding belongs - to. See: https://cloud.google.com/apis/design/resource_names#r - elative_resource_name This field is immutable after creation - time. For example: - “organizations/{organization_id}/sources/{source_id}” - resource_name: - 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_nam - e 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: - The state of the finding. - category: - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. Example: - “XSS_FLASH_INJECTION” - external_uri: - 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: - 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: - 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: - 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: - The time at which the finding was created in Security Command - Center. - severity: - The severity of the finding. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Finding) - }, -) -_sym_db.RegisterMessage(Finding) -_sym_db.RegisterMessage(Finding.SourcePropertiesEntry) - - -DESCRIPTOR._options = None -_FINDING_SOURCEPROPERTIESENTRY._options = None -_FINDING.fields_by_name["security_marks"]._options = None -_FINDING._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2.py deleted file mode 100644 index 8bbd4f58..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2.py +++ /dev/null @@ -1,342 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1\352A@\n\033pubsub.googleapis.com/Topic\022!projects/{project}/topics/{topic}", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nEgoogle/cloud/securitycenter_v1p1beta1/proto/notification_config.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto"\xb6\x04\n\x12NotificationConfig\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12W\n\nevent_type\x18\x03 \x01(\x0e\x32\x43.google.cloud.securitycenter.v1p1beta1.NotificationConfig.EventType\x12\x36\n\x0cpubsub_topic\x18\x04 \x01(\tB \xfa\x41\x1d\n\x1bpubsub.googleapis.com/Topic\x12\x1c\n\x0fservice_account\x18\x05 \x01(\tB\x03\xe0\x41\x03\x12\x65\n\x10streaming_config\x18\x06 \x01(\x0b\x32I.google.cloud.securitycenter.v1p1beta1.NotificationConfig.StreamingConfigH\x00\x1a!\n\x0fStreamingConfig\x12\x0e\n\x06\x66ilter\x18\x01 \x01(\t"4\n\tEventType\x12\x1a\n\x16\x45VENT_TYPE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x46INDING\x10\x01:}\xea\x41z\n0securitycenter.googleapis.com/NotificationConfig\x12\x46organizations/{organization}/notificationConfigs/{notification_config}B\x0f\n\rnotify_configB\xc0\x02\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1\xea\x41@\n\x1bpubsub.googleapis.com/Topic\x12!projects/{project}/topics/{topic}b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_NOTIFICATIONCONFIG_EVENTTYPE = _descriptor.EnumDescriptor( - name="EventType", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.EventType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="EVENT_TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FINDING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=573, - serialized_end=625, -) -_sym_db.RegisterEnumDescriptor(_NOTIFICATIONCONFIG_EVENTTYPE) - - -_NOTIFICATIONCONFIG_STREAMINGCONFIG = _descriptor.Descriptor( - name="StreamingConfig", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.StreamingConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.StreamingConfig.filter", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=538, - serialized_end=571, -) - -_NOTIFICATIONCONFIG = _descriptor.Descriptor( - name="NotificationConfig", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.description", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="event_type", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.event_type", - index=2, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pubsub_topic", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.pubsub_topic", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\372A\035\n\033pubsub.googleapis.com/Topic", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="service_account", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.service_account", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="streaming_config", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.streaming_config", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_NOTIFICATIONCONFIG_STREAMINGCONFIG,], - enum_types=[_NOTIFICATIONCONFIG_EVENTTYPE,], - serialized_options=b"\352Az\n0securitycenter.googleapis.com/NotificationConfig\022Forganizations/{organization}/notificationConfigs/{notification_config}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="notify_config", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationConfig.notify_config", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=203, - serialized_end=769, -) - -_NOTIFICATIONCONFIG_STREAMINGCONFIG.containing_type = _NOTIFICATIONCONFIG -_NOTIFICATIONCONFIG.fields_by_name[ - "event_type" -].enum_type = _NOTIFICATIONCONFIG_EVENTTYPE -_NOTIFICATIONCONFIG.fields_by_name[ - "streaming_config" -].message_type = _NOTIFICATIONCONFIG_STREAMINGCONFIG -_NOTIFICATIONCONFIG_EVENTTYPE.containing_type = _NOTIFICATIONCONFIG -_NOTIFICATIONCONFIG.oneofs_by_name["notify_config"].fields.append( - _NOTIFICATIONCONFIG.fields_by_name["streaming_config"] -) -_NOTIFICATIONCONFIG.fields_by_name[ - "streaming_config" -].containing_oneof = _NOTIFICATIONCONFIG.oneofs_by_name["notify_config"] -DESCRIPTOR.message_types_by_name["NotificationConfig"] = _NOTIFICATIONCONFIG -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -NotificationConfig = _reflection.GeneratedProtocolMessageType( - "NotificationConfig", - (_message.Message,), - { - "StreamingConfig": _reflection.GeneratedProtocolMessageType( - "StreamingConfig", - (_message.Message,), - { - "DESCRIPTOR": _NOTIFICATIONCONFIG_STREAMINGCONFIG, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.notification_config_pb2", - "__doc__": """The config for streaming-based notifications, which send each event as - soon as it is detected. - - Attributes: - filter: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.NotificationConfig.StreamingConfig) - }, - ), - "DESCRIPTOR": _NOTIFICATIONCONFIG, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.notification_config_pb2", - "__doc__": """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: - The relative resource name of this notification config. See: h - ttps://cloud.google.com/apis/design/resource_names#relative_re - source_name Example: “organizations/{organization_id}/notifica - tionConfigs/notify_public_bucket”. - description: - The description of the notification config (max of 1024 - characters). - event_type: - The type of events the config is for, e.g. FINDING. - pubsub_topic: - The Pub/Sub topic to send notifications to. Its format is - “projects/[project_id]/topics/[topic]”. - service_account: - Output only. The service account that needs - “pubsub.topics.publish” permission to publish to the Pub/Sub - topic. - notify_config: - The config for triggering notifications. - streaming_config: - The config for triggering streaming-based notifications. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.NotificationConfig) - }, -) -_sym_db.RegisterMessage(NotificationConfig) -_sym_db.RegisterMessage(NotificationConfig.StreamingConfig) - - -DESCRIPTOR._options = None -_NOTIFICATIONCONFIG.fields_by_name["pubsub_topic"]._options = None -_NOTIFICATIONCONFIG.fields_by_name["service_account"]._options = None -_NOTIFICATIONCONFIG._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2.py deleted file mode 100644 index ad130b54..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/notification_message.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.cloud.securitycenter_v1p1beta1.proto import ( - asset_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_asset__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - finding_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - resource_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_resource__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/notification_message.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nFgoogle/cloud/securitycenter_v1p1beta1/proto/notification_message.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x37google/cloud/securitycenter_v1p1beta1/proto/asset.proto\x1a\x39google/cloud/securitycenter_v1p1beta1/proto/finding.proto\x1a:google/cloud/securitycenter_v1p1beta1/proto/resource.proto"\xc6\x01\n\x13NotificationMessage\x12 \n\x18notification_config_name\x18\x01 \x01(\t\x12\x41\n\x07\x66inding\x18\x02 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.FindingH\x00\x12\x41\n\x08resource\x18\x03 \x01(\x0b\x32/.google.cloud.securitycenter.v1p1beta1.ResourceB\x07\n\x05\x65ventB\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_asset__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_NOTIFICATIONMESSAGE = _descriptor.Descriptor( - name="NotificationMessage", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationMessage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="notification_config_name", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationMessage.notification_config_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="finding", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationMessage.finding", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationMessage.resource", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="event", - full_name="google.cloud.securitycenter.v1p1beta1.NotificationMessage.event", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=320, - serialized_end=518, -) - -_NOTIFICATIONMESSAGE.fields_by_name[ - "finding" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2._FINDING -) -_NOTIFICATIONMESSAGE.fields_by_name[ - "resource" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_resource__pb2._RESOURCE -) -_NOTIFICATIONMESSAGE.oneofs_by_name["event"].fields.append( - _NOTIFICATIONMESSAGE.fields_by_name["finding"] -) -_NOTIFICATIONMESSAGE.fields_by_name[ - "finding" -].containing_oneof = _NOTIFICATIONMESSAGE.oneofs_by_name["event"] -DESCRIPTOR.message_types_by_name["NotificationMessage"] = _NOTIFICATIONMESSAGE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -NotificationMessage = _reflection.GeneratedProtocolMessageType( - "NotificationMessage", - (_message.Message,), - { - "DESCRIPTOR": _NOTIFICATIONMESSAGE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.notification_message_pb2", - "__doc__": """Security Command Center’s Notification - - Attributes: - notification_config_name: - Name of the notification config that generated current - notification. - event: - Notification Event. - finding: - If it’s a Finding based notification config, this field will - be populated. - resource: - The Cloud resource tied to the notification. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.NotificationMessage) - }, -) -_sym_db.RegisterMessage(NotificationMessage) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2.py deleted file mode 100644 index 544781d4..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2.py +++ /dev/null @@ -1,272 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nGgoogle/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto"\x98\x04\n\x14OrganizationSettings\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1e\n\x16\x65nable_asset_discovery\x18\x02 \x01(\x08\x12p\n\x16\x61sset_discovery_config\x18\x03 \x01(\x0b\x32P.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.AssetDiscoveryConfig\x1a\xf3\x01\n\x14\x41ssetDiscoveryConfig\x12\x13\n\x0bproject_ids\x18\x01 \x03(\t\x12v\n\x0einclusion_mode\x18\x02 \x01(\x0e\x32^.google.cloud.securitycenter.v1p1beta1.OrganizationSettings.AssetDiscoveryConfig.InclusionMode"N\n\rInclusionMode\x12\x1e\n\x1aINCLUSION_MODE_UNSPECIFIED\x10\x00\x12\x10\n\x0cINCLUDE_ONLY\x10\x01\x12\x0b\n\x07\x45XCLUDE\x10\x02:j\xea\x41g\n2securitycenter.googleapis.com/OrganizationSettings\x12\x31organizations/{organization}/organizationSettingsB\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE = _descriptor.EnumDescriptor( - name="InclusionMode", - full_name="google.cloud.securitycenter.v1p1beta1.OrganizationSettings.AssetDiscoveryConfig.InclusionMode", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="INCLUSION_MODE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INCLUDE_ONLY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="EXCLUDE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=522, - serialized_end=600, -) -_sym_db.RegisterEnumDescriptor(_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE) - - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG = _descriptor.Descriptor( - name="AssetDiscoveryConfig", - full_name="google.cloud.securitycenter.v1p1beta1.OrganizationSettings.AssetDiscoveryConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="project_ids", - full_name="google.cloud.securitycenter.v1p1beta1.OrganizationSettings.AssetDiscoveryConfig.project_ids", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="inclusion_mode", - full_name="google.cloud.securitycenter.v1p1beta1.OrganizationSettings.AssetDiscoveryConfig.inclusion_mode", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=357, - serialized_end=600, -) - -_ORGANIZATIONSETTINGS = _descriptor.Descriptor( - name="OrganizationSettings", - full_name="google.cloud.securitycenter.v1p1beta1.OrganizationSettings", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.OrganizationSettings.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="enable_asset_discovery", - full_name="google.cloud.securitycenter.v1p1beta1.OrganizationSettings.enable_asset_discovery", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_discovery_config", - full_name="google.cloud.securitycenter.v1p1beta1.OrganizationSettings.asset_discovery_config", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG,], - enum_types=[], - serialized_options=b"\352Ag\n2securitycenter.googleapis.com/OrganizationSettings\0221organizations/{organization}/organizationSettings", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=172, - serialized_end=708, -) - -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG.fields_by_name[ - "inclusion_mode" -].enum_type = _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG.containing_type = _ORGANIZATIONSETTINGS -_ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG_INCLUSIONMODE.containing_type = ( - _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG -) -_ORGANIZATIONSETTINGS.fields_by_name[ - "asset_discovery_config" -].message_type = _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG -DESCRIPTOR.message_types_by_name["OrganizationSettings"] = _ORGANIZATIONSETTINGS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -OrganizationSettings = _reflection.GeneratedProtocolMessageType( - "OrganizationSettings", - (_message.Message,), - { - "AssetDiscoveryConfig": _reflection.GeneratedProtocolMessageType( - "AssetDiscoveryConfig", - (_message.Message,), - { - "DESCRIPTOR": _ORGANIZATIONSETTINGS_ASSETDISCOVERYCONFIG, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.organization_settings_pb2", - "__doc__": """The configuration used for Asset Discovery runs. - - Attributes: - project_ids: - The project ids to use for filtering asset discovery. - inclusion_mode: - The mode to use for filtering asset discovery. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.OrganizationSettings.AssetDiscoveryConfig) - }, - ), - "DESCRIPTOR": _ORGANIZATIONSETTINGS, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.organization_settings_pb2", - "__doc__": """User specified settings that are attached to the Security Command - Center organization. - - Attributes: - name: - 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: - 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: - The configuration used for Asset Discovery runs. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.OrganizationSettings) - }, -) -_sym_db.RegisterMessage(OrganizationSettings) -_sym_db.RegisterMessage(OrganizationSettings.AssetDiscoveryConfig) - - -DESCRIPTOR._options = None -_ORGANIZATIONSETTINGS._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2.py deleted file mode 100644 index 8ed3294f..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2.py +++ /dev/null @@ -1,178 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/resource.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/resource.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1B\rResourceProtoP\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n:google/cloud/securitycenter_v1p1beta1/proto/resource.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto"t\n\x08Resource\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x1c\n\x14project_display_name\x18\x03 \x01(\t\x12\x0e\n\x06parent\x18\x04 \x01(\t\x12\x1b\n\x13parent_display_name\x18\x05 \x01(\tB\x8c\x02\n)com.google.cloud.securitycenter.v1p1beta1B\rResourceProtoP\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', - dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,], -) - - -_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.securitycenter.v1p1beta1.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.Resource.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project", - full_name="google.cloud.securitycenter.v1p1beta1.Resource.project", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project_display_name", - full_name="google.cloud.securitycenter.v1p1beta1.Resource.project_display_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.Resource.parent", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent_display_name", - full_name="google.cloud.securitycenter.v1p1beta1.Resource.parent_display_name", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=131, - serialized_end=247, -) - -DESCRIPTOR.message_types_by_name["Resource"] = _RESOURCE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Resource = _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _RESOURCE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.resource_pb2", - "__doc__": """Information related to the Google Cloud resource. - - Attributes: - name: - The full resource name of the resource. See: https://cloud.goo - gle.com/apis/design/resource_names#full_resource_name - project: - The full resource name of project that the resource belongs - to. - project_display_name: - The human readable name of project that the resource belongs - to. - parent: - The full resource name of resource’s parent. - parent_display_name: - The human readable name of resource’s parent. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Resource) - }, -) -_sym_db.RegisterMessage(Resource) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2.py deleted file mode 100644 index a2657770..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2.py +++ /dev/null @@ -1,173 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nNgoogle/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1egoogle/protobuf/duration.proto"\xee\x01\n\x19RunAssetDiscoveryResponse\x12U\n\x05state\x18\x01 \x01(\x0e\x32\x46.google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryResponse.State\x12+\n\x08\x64uration\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"M\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\r\n\tCOMPLETED\x10\x01\x12\x0e\n\nSUPERSEDED\x10\x02\x12\x0e\n\nTERMINATED\x10\x03\x42\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - ], -) - - -_RUNASSETDISCOVERYRESPONSE_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryResponse.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="COMPLETED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUPERSEDED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TERMINATED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=345, - serialized_end=422, -) -_sym_db.RegisterEnumDescriptor(_RUNASSETDISCOVERYRESPONSE_STATE) - - -_RUNASSETDISCOVERYRESPONSE = _descriptor.Descriptor( - name="RunAssetDiscoveryResponse", - full_name="google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryResponse.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="duration", - full_name="google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryResponse.duration", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_RUNASSETDISCOVERYRESPONSE_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=184, - serialized_end=422, -) - -_RUNASSETDISCOVERYRESPONSE.fields_by_name[ - "state" -].enum_type = _RUNASSETDISCOVERYRESPONSE_STATE -_RUNASSETDISCOVERYRESPONSE.fields_by_name[ - "duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_RUNASSETDISCOVERYRESPONSE_STATE.containing_type = _RUNASSETDISCOVERYRESPONSE -DESCRIPTOR.message_types_by_name[ - "RunAssetDiscoveryResponse" -] = _RUNASSETDISCOVERYRESPONSE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -RunAssetDiscoveryResponse = _reflection.GeneratedProtocolMessageType( - "RunAssetDiscoveryResponse", - (_message.Message,), - { - "DESCRIPTOR": _RUNASSETDISCOVERYRESPONSE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.run_asset_discovery_response_pb2", - "__doc__": """Response of asset discovery run - - Attributes: - state: - The state of an asset discovery run. - duration: - The duration between asset discovery run start and end - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryResponse) - }, -) -_sym_db.RegisterMessage(RunAssetDiscoveryResponse) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2.py deleted file mode 100644 index 76a7c221..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2.py +++ /dev/null @@ -1,201 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n@google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto"\xda\x02\n\rSecurityMarks\x12\x0c\n\x04name\x18\x01 \x01(\t\x12N\n\x05marks\x18\x02 \x03(\x0b\x32?.google.cloud.securitycenter.v1p1beta1.SecurityMarks.MarksEntry\x1a,\n\nMarksEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01:\xbc\x01\xea\x41\xb8\x01\n+securitycenter.googleapis.com/SecurityMarks\x12\x39organizations/{organization}/assets/{asset}/securityMarks\x12Norganizations/{organization}/sources/{source}/findings/{finding}/securityMarksB\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_SECURITYMARKS_MARKSENTRY = _descriptor.Descriptor( - name="MarksEntry", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityMarks.MarksEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityMarks.MarksEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityMarks.MarksEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=276, - serialized_end=320, -) - -_SECURITYMARKS = _descriptor.Descriptor( - name="SecurityMarks", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityMarks", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityMarks.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="marks", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityMarks.marks", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_SECURITYMARKS_MARKSENTRY,], - enum_types=[], - serialized_options=b"\352A\270\001\n+securitycenter.googleapis.com/SecurityMarks\0229organizations/{organization}/assets/{asset}/securityMarks\022Norganizations/{organization}/sources/{source}/findings/{finding}/securityMarks", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=165, - serialized_end=511, -) - -_SECURITYMARKS_MARKSENTRY.containing_type = _SECURITYMARKS -_SECURITYMARKS.fields_by_name["marks"].message_type = _SECURITYMARKS_MARKSENTRY -DESCRIPTOR.message_types_by_name["SecurityMarks"] = _SECURITYMARKS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -SecurityMarks = _reflection.GeneratedProtocolMessageType( - "SecurityMarks", - (_message.Message,), - { - "MarksEntry": _reflection.GeneratedProtocolMessageType( - "MarksEntry", - (_message.Message,), - { - "DESCRIPTOR": _SECURITYMARKS_MARKSENTRY, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.security_marks_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.SecurityMarks.MarksEntry) - }, - ), - "DESCRIPTOR": _SECURITYMARKS, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.security_marks_pb2", - "__doc__": """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: - 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: - 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) - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.SecurityMarks) - }, -) -_sym_db.RegisterMessage(SecurityMarks) -_sym_db.RegisterMessage(SecurityMarks.MarksEntry) - - -DESCRIPTOR._options = None -_SECURITYMARKS_MARKSENTRY._options = None -_SECURITYMARKS._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto index 69d864c6..f8f1580f 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto +++ b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto @@ -16,6 +16,7 @@ syntax = "proto3"; package google.cloud.securitycenter.v1p1beta1; +import public "google/cloud/securitycenter/v1p1beta1/notification_message.proto"; import public "google/cloud/securitycenter/v1p1beta1/run_asset_discovery_response.proto"; import "google/api/annotations.proto"; import "google/api/client.proto"; @@ -307,8 +308,7 @@ message CreateNotificationConfigRequest { } ]; - // Required. - // Unique identifier provided by the client within the parent scope. + // 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. string config_id = 2 [(google.api.field_behavior) = REQUIRED]; @@ -586,6 +586,7 @@ message GroupFindingsRequest { // * category: `=`, `:` // * external_uri: `=`, `:` // * event_time: `=`, `>`, `<`, `>=`, `<=` + // * severity: `=`, `:` // // Usage: This should be milliseconds since epoch or an RFC3339 string. // Examples: @@ -614,6 +615,7 @@ message GroupFindingsRequest { // * category // * state // * parent + // * severity // // The following fields are supported when compare_duration is set: // @@ -988,13 +990,14 @@ message ListFindingsRequest { // // The following field and operator combinations are supported: // - // name: `=` - // parent: `=`, `:` - // resource_name: `=`, `:` - // state: `=`, `:` - // category: `=`, `:` - // external_uri: `=`, `:` - // event_time: `=`, `>`, `<`, `>=`, `<=` + // * name: `=` + // * parent: `=`, `:` + // * resource_name: `=`, `:` + // * state: `=`, `:` + // * category: `=`, `:` + // * external_uri: `=`, `:` + // * event_time: `=`, `>`, `<`, `>=`, `<=` + // * severity: `=`, `:` // // Usage: This should be milliseconds since epoch or an RFC3339 string. // Examples: diff --git a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2.py deleted file mode 100644 index 5a70da84..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2.py +++ /dev/null @@ -1,4233 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.cloud.securitycenter_v1p1beta1.proto import ( - run_asset_discovery_response_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_run__asset__discovery__response__pb2, -) -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.securitycenter_v1p1beta1.proto import ( - asset_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_asset__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - finding_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - notification_config_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - organization_settings_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - source_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - -from google.cloud.securitycenter_v1p1beta1.proto.run_asset_discovery_response_pb2 import * - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\nHgoogle/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto\x12%google.cloud.securitycenter.v1p1beta1\x1aNgoogle/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x37google/cloud/securitycenter_v1p1beta1/proto/asset.proto\x1a\x39google/cloud/securitycenter_v1p1beta1/proto/finding.proto\x1a\x45google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto\x1aGgoogle/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto\x1a@google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto\x1a\x38google/cloud/securitycenter_v1p1beta1/proto/source.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a#google/longrunning/operations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb3\x01\n\x14\x43reateFindingRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x17\n\nfinding_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x44\n\x07\x66inding\x18\x03 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.FindingB\x03\xe0\x41\x02"\xe0\x01\n\x1f\x43reateNotificationConfigRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x16\n\tconfig_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12[\n\x13notification_config\x18\x03 \x01(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfigB\x03\xe0\x41\x02"\xa3\x01\n\x13\x43reateSourceRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x42\n\x06source\x18\x02 \x01(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.SourceB\x03\xe0\x41\x02"i\n\x1f\x44\x65leteNotificationConfigRequest\x12\x46\n\x04name\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0securitycenter.googleapis.com/NotificationConfig"f\n\x1cGetNotificationConfigRequest\x12\x46\n\x04name\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0securitycenter.googleapis.com/NotificationConfig"j\n\x1eGetOrganizationSettingsRequest\x12H\n\x04name\x18\x01 \x01(\tB:\xe0\x41\x02\xfa\x41\x34\n2securitycenter.googleapis.com/OrganizationSettings"N\n\x10GetSourceRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source"\x90\x02\n\x12GroupAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12\x33\n\x10\x63ompare_duration\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12-\n\tread_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xbf\x01\n\x13GroupAssetsResponse\x12L\n\x10group_by_results\x18\x01 \x03(\x0b\x32\x32.google.cloud.securitycenter.v1p1beta1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\x86\x02\n\x14GroupFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xc1\x01\n\x15GroupFindingsResponse\x12L\n\x10group_by_results\x18\x01 \x03(\x0b\x32\x32.google.cloud.securitycenter.v1p1beta1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\xbf\x01\n\x0bGroupResult\x12V\n\nproperties\x18\x01 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1p1beta1.GroupResult.PropertiesEntry\x12\r\n\x05\x63ount\x18\x02 \x01(\x03\x1aI\n\x0fPropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"\x91\x01\n\x1eListNotificationConfigsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x03 \x01(\x05"\x93\x01\n\x1fListNotificationConfigsResponse\x12W\n\x14notification_configs\x18\x01 \x03(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\x85\x01\n\x12ListSourcesRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x07 \x01(\x05"n\n\x13ListSourcesResponse\x12>\n\x07sources\x18\x01 \x03(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.Source\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\xba\x02\n\x11ListAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12.\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xd8\x03\n\x12ListAssetsResponse\x12g\n\x13list_assets_results\x18\x01 \x03(\x0b\x32J.google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\xfc\x01\n\x10ListAssetsResult\x12;\n\x05\x61sset\x18\x01 \x01(\x0b\x32,.google.cloud.securitycenter.v1p1beta1.Asset\x12l\n\x0cstate_change\x18\x02 \x01(\x0e\x32V.google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult.StateChange"=\n\x0bStateChange\x12\n\n\x06UNUSED\x10\x00\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x01\x12\x0b\n\x07REMOVED\x10\x02\x12\n\n\x06\x41\x43TIVE\x10\x03"\xb0\x02\n\x13ListFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12.\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xea\x05\n\x14ListFindingsResponse\x12m\n\x15list_findings_results\x18\x01 \x03(\x0b\x32N.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\x86\x04\n\x12ListFindingsResult\x12?\n\x07\x66inding\x18\x01 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.Finding\x12p\n\x0cstate_change\x18\x02 \x01(\x0e\x32Z.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.StateChange\x12n\n\x08resource\x18\x03 \x01(\x0b\x32W.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.ResourceB\x03\xe0\x41\x03\x1a~\n\x08Resource\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cproject_name\x18\x02 \x01(\t\x12\x1c\n\x14project_display_name\x18\x03 \x01(\t\x12\x13\n\x0bparent_name\x18\x04 \x01(\t\x12\x1b\n\x13parent_display_name\x18\x05 \x01(\t"M\n\x0bStateChange\x12\n\n\x06UNUSED\x10\x00\x12\x0b\n\x07\x43HANGED\x10\x01\x12\r\n\tUNCHANGED\x10\x02\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x03\x12\x0b\n\x07REMOVED\x10\x04"\xd4\x01\n\x16SetFindingStateRequest\x12;\n\x04name\x18\x01 \x01(\tB-\xe0\x41\x02\xfa\x41\'\n%securitycenter.googleapis.com/Finding\x12H\n\x05state\x18\x02 \x01(\x0e\x32\x34.google.cloud.securitycenter.v1p1beta1.Finding.StateB\x03\xe0\x41\x02\x12\x33\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x02"d\n\x18RunAssetDiscoveryRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization"\x8d\x01\n\x14UpdateFindingRequest\x12\x44\n\x07\x66inding\x18\x01 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.FindingB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xaf\x01\n\x1fUpdateNotificationConfigRequest\x12[\n\x13notification_config\x18\x01 \x01(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfigB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xb5\x01\n!UpdateOrganizationSettingsRequest\x12_\n\x15organization_settings\x18\x01 \x01(\x0b\x32;.google.cloud.securitycenter.v1p1beta1.OrganizationSettingsB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\x8a\x01\n\x13UpdateSourceRequest\x12\x42\n\x06source\x18\x01 \x01(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.SourceB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xd0\x01\n\x1aUpdateSecurityMarksRequest\x12Q\n\x0esecurity_marks\x18\x01 \x01(\x0b\x32\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarksB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12.\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\x86+\n\x0eSecurityCenter\x12\xc6\x01\n\x0c\x43reateSource\x12:.google.cloud.securitycenter.v1p1beta1.CreateSourceRequest\x1a-.google.cloud.securitycenter.v1p1beta1.Source"K\x82\xd3\xe4\x93\x02\x35"+/v1p1beta1/{parent=organizations/*}/sources:\x06source\xda\x41\rparent,source\x12\xfd\x01\n\rCreateFinding\x12;.google.cloud.securitycenter.v1p1beta1.CreateFindingRequest\x1a..google.cloud.securitycenter.v1p1beta1.Finding"\x7f\x82\xd3\xe4\x93\x02\x41"6/v1p1beta1/{parent=organizations/*/sources/*}/findings:\x07\x66inding\xda\x41\x19parent,finding_id,finding\xda\x41\x19parent,finding,finding_id\x12\xb8\x02\n\x18\x43reateNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.CreateNotificationConfigRequest\x1a\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig"\x98\x01\x82\xd3\xe4\x93\x02N"7/v1p1beta1/{parent=organizations/*}/notificationConfigs:\x13notification_config\xda\x41$parent,config_id,notification_config\xda\x41\x1aparent,notification_config\x12\xc2\x01\n\x18\x44\x65leteNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.DeleteNotificationConfigRequest\x1a\x16.google.protobuf.Empty"F\x82\xd3\xe4\x93\x02\x39*7/v1p1beta1/{name=organizations/*/notificationConfigs/*}\xda\x41\x04name\x12\x9d\x01\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"R\x82\xd3\xe4\x93\x02\x41"/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}:\x07\x66inding\xda\x41\x07\x66inding\xda\x41\x13\x66inding,update_mask\x12\xc0\x02\n\x18UpdateNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.UpdateNotificationConfigRequest\x1a\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig"\xa0\x01\x82\xd3\xe4\x93\x02\x62\x32K/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}:\x13notification_config\xda\x41\x13notification_config\xda\x41\x1fnotification_config,update_mask\x12\xa9\x02\n\x1aUpdateOrganizationSettings\x12H.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest\x1a;.google.cloud.securitycenter.v1p1beta1.OrganizationSettings"\x83\x01\x82\xd3\xe4\x93\x02\x65\x32L/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}:\x15organization_settings\xda\x41\x15organization_settings\x12\xdb\x01\n\x0cUpdateSource\x12:.google.cloud.securitycenter.v1p1beta1.UpdateSourceRequest\x1a-.google.cloud.securitycenter.v1p1beta1.Source"`\x82\xd3\xe4\x93\x02<22/v1p1beta1/{source.name=organizations/*/sources/*}:\x06source\xda\x41\x06source\xda\x41\x12source,update_mask\x12\x86\x03\n\x13UpdateSecurityMarks\x12\x41.google.cloud.securitycenter.v1p1beta1.UpdateSecurityMarksRequest\x1a\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarks"\xf5\x01\x82\xd3\xe4\x93\x02\xc0\x01\x32G/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}:\x0esecurity_marksZe2S/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}:\x0esecurity_marks\xda\x41\x0esecurity_marks\xda\x41\x1asecurity_marks,update_mask\x1aQ\xca\x41\x1dsecuritycenter.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1P\x00\x62\x06proto3', - dependencies=[ - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_run__asset__discovery__response__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_asset__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_iam__policy__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], - public_dependencies=[ - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_run__asset__discovery__response__pb2.DESCRIPTOR, - ], -) - - -_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE = _descriptor.EnumDescriptor( - name="StateChange", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult.StateChange", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNUSED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ADDED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="REMOVED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACTIVE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=4322, - serialized_end=4383, -) -_sym_db.RegisterEnumDescriptor(_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE) - -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE = _descriptor.EnumDescriptor( - name="StateChange", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.StateChange", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNUSED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHANGED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UNCHANGED", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ADDED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="REMOVED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=5362, - serialized_end=5439, -) -_sym_db.RegisterEnumDescriptor(_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE) - - -_CREATEFINDINGREQUEST = _descriptor.Descriptor( - name="CreateFindingRequest", - full_name="google.cloud.securitycenter.v1p1beta1.CreateFindingRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.CreateFindingRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$securitycenter.googleapis.com/Source", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="finding_id", - full_name="google.cloud.securitycenter.v1p1beta1.CreateFindingRequest.finding_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="finding", - full_name="google.cloud.securitycenter.v1p1beta1.CreateFindingRequest.finding", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=950, - serialized_end=1129, -) - - -_CREATENOTIFICATIONCONFIGREQUEST = _descriptor.Descriptor( - name="CreateNotificationConfigRequest", - full_name="google.cloud.securitycenter.v1p1beta1.CreateNotificationConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.CreateNotificationConfigRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="config_id", - full_name="google.cloud.securitycenter.v1p1beta1.CreateNotificationConfigRequest.config_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="notification_config", - full_name="google.cloud.securitycenter.v1p1beta1.CreateNotificationConfigRequest.notification_config", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1132, - serialized_end=1356, -) - - -_CREATESOURCEREQUEST = _descriptor.Descriptor( - name="CreateSourceRequest", - full_name="google.cloud.securitycenter.v1p1beta1.CreateSourceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.CreateSourceRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source", - full_name="google.cloud.securitycenter.v1p1beta1.CreateSourceRequest.source", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1359, - serialized_end=1522, -) - - -_DELETENOTIFICATIONCONFIGREQUEST = _descriptor.Descriptor( - name="DeleteNotificationConfigRequest", - full_name="google.cloud.securitycenter.v1p1beta1.DeleteNotificationConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.DeleteNotificationConfigRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0securitycenter.googleapis.com/NotificationConfig", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1524, - serialized_end=1629, -) - - -_GETNOTIFICATIONCONFIGREQUEST = _descriptor.Descriptor( - name="GetNotificationConfigRequest", - full_name="google.cloud.securitycenter.v1p1beta1.GetNotificationConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.GetNotificationConfigRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0securitycenter.googleapis.com/NotificationConfig", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1631, - serialized_end=1733, -) - - -_GETORGANIZATIONSETTINGSREQUEST = _descriptor.Descriptor( - name="GetOrganizationSettingsRequest", - full_name="google.cloud.securitycenter.v1p1beta1.GetOrganizationSettingsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.GetOrganizationSettingsRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A4\n2securitycenter.googleapis.com/OrganizationSettings", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1735, - serialized_end=1841, -) - - -_GETSOURCEREQUEST = _descriptor.Descriptor( - name="GetSourceRequest", - full_name="google.cloud.securitycenter.v1p1beta1.GetSourceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.GetSourceRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$securitycenter.googleapis.com/Source", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1843, - serialized_end=1921, -) - - -_GROUPASSETSREQUEST = _descriptor.Descriptor( - name="GroupAssetsRequest", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest.filter", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="group_by", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest.group_by", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compare_duration", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest.compare_duration", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest.read_time", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest.page_token", - index=5, - number=7, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest.page_size", - index=6, - number=8, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1924, - serialized_end=2196, -) - - -_GROUPASSETSRESPONSE = _descriptor.Descriptor( - name="GroupAssetsResponse", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="group_by_results", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsResponse.group_by_results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsResponse.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.securitycenter.v1p1beta1.GroupAssetsResponse.total_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2199, - serialized_end=2390, -) - - -_GROUPFINDINGSREQUEST = _descriptor.Descriptor( - name="GroupFindingsRequest", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$securitycenter.googleapis.com/Source", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest.filter", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="group_by", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest.group_by", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest.read_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compare_duration", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest.compare_duration", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest.page_token", - index=5, - number=7, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest.page_size", - index=6, - number=8, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2393, - serialized_end=2655, -) - - -_GROUPFINDINGSRESPONSE = _descriptor.Descriptor( - name="GroupFindingsResponse", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="group_by_results", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsResponse.group_by_results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsResponse.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.securitycenter.v1p1beta1.GroupFindingsResponse.total_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2658, - serialized_end=2851, -) - - -_GROUPRESULT_PROPERTIESENTRY = _descriptor.Descriptor( - name="PropertiesEntry", - full_name="google.cloud.securitycenter.v1p1beta1.GroupResult.PropertiesEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.securitycenter.v1p1beta1.GroupResult.PropertiesEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.securitycenter.v1p1beta1.GroupResult.PropertiesEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2972, - serialized_end=3045, -) - -_GROUPRESULT = _descriptor.Descriptor( - name="GroupResult", - full_name="google.cloud.securitycenter.v1p1beta1.GroupResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="properties", - full_name="google.cloud.securitycenter.v1p1beta1.GroupResult.properties", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="count", - full_name="google.cloud.securitycenter.v1p1beta1.GroupResult.count", - index=1, - number=2, - type=3, - cpp_type=2, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_GROUPRESULT_PROPERTIESENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2854, - serialized_end=3045, -) - - -_LISTNOTIFICATIONCONFIGSREQUEST = _descriptor.Descriptor( - name="ListNotificationConfigsRequest", - full_name="google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsRequest.page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsRequest.page_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3048, - serialized_end=3193, -) - - -_LISTNOTIFICATIONCONFIGSRESPONSE = _descriptor.Descriptor( - name="ListNotificationConfigsResponse", - full_name="google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="notification_configs", - full_name="google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsResponse.notification_configs", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3196, - serialized_end=3343, -) - - -_LISTSOURCESREQUEST = _descriptor.Descriptor( - name="ListSourcesRequest", - full_name="google.cloud.securitycenter.v1p1beta1.ListSourcesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.ListSourcesRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1p1beta1.ListSourcesRequest.page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1p1beta1.ListSourcesRequest.page_size", - index=2, - number=7, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3346, - serialized_end=3479, -) - - -_LISTSOURCESRESPONSE = _descriptor.Descriptor( - name="ListSourcesResponse", - full_name="google.cloud.securitycenter.v1p1beta1.ListSourcesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="sources", - full_name="google.cloud.securitycenter.v1p1beta1.ListSourcesResponse.sources", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1p1beta1.ListSourcesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3481, - serialized_end=3591, -) - - -_LISTASSETSREQUEST = _descriptor.Descriptor( - name="ListAssetsRequest", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest.filter", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="order_by", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest.order_by", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest.read_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compare_duration", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest.compare_duration", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="field_mask", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest.field_mask", - index=5, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest.page_token", - index=6, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsRequest.page_size", - index=7, - number=9, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3594, - serialized_end=3908, -) - - -_LISTASSETSRESPONSE_LISTASSETSRESULT = _descriptor.Descriptor( - name="ListAssetsResult", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="asset", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult.asset", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_change", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult.state_change", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4131, - serialized_end=4383, -) - -_LISTASSETSRESPONSE = _descriptor.Descriptor( - name="ListAssetsResponse", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="list_assets_results", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.list_assets_results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.total_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_LISTASSETSRESPONSE_LISTASSETSRESULT,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3911, - serialized_end=4383, -) - - -_LISTFINDINGSREQUEST = _descriptor.Descriptor( - name="ListFindingsRequest", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$securitycenter.googleapis.com/Source", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest.filter", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="order_by", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest.order_by", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest.read_time", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="compare_duration", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest.compare_duration", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="field_mask", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest.field_mask", - index=5, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest.page_token", - index=6, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsRequest.page_size", - index=7, - number=9, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4386, - serialized_end=4690, -) - - -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.Resource.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project_name", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.Resource.project_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project_display_name", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.Resource.project_display_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent_name", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.Resource.parent_name", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent_display_name", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.Resource.parent_display_name", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5234, - serialized_end=5360, -) - -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT = _descriptor.Descriptor( - name="ListFindingsResult", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="finding", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.finding", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state_change", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.state_change", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.resource", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE,], - enum_types=[_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4921, - serialized_end=5439, -) - -_LISTFINDINGSRESPONSE = _descriptor.Descriptor( - name="ListFindingsResponse", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="list_findings_results", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.list_findings_results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_size", - full_name="google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.total_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4693, - serialized_end=5439, -) - - -_SETFINDINGSTATEREQUEST = _descriptor.Descriptor( - name="SetFindingStateRequest", - full_name="google.cloud.securitycenter.v1p1beta1.SetFindingStateRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.SetFindingStateRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A'\n%securitycenter.googleapis.com/Finding", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.securitycenter.v1p1beta1.SetFindingStateRequest.state", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.cloud.securitycenter.v1p1beta1.SetFindingStateRequest.start_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5442, - serialized_end=5654, -) - - -_RUNASSETDISCOVERYREQUEST = _descriptor.Descriptor( - name="RunAssetDiscoveryRequest", - full_name="google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A2\n0cloudresourcemanager.googleapis.com/Organization", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5656, - serialized_end=5756, -) - - -_UPDATEFINDINGREQUEST = _descriptor.Descriptor( - name="UpdateFindingRequest", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateFindingRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="finding", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateFindingRequest.finding", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateFindingRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5759, - serialized_end=5900, -) - - -_UPDATENOTIFICATIONCONFIGREQUEST = _descriptor.Descriptor( - name="UpdateNotificationConfigRequest", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateNotificationConfigRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="notification_config", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateNotificationConfigRequest.notification_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateNotificationConfigRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5903, - serialized_end=6078, -) - - -_UPDATEORGANIZATIONSETTINGSREQUEST = _descriptor.Descriptor( - name="UpdateOrganizationSettingsRequest", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="organization_settings", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest.organization_settings", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6081, - serialized_end=6262, -) - - -_UPDATESOURCEREQUEST = _descriptor.Descriptor( - name="UpdateSourceRequest", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateSourceRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="source", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateSourceRequest.source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateSourceRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6265, - serialized_end=6403, -) - - -_UPDATESECURITYMARKSREQUEST = _descriptor.Descriptor( - name="UpdateSecurityMarksRequest", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateSecurityMarksRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="security_marks", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateSecurityMarksRequest.security_marks", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateSecurityMarksRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.cloud.securitycenter.v1p1beta1.UpdateSecurityMarksRequest.start_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6406, - serialized_end=6614, -) - -_CREATEFINDINGREQUEST.fields_by_name[ - "finding" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2._FINDING -) -_CREATENOTIFICATIONCONFIGREQUEST.fields_by_name[ - "notification_config" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG -) -_CREATESOURCEREQUEST.fields_by_name[ - "source" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2._SOURCE -) -_GROUPASSETSREQUEST.fields_by_name[ - "compare_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_GROUPASSETSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GROUPASSETSRESPONSE.fields_by_name["group_by_results"].message_type = _GROUPRESULT -_GROUPASSETSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GROUPFINDINGSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GROUPFINDINGSREQUEST.fields_by_name[ - "compare_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_GROUPFINDINGSRESPONSE.fields_by_name["group_by_results"].message_type = _GROUPRESULT -_GROUPFINDINGSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_GROUPRESULT_PROPERTIESENTRY.fields_by_name[ - "value" -].message_type = google_dot_protobuf_dot_struct__pb2._VALUE -_GROUPRESULT_PROPERTIESENTRY.containing_type = _GROUPRESULT -_GROUPRESULT.fields_by_name["properties"].message_type = _GROUPRESULT_PROPERTIESENTRY -_LISTNOTIFICATIONCONFIGSRESPONSE.fields_by_name[ - "notification_configs" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG -) -_LISTSOURCESRESPONSE.fields_by_name[ - "sources" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2._SOURCE -) -_LISTASSETSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTASSETSREQUEST.fields_by_name[ - "compare_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_LISTASSETSREQUEST.fields_by_name[ - "field_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_LISTASSETSRESPONSE_LISTASSETSRESULT.fields_by_name[ - "asset" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_asset__pb2._ASSET -) -_LISTASSETSRESPONSE_LISTASSETSRESULT.fields_by_name[ - "state_change" -].enum_type = _LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE -_LISTASSETSRESPONSE_LISTASSETSRESULT.containing_type = _LISTASSETSRESPONSE -_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE.containing_type = ( - _LISTASSETSRESPONSE_LISTASSETSRESULT -) -_LISTASSETSRESPONSE.fields_by_name[ - "list_assets_results" -].message_type = _LISTASSETSRESPONSE_LISTASSETSRESULT -_LISTASSETSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTFINDINGSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTFINDINGSREQUEST.fields_by_name[ - "compare_duration" -].message_type = google_dot_protobuf_dot_duration__pb2._DURATION -_LISTFINDINGSREQUEST.fields_by_name[ - "field_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE.containing_type = ( - _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT -) -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.fields_by_name[ - "finding" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2._FINDING -) -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.fields_by_name[ - "state_change" -].enum_type = _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.fields_by_name[ - "resource" -].message_type = _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.containing_type = _LISTFINDINGSRESPONSE -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE.containing_type = ( - _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT -) -_LISTFINDINGSRESPONSE.fields_by_name[ - "list_findings_results" -].message_type = _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT -_LISTFINDINGSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_SETFINDINGSTATEREQUEST.fields_by_name[ - "state" -].enum_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2._FINDING_STATE -) -_SETFINDINGSTATEREQUEST.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_UPDATEFINDINGREQUEST.fields_by_name[ - "finding" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2._FINDING -) -_UPDATEFINDINGREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATENOTIFICATIONCONFIGREQUEST.fields_by_name[ - "notification_config" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG -) -_UPDATENOTIFICATIONCONFIGREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATEORGANIZATIONSETTINGSREQUEST.fields_by_name[ - "organization_settings" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2._ORGANIZATIONSETTINGS -) -_UPDATEORGANIZATIONSETTINGSREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATESOURCEREQUEST.fields_by_name[ - "source" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2._SOURCE -) -_UPDATESOURCEREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATESECURITYMARKSREQUEST.fields_by_name[ - "security_marks" -].message_type = ( - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2._SECURITYMARKS -) -_UPDATESECURITYMARKSREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_UPDATESECURITYMARKSREQUEST.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -DESCRIPTOR.message_types_by_name["CreateFindingRequest"] = _CREATEFINDINGREQUEST -DESCRIPTOR.message_types_by_name[ - "CreateNotificationConfigRequest" -] = _CREATENOTIFICATIONCONFIGREQUEST -DESCRIPTOR.message_types_by_name["CreateSourceRequest"] = _CREATESOURCEREQUEST -DESCRIPTOR.message_types_by_name[ - "DeleteNotificationConfigRequest" -] = _DELETENOTIFICATIONCONFIGREQUEST -DESCRIPTOR.message_types_by_name[ - "GetNotificationConfigRequest" -] = _GETNOTIFICATIONCONFIGREQUEST -DESCRIPTOR.message_types_by_name[ - "GetOrganizationSettingsRequest" -] = _GETORGANIZATIONSETTINGSREQUEST -DESCRIPTOR.message_types_by_name["GetSourceRequest"] = _GETSOURCEREQUEST -DESCRIPTOR.message_types_by_name["GroupAssetsRequest"] = _GROUPASSETSREQUEST -DESCRIPTOR.message_types_by_name["GroupAssetsResponse"] = _GROUPASSETSRESPONSE -DESCRIPTOR.message_types_by_name["GroupFindingsRequest"] = _GROUPFINDINGSREQUEST -DESCRIPTOR.message_types_by_name["GroupFindingsResponse"] = _GROUPFINDINGSRESPONSE -DESCRIPTOR.message_types_by_name["GroupResult"] = _GROUPRESULT -DESCRIPTOR.message_types_by_name[ - "ListNotificationConfigsRequest" -] = _LISTNOTIFICATIONCONFIGSREQUEST -DESCRIPTOR.message_types_by_name[ - "ListNotificationConfigsResponse" -] = _LISTNOTIFICATIONCONFIGSRESPONSE -DESCRIPTOR.message_types_by_name["ListSourcesRequest"] = _LISTSOURCESREQUEST -DESCRIPTOR.message_types_by_name["ListSourcesResponse"] = _LISTSOURCESRESPONSE -DESCRIPTOR.message_types_by_name["ListAssetsRequest"] = _LISTASSETSREQUEST -DESCRIPTOR.message_types_by_name["ListAssetsResponse"] = _LISTASSETSRESPONSE -DESCRIPTOR.message_types_by_name["ListFindingsRequest"] = _LISTFINDINGSREQUEST -DESCRIPTOR.message_types_by_name["ListFindingsResponse"] = _LISTFINDINGSRESPONSE -DESCRIPTOR.message_types_by_name["SetFindingStateRequest"] = _SETFINDINGSTATEREQUEST -DESCRIPTOR.message_types_by_name["RunAssetDiscoveryRequest"] = _RUNASSETDISCOVERYREQUEST -DESCRIPTOR.message_types_by_name["UpdateFindingRequest"] = _UPDATEFINDINGREQUEST -DESCRIPTOR.message_types_by_name[ - "UpdateNotificationConfigRequest" -] = _UPDATENOTIFICATIONCONFIGREQUEST -DESCRIPTOR.message_types_by_name[ - "UpdateOrganizationSettingsRequest" -] = _UPDATEORGANIZATIONSETTINGSREQUEST -DESCRIPTOR.message_types_by_name["UpdateSourceRequest"] = _UPDATESOURCEREQUEST -DESCRIPTOR.message_types_by_name[ - "UpdateSecurityMarksRequest" -] = _UPDATESECURITYMARKSREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -CreateFindingRequest = _reflection.GeneratedProtocolMessageType( - "CreateFindingRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEFINDINGREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for creating a finding. - - Attributes: - parent: - Required. Resource name of the new finding’s parent. Its - format should be - “organizations/[organization_id]/sources/[source_id]”. - finding_id: - Required. Unique identifier provided by the client within the - parent scope. - finding: - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.CreateFindingRequest) - }, -) -_sym_db.RegisterMessage(CreateFindingRequest) - -CreateNotificationConfigRequest = _reflection.GeneratedProtocolMessageType( - "CreateNotificationConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATENOTIFICATIONCONFIGREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for creating a notification config. - - Attributes: - parent: - Required. Resource name of the new notification config’s - parent. Its format is “organizations/[organization_id]”. - config_id: - 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: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.CreateNotificationConfigRequest) - }, -) -_sym_db.RegisterMessage(CreateNotificationConfigRequest) - -CreateSourceRequest = _reflection.GeneratedProtocolMessageType( - "CreateSourceRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATESOURCEREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for creating a source. - - Attributes: - parent: - Required. Resource name of the new source’s parent. Its format - should be “organizations/[organization_id]”. - source: - Required. The Source being created, only the display_name and - description will be used. All other fields will be ignored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.CreateSourceRequest) - }, -) -_sym_db.RegisterMessage(CreateSourceRequest) - -DeleteNotificationConfigRequest = _reflection.GeneratedProtocolMessageType( - "DeleteNotificationConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETENOTIFICATIONCONFIGREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for deleting a notification config. - - Attributes: - name: - Required. Name of the notification config to delete. Its - format is “organizations/[organization_id]/notificationConfigs - /[config_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.DeleteNotificationConfigRequest) - }, -) -_sym_db.RegisterMessage(DeleteNotificationConfigRequest) - -GetNotificationConfigRequest = _reflection.GeneratedProtocolMessageType( - "GetNotificationConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETNOTIFICATIONCONFIGREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for getting a notification config. - - Attributes: - name: - Required. Name of the notification config to get. Its format - is “organizations/[organization_id]/notificationConfigs/[confi - g_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GetNotificationConfigRequest) - }, -) -_sym_db.RegisterMessage(GetNotificationConfigRequest) - -GetOrganizationSettingsRequest = _reflection.GeneratedProtocolMessageType( - "GetOrganizationSettingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETORGANIZATIONSETTINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for getting organization settings. - - Attributes: - name: - Required. Name of the organization to get organization - settings for. Its format is - “organizations/[organization_id]/organizationSettings”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GetOrganizationSettingsRequest) - }, -) -_sym_db.RegisterMessage(GetOrganizationSettingsRequest) - -GetSourceRequest = _reflection.GeneratedProtocolMessageType( - "GetSourceRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETSOURCEREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for getting a source. - - Attributes: - name: - Required. Relative resource name of the source. Its format is - “organizations/[organization_id]/source/[source_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GetSourceRequest) - }, -) -_sym_db.RegisterMessage(GetSourceRequest) - -GroupAssetsRequest = _reflection.GeneratedProtocolMessageType( - "GroupAssetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _GROUPASSETSREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for grouping by assets. - - Attributes: - parent: - Required. Name of the organization to groupBy. Its format is - “organizations/[organization_id]”. - filter: - 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: - 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_proper - ties.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: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GroupAssetsRequest) - }, -) -_sym_db.RegisterMessage(GroupAssetsRequest) - -GroupAssetsResponse = _reflection.GeneratedProtocolMessageType( - "GroupAssetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _GROUPASSETSRESPONSE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for grouping by assets. - - Attributes: - group_by_results: - 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: - Time used for executing the groupBy request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of results matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GroupAssetsResponse) - }, -) -_sym_db.RegisterMessage(GroupAssetsResponse) - -GroupFindingsRequest = _reflection.GeneratedProtocolMessageType( - "GroupFindingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _GROUPFINDINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for grouping by findings. - - Attributes: - parent: - 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: - 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`` - 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: - 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 - The following fields are supported when compare_duration is - set: - state_change - read_time: - 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: - 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: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GroupFindingsRequest) - }, -) -_sym_db.RegisterMessage(GroupFindingsRequest) - -GroupFindingsResponse = _reflection.GeneratedProtocolMessageType( - "GroupFindingsResponse", - (_message.Message,), - { - "DESCRIPTOR": _GROUPFINDINGSRESPONSE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for group by findings. - - Attributes: - group_by_results: - 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: - Time used for executing the groupBy request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of results matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GroupFindingsResponse) - }, -) -_sym_db.RegisterMessage(GroupFindingsResponse) - -GroupResult = _reflection.GeneratedProtocolMessageType( - "GroupResult", - (_message.Message,), - { - "PropertiesEntry": _reflection.GeneratedProtocolMessageType( - "PropertiesEntry", - (_message.Message,), - { - "DESCRIPTOR": _GROUPRESULT_PROPERTIESENTRY, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GroupResult.PropertiesEntry) - }, - ), - "DESCRIPTOR": _GROUPRESULT, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Result containing the properties and count of a groupBy request. - - Attributes: - properties: - Properties matching the groupBy fields in the request. - count: - Total count of resources for the given properties. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.GroupResult) - }, -) -_sym_db.RegisterMessage(GroupResult) -_sym_db.RegisterMessage(GroupResult.PropertiesEntry) - -ListNotificationConfigsRequest = _reflection.GeneratedProtocolMessageType( - "ListNotificationConfigsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTNOTIFICATIONCONFIGSREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing notification configs. - - Attributes: - parent: - Required. Name of the organization to list notification - configs. Its format is “organizations/[organization_id]”. - page_token: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsRequest) - }, -) -_sym_db.RegisterMessage(ListNotificationConfigsRequest) - -ListNotificationConfigsResponse = _reflection.GeneratedProtocolMessageType( - "ListNotificationConfigsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTNOTIFICATIONCONFIGSRESPONSE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing notification configs. - - Attributes: - notification_configs: - Notification configs belonging to the requested parent. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListNotificationConfigsResponse) - }, -) -_sym_db.RegisterMessage(ListNotificationConfigsResponse) - -ListSourcesRequest = _reflection.GeneratedProtocolMessageType( - "ListSourcesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTSOURCESREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing sources. - - Attributes: - parent: - Required. Resource name of the parent of sources to list. Its - format should be “organizations/[organization_id]”. - page_token: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListSourcesRequest) - }, -) -_sym_db.RegisterMessage(ListSourcesRequest) - -ListSourcesResponse = _reflection.GeneratedProtocolMessageType( - "ListSourcesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTSOURCESRESPONSE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing sources. - - Attributes: - sources: - Sources belonging to the requested parent. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListSourcesResponse) - }, -) -_sym_db.RegisterMessage(ListSourcesResponse) - -ListAssetsRequest = _reflection.GeneratedProtocolMessageType( - "ListAssetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTASSETSREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing assets. - - Attributes: - parent: - Required. Name of the organization assets should belong to. - Its format is “organizations/[organization_id]”. - filter: - 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: - 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: - 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: - 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: - A field mask to specify the ListAssetsResult fields to be - listed in the response. An empty field mask will list all - fields. - page_token: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListAssetsRequest) - }, -) -_sym_db.RegisterMessage(ListAssetsRequest) - -ListAssetsResponse = _reflection.GeneratedProtocolMessageType( - "ListAssetsResponse", - (_message.Message,), - { - "ListAssetsResult": _reflection.GeneratedProtocolMessageType( - "ListAssetsResult", - (_message.Message,), - { - "DESCRIPTOR": _LISTASSETSRESPONSE_LISTASSETSRESULT, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Result containing the Asset and its State. - - Attributes: - asset: - Asset matching the search request. - state_change: - State change of the asset between the points in time. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult) - }, - ), - "DESCRIPTOR": _LISTASSETSRESPONSE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing assets. - - Attributes: - list_assets_results: - Assets matching the list request. - read_time: - Time used for executing the list request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of assets matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListAssetsResponse) - }, -) -_sym_db.RegisterMessage(ListAssetsResponse) -_sym_db.RegisterMessage(ListAssetsResponse.ListAssetsResult) - -ListFindingsRequest = _reflection.GeneratedProtocolMessageType( - "ListFindingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTFINDINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for listing findings. - - Attributes: - parent: - 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: - 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`` 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: - 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: - 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: - 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: - A field mask to specify the Finding fields to be listed in the - response. An empty field mask will list all fields. - page_token: - 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: - The maximum number of results to return in a single response. - Default is 10, minimum is 1, maximum is 1000. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListFindingsRequest) - }, -) -_sym_db.RegisterMessage(ListFindingsRequest) - -ListFindingsResponse = _reflection.GeneratedProtocolMessageType( - "ListFindingsResponse", - (_message.Message,), - { - "ListFindingsResult": _reflection.GeneratedProtocolMessageType( - "ListFindingsResult", - (_message.Message,), - { - "Resource": _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_RESOURCE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Information related to the Google Cloud resource that is associated - with this finding. - - Attributes: - name: - The full resource name of the resource. See: https://cloud.goo - gle.com/apis/design/resource_names#full_resource_name - project_name: - The full resource name of project that the resource belongs - to. - project_display_name: - The human readable name of project that the resource belongs - to. - parent_name: - The full resource name of resource’s parent. - parent_display_name: - The human readable name of resource’s parent. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.Resource) - }, - ), - "DESCRIPTOR": _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Result containing the Finding and its StateChange. - - Attributes: - finding: - Finding matching the search request. - state_change: - State change of the finding between the points in time. - resource: - Output only. Resource that is associated with this finding. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult) - }, - ), - "DESCRIPTOR": _LISTFINDINGSRESPONSE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Response message for listing findings. - - Attributes: - list_findings_results: - Findings matching the list request. - read_time: - Time used for executing the list request. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results. - total_size: - The total number of findings matching the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.ListFindingsResponse) - }, -) -_sym_db.RegisterMessage(ListFindingsResponse) -_sym_db.RegisterMessage(ListFindingsResponse.ListFindingsResult) -_sym_db.RegisterMessage(ListFindingsResponse.ListFindingsResult.Resource) - -SetFindingStateRequest = _reflection.GeneratedProtocolMessageType( - "SetFindingStateRequest", - (_message.Message,), - { - "DESCRIPTOR": _SETFINDINGSTATEREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a finding’s state. - - Attributes: - name: - Required. The relative resource name of the finding. See: http - s://cloud.google.com/apis/design/resource_names#relative_resou - rce_name Example: “organizations/{organization_id}/sources/{so - urce_id}/finding/{finding_id}”. - state: - Required. The desired State of the finding. - start_time: - Required. The time at which the updated state takes effect. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.SetFindingStateRequest) - }, -) -_sym_db.RegisterMessage(SetFindingStateRequest) - -RunAssetDiscoveryRequest = _reflection.GeneratedProtocolMessageType( - "RunAssetDiscoveryRequest", - (_message.Message,), - { - "DESCRIPTOR": _RUNASSETDISCOVERYREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for running asset discovery for an organization. - - Attributes: - parent: - Required. Name of the organization to run asset discovery for. - Its format is “organizations/[organization_id]”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.RunAssetDiscoveryRequest) - }, -) -_sym_db.RegisterMessage(RunAssetDiscoveryRequest) - -UpdateFindingRequest = _reflection.GeneratedProtocolMessageType( - "UpdateFindingRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEFINDINGREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating or creating a finding. - - Attributes: - 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: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.UpdateFindingRequest) - }, -) -_sym_db.RegisterMessage(UpdateFindingRequest) - -UpdateNotificationConfigRequest = _reflection.GeneratedProtocolMessageType( - "UpdateNotificationConfigRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATENOTIFICATIONCONFIGREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a notification config. - - Attributes: - notification_config: - Required. The notification config to update. - update_mask: - The FieldMask to use when updating the notification config. - If empty all mutable fields will be updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.UpdateNotificationConfigRequest) - }, -) -_sym_db.RegisterMessage(UpdateNotificationConfigRequest) - -UpdateOrganizationSettingsRequest = _reflection.GeneratedProtocolMessageType( - "UpdateOrganizationSettingsRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEORGANIZATIONSETTINGSREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating an organization’s settings. - - Attributes: - organization_settings: - Required. The organization settings resource to update. - update_mask: - The FieldMask to use when updating the settings resource. If - empty all mutable fields will be updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest) - }, -) -_sym_db.RegisterMessage(UpdateOrganizationSettingsRequest) - -UpdateSourceRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSourceRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESOURCEREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a source. - - Attributes: - source: - Required. The source resource to update. - update_mask: - The FieldMask to use when updating the source resource. If - empty all mutable fields will be updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.UpdateSourceRequest) - }, -) -_sym_db.RegisterMessage(UpdateSourceRequest) - -UpdateSecurityMarksRequest = _reflection.GeneratedProtocolMessageType( - "UpdateSecurityMarksRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATESECURITYMARKSREQUEST, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.securitycenter_service_pb2", - "__doc__": """Request message for updating a SecurityMarks resource. - - Attributes: - security_marks: - Required. The security marks resource to update. - update_mask: - 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: - 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. - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.UpdateSecurityMarksRequest) - }, -) -_sym_db.RegisterMessage(UpdateSecurityMarksRequest) - - -DESCRIPTOR._options = None -_CREATEFINDINGREQUEST.fields_by_name["parent"]._options = None -_CREATEFINDINGREQUEST.fields_by_name["finding_id"]._options = None -_CREATEFINDINGREQUEST.fields_by_name["finding"]._options = None -_CREATENOTIFICATIONCONFIGREQUEST.fields_by_name["parent"]._options = None -_CREATENOTIFICATIONCONFIGREQUEST.fields_by_name["config_id"]._options = None -_CREATENOTIFICATIONCONFIGREQUEST.fields_by_name["notification_config"]._options = None -_CREATESOURCEREQUEST.fields_by_name["parent"]._options = None -_CREATESOURCEREQUEST.fields_by_name["source"]._options = None -_DELETENOTIFICATIONCONFIGREQUEST.fields_by_name["name"]._options = None -_GETNOTIFICATIONCONFIGREQUEST.fields_by_name["name"]._options = None -_GETORGANIZATIONSETTINGSREQUEST.fields_by_name["name"]._options = None -_GETSOURCEREQUEST.fields_by_name["name"]._options = None -_GROUPASSETSREQUEST.fields_by_name["parent"]._options = None -_GROUPASSETSREQUEST.fields_by_name["group_by"]._options = None -_GROUPFINDINGSREQUEST.fields_by_name["parent"]._options = None -_GROUPFINDINGSREQUEST.fields_by_name["group_by"]._options = None -_GROUPRESULT_PROPERTIESENTRY._options = None -_LISTNOTIFICATIONCONFIGSREQUEST.fields_by_name["parent"]._options = None -_LISTSOURCESREQUEST.fields_by_name["parent"]._options = None -_LISTASSETSREQUEST.fields_by_name["parent"]._options = None -_LISTFINDINGSREQUEST.fields_by_name["parent"]._options = None -_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.fields_by_name["resource"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["name"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["state"]._options = None -_SETFINDINGSTATEREQUEST.fields_by_name["start_time"]._options = None -_RUNASSETDISCOVERYREQUEST.fields_by_name["parent"]._options = None -_UPDATEFINDINGREQUEST.fields_by_name["finding"]._options = None -_UPDATENOTIFICATIONCONFIGREQUEST.fields_by_name["notification_config"]._options = None -_UPDATEORGANIZATIONSETTINGSREQUEST.fields_by_name[ - "organization_settings" -]._options = None -_UPDATESOURCEREQUEST.fields_by_name["source"]._options = None -_UPDATESECURITYMARKSREQUEST.fields_by_name["security_marks"]._options = None - -_SECURITYCENTER = _descriptor.ServiceDescriptor( - name="SecurityCenter", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\035securitycenter.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=6617, - serialized_end=12127, - methods=[ - _descriptor.MethodDescriptor( - name="CreateSource", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateSource", - index=0, - containing_service=None, - input_type=_CREATESOURCEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2._SOURCE, - serialized_options=b'\202\323\344\223\0025"+/v1p1beta1/{parent=organizations/*}/sources:\006source\332A\rparent,source', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateFinding", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateFinding", - index=1, - containing_service=None, - input_type=_CREATEFINDINGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2._FINDING, - serialized_options=b'\202\323\344\223\002A"6/v1p1beta1/{parent=organizations/*/sources/*}/findings:\007finding\332A\031parent,finding_id,finding\332A\031parent,finding,finding_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateNotificationConfig", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.CreateNotificationConfig", - index=2, - containing_service=None, - input_type=_CREATENOTIFICATIONCONFIGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG, - serialized_options=b'\202\323\344\223\002N"7/v1p1beta1/{parent=organizations/*}/notificationConfigs:\023notification_config\332A$parent,config_id,notification_config\332A\032parent,notification_config', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteNotificationConfig", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.DeleteNotificationConfig", - index=3, - containing_service=None, - input_type=_DELETENOTIFICATIONCONFIGREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\0029*7/v1p1beta1/{name=organizations/*/notificationConfigs/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetIamPolicy", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.GetIamPolicy", - index=4, - containing_service=None, - input_type=google_dot_iam_dot_v1_dot_iam__policy__pb2._GETIAMPOLICYREQUEST, - output_type=google_dot_iam_dot_v1_dot_policy__pb2._POLICY, - serialized_options=b'\202\323\344\223\002A"/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}:\007finding\332A\007finding\332A\023finding,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateNotificationConfig", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateNotificationConfig", - index=19, - containing_service=None, - input_type=_UPDATENOTIFICATIONCONFIGREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2._NOTIFICATIONCONFIG, - serialized_options=b"\202\323\344\223\002b2K/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}:\023notification_config\332A\023notification_config\332A\037notification_config,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateOrganizationSettings", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateOrganizationSettings", - index=20, - containing_service=None, - input_type=_UPDATEORGANIZATIONSETTINGSREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2._ORGANIZATIONSETTINGS, - serialized_options=b"\202\323\344\223\002e2L/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}:\025organization_settings\332A\025organization_settings", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateSource", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSource", - index=21, - containing_service=None, - input_type=_UPDATESOURCEREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2._SOURCE, - serialized_options=b"\202\323\344\223\002<22/v1p1beta1/{source.name=organizations/*/sources/*}:\006source\332A\006source\332A\022source,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateSecurityMarks", - full_name="google.cloud.securitycenter.v1p1beta1.SecurityCenter.UpdateSecurityMarks", - index=22, - containing_service=None, - input_type=_UPDATESECURITYMARKSREQUEST, - output_type=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2._SECURITYMARKS, - serialized_options=b"\202\323\344\223\002\300\0012G/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}:\016security_marksZe2S/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}:\016security_marks\332A\016security_marks\332A\032security_marks,update_mask", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_SECURITYCENTER) - -DESCRIPTOR.services_by_name["SecurityCenter"] = _SECURITYCENTER - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2_grpc.py deleted file mode 100644 index 59b91c3f..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2_grpc.py +++ /dev/null @@ -1,1088 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.securitycenter_v1p1beta1.proto import ( - finding_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - notification_config_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - organization_settings_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - securitycenter_service_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2, -) -from google.cloud.securitycenter_v1p1beta1.proto import ( - source_pb2 as google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class SecurityCenterStub(object): - """V1p1Beta1 APIs for Security Center service. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.CreateSource = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateSourceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.FromString, - ) - self.CreateFinding = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateFindingRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.FromString, - ) - self.CreateNotificationConfig = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateNotificationConfigRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - ) - self.DeleteNotificationConfig = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.DeleteNotificationConfigRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.GetIamPolicy = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.GetNotificationConfig = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetNotificationConfigRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - ) - self.GetOrganizationSettings = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetOrganizationSettingsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.FromString, - ) - self.GetSource = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetSourceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.FromString, - ) - self.GroupAssets = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsResponse.FromString, - ) - self.GroupFindings = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsResponse.FromString, - ) - self.ListAssets = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListAssetsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListAssetsResponse.FromString, - ) - self.ListFindings = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListFindingsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListFindingsResponse.FromString, - ) - self.ListNotificationConfigs = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsResponse.FromString, - ) - self.ListSources = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListSourcesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListSourcesResponse.FromString, - ) - self.RunAssetDiscovery = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.RunAssetDiscoveryRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.SetFindingState = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.SetFindingStateRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.FromString, - ) - self.SetIamPolicy = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - ) - self.TestIamPermissions = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions", - request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - ) - self.UpdateFinding = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateFindingRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.FromString, - ) - self.UpdateNotificationConfig = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateNotificationConfigRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - ) - self.UpdateOrganizationSettings = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateOrganizationSettingsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.FromString, - ) - self.UpdateSource = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateSourceRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.FromString, - ) - self.UpdateSecurityMarks = channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks", - request_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateSecurityMarksRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2.SecurityMarks.FromString, - ) - - -class SecurityCenterServicer(object): - """V1p1Beta1 APIs for Security Center service. - """ - - def CreateSource(self, request, context): - """Creates a source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateFinding(self, request, context): - """Creates a finding. The corresponding source must exist for finding - creation to succeed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateNotificationConfig(self, request, context): - """Creates a notification config. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteNotificationConfig(self, request, context): - """Deletes a notification config. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetIamPolicy(self, request, context): - """Gets the access control policy on the specified Source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetNotificationConfig(self, request, context): - """Gets a notification config. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetOrganizationSettings(self, request, context): - """Gets the settings for an organization. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetSource(self, request, context): - """Gets a source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GroupAssets(self, request, context): - """Filters an organization's assets and groups them by their specified - properties. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GroupFindings(self, request, context): - """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: /v1p1beta1/organizations/{organization_id}/sources/-/findings - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListAssets(self, request, context): - """Lists an organization's assets. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListFindings(self, request, context): - """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 - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListNotificationConfigs(self, request, context): - """Lists notification configs. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListSources(self, request, context): - """Lists all sources belonging to an organization. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def RunAssetDiscovery(self, request, context): - """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. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SetFindingState(self, request, context): - """Updates the state of a finding. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SetIamPolicy(self, request, context): - """Sets the access control policy on the specified Source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def TestIamPermissions(self, request, context): - """Returns the permissions that a caller has on the specified source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateFinding(self, request, context): - """Creates or updates a finding. The corresponding source must exist for a - finding creation to succeed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateNotificationConfig(self, request, context): - """Updates a notification config. The following update - fields are allowed: description, pubsub_topic, streaming_config.filter - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateOrganizationSettings(self, request, context): - """Updates an organization's settings. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateSource(self, request, context): - """Updates a source. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateSecurityMarks(self, request, context): - """Updates security marks. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_SecurityCenterServicer_to_server(servicer, server): - rpc_method_handlers = { - "CreateSource": grpc.unary_unary_rpc_method_handler( - servicer.CreateSource, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateSourceRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.SerializeToString, - ), - "CreateFinding": grpc.unary_unary_rpc_method_handler( - servicer.CreateFinding, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateFindingRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.SerializeToString, - ), - "CreateNotificationConfig": grpc.unary_unary_rpc_method_handler( - servicer.CreateNotificationConfig, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateNotificationConfigRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.SerializeToString, - ), - "DeleteNotificationConfig": grpc.unary_unary_rpc_method_handler( - servicer.DeleteNotificationConfig, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.DeleteNotificationConfigRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "GetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.GetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "GetNotificationConfig": grpc.unary_unary_rpc_method_handler( - servicer.GetNotificationConfig, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetNotificationConfigRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.SerializeToString, - ), - "GetOrganizationSettings": grpc.unary_unary_rpc_method_handler( - servicer.GetOrganizationSettings, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetOrganizationSettingsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.SerializeToString, - ), - "GetSource": grpc.unary_unary_rpc_method_handler( - servicer.GetSource, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetSourceRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.SerializeToString, - ), - "GroupAssets": grpc.unary_unary_rpc_method_handler( - servicer.GroupAssets, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsResponse.SerializeToString, - ), - "GroupFindings": grpc.unary_unary_rpc_method_handler( - servicer.GroupFindings, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsResponse.SerializeToString, - ), - "ListAssets": grpc.unary_unary_rpc_method_handler( - servicer.ListAssets, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListAssetsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListAssetsResponse.SerializeToString, - ), - "ListFindings": grpc.unary_unary_rpc_method_handler( - servicer.ListFindings, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListFindingsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListFindingsResponse.SerializeToString, - ), - "ListNotificationConfigs": grpc.unary_unary_rpc_method_handler( - servicer.ListNotificationConfigs, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsResponse.SerializeToString, - ), - "ListSources": grpc.unary_unary_rpc_method_handler( - servicer.ListSources, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListSourcesRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListSourcesResponse.SerializeToString, - ), - "RunAssetDiscovery": grpc.unary_unary_rpc_method_handler( - servicer.RunAssetDiscovery, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.RunAssetDiscoveryRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "SetFindingState": grpc.unary_unary_rpc_method_handler( - servicer.SetFindingState, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.SetFindingStateRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.SerializeToString, - ), - "SetIamPolicy": grpc.unary_unary_rpc_method_handler( - servicer.SetIamPolicy, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, - ), - "TestIamPermissions": grpc.unary_unary_rpc_method_handler( - servicer.TestIamPermissions, - request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, - response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, - ), - "UpdateFinding": grpc.unary_unary_rpc_method_handler( - servicer.UpdateFinding, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateFindingRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.SerializeToString, - ), - "UpdateNotificationConfig": grpc.unary_unary_rpc_method_handler( - servicer.UpdateNotificationConfig, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateNotificationConfigRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.SerializeToString, - ), - "UpdateOrganizationSettings": grpc.unary_unary_rpc_method_handler( - servicer.UpdateOrganizationSettings, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateOrganizationSettingsRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.SerializeToString, - ), - "UpdateSource": grpc.unary_unary_rpc_method_handler( - servicer.UpdateSource, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateSourceRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.SerializeToString, - ), - "UpdateSecurityMarks": grpc.unary_unary_rpc_method_handler( - servicer.UpdateSecurityMarks, - request_deserializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateSecurityMarksRequest.FromString, - response_serializer=google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2.SecurityMarks.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.securitycenter.v1p1beta1.SecurityCenter", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class SecurityCenter(object): - """V1p1Beta1 APIs for Security Center service. - """ - - @staticmethod - def CreateSource( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateSourceRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateFinding( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateFindingRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateNotificationConfig( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.CreateNotificationConfigRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteNotificationConfig( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.DeleteNotificationConfigRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetIamPolicy( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy", - google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, - google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetNotificationConfig( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetNotificationConfigRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetOrganizationSettings( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetOrganizationSettingsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetSource( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GetSourceRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GroupAssets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupAssetsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GroupFindings( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.GroupFindingsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListAssets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListAssetsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListAssetsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListFindings( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListFindingsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListFindingsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListNotificationConfigs( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListNotificationConfigsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListSources( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListSourcesRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.ListSourcesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def RunAssetDiscovery( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.RunAssetDiscoveryRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SetFindingState( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.SetFindingStateRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SetIamPolicy( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy", - google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, - google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def TestIamPermissions( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions", - google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, - google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateFinding( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateFindingRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_finding__pb2.Finding.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateNotificationConfig( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateNotificationConfigRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_notification__config__pb2.NotificationConfig.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateOrganizationSettings( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateOrganizationSettingsRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_organization__settings__pb2.OrganizationSettings.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateSource( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateSourceRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_source__pb2.Source.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateSecurityMarks( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks", - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_securitycenter__service__pb2.UpdateSecurityMarksRequest.SerializeToString, - google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_security__marks__pb2.SecurityMarks.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/source_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/source_pb2.py deleted file mode 100644 index e50bfc53..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/source_pb2.py +++ /dev/null @@ -1,152 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/securitycenter_v1p1beta1/proto/source.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/securitycenter_v1p1beta1/proto/source.proto", - package="google.cloud.securitycenter.v1p1beta1", - syntax="proto3", - serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n8google/cloud/securitycenter_v1p1beta1/proto/source.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto"\x9b\x01\n\x06Source\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t:X\xea\x41U\n$securitycenter.googleapis.com/Source\x12-organizations/{organization}/sources/{source}B\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - ], -) - - -_SOURCE = _descriptor.Descriptor( - name="Source", - full_name="google.cloud.securitycenter.v1p1beta1.Source", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.securitycenter.v1p1beta1.Source.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.securitycenter.v1p1beta1.Source.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.securitycenter.v1p1beta1.Source.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352AU\n$securitycenter.googleapis.com/Source\022-organizations/{organization}/sources/{source}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=157, - serialized_end=312, -) - -DESCRIPTOR.message_types_by_name["Source"] = _SOURCE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Source = _reflection.GeneratedProtocolMessageType( - "Source", - (_message.Message,), - { - "DESCRIPTOR": _SOURCE, - "__module__": "google.cloud.securitycenter_v1p1beta1.proto.source_pb2", - "__doc__": """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: - 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: - 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: - 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.” - """, - # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Source) - }, -) -_sym_db.RegisterMessage(Source) - - -DESCRIPTOR._options = None -_SOURCE._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1p1beta1/proto/source_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/source_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/securitycenter_v1p1beta1/proto/source_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/securitycenter_v1p1beta1/py.typed b/google/cloud/securitycenter_v1p1beta1/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/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/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/__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/google/cloud/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py similarity index 67% rename from google/cloud/__init__.py rename to google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py index 8fcc60e2..6250349b 100644 --- a/google/cloud/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py @@ -1,24 +1,24 @@ # -*- coding: utf-8 -*- -# -# Copyright 2019 Google LLC + +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import SecurityCenterClient +from .async_client import SecurityCenterAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "SecurityCenterClient", + "SecurityCenterAsyncClient", +) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py new file mode 100644 index 00000000..78f388f0 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -0,0 +1,2330 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # 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 # 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 + + 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) + + from_service_account_file = SecurityCenterClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate 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:`~.securitycenter_service.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:`~.gcs_source.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: + ~.gcs_source.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. + if request is not None and any([parent, source]): + 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:`~.securitycenter_service.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:`~.gcs_finding.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: + ~.gcs_finding.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. + if request is not None and any([parent, finding_id, finding]): + 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:`~.securitycenter_service.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:`~.gcs_notification_config.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: + ~.gcs_notification_config.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. + if request is not None and any([parent, config_id, notification_config]): + 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:`~.securitycenter_service.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. + if request is not None and any([name]): + 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.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + 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.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.notification_config.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. + if request is not None and any([name]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.organization_settings.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. + if request is not None and any([name]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.source.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. + if request is not None and any([name]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.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_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: + ~.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. + if request is not None and any([parent, group_by]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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]". + 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: + ~.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. + if request is not None and any([parent]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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]". + To list 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. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.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. + if request is not None and any([parent]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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. + if request is not None and any([parent]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.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. + if request is not None and any([parent]): + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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:`~.securitycenter_service.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: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.run_asset_discovery_response.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. + if request is not None and any([parent]): + 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.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.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:`~.securitycenter_service.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:`~.finding.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:`~.timestamp.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: + ~.finding.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. + if request is not None and any([name, state, start_time]): + 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.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + 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.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.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.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.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.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: + ~.iam_policy.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. + if request is not None and any([resource, permissions]): + 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.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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 = 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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.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:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.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:`~.field_mask.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: + ~.gcs_finding.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. + if request is not None and any([finding, update_mask]): + 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.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:`~.securitycenter_service.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`~.gcs_notification_config.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:`~.field_mask.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: + ~.gcs_notification_config.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. + if request is not None and any([notification_config, update_mask]): + 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:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.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: + ~.gcs_organization_settings.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. + if request is not None and any([organization_settings]): + 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.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:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.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:`~.field_mask.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: + ~.gcs_source.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. + if request is not None and any([source, update_mask]): + 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.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:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.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:`~.field_mask.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: + ~.gcs_security_marks.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. + if request is not None and any([security_marks, update_mask]): + 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/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py new file mode 100644 index 00000000..814ad115 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -0,0 +1,2501 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # 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 # 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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]: + """Return 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): + """Convert 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_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: + {@api.name}: 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 + + @staticmethod + def finding_path(organization: str, source: str, finding: str,) -> str: + """Return 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]: + """Parse 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: + """Return 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]: + """Parse 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: + """Return a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str, str]: + """Parse 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: + """Return 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]: + """Parse 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: + """Return 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]: + """Parse a source path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[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: + """Instantiate 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 (client_options_lib.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")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else 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": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else 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, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + 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:`~.securitycenter_service.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:`~.gcs_source.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: + ~.gcs_source.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 (:class:`~.securitycenter_service.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:`~.gcs_finding.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: + ~.gcs_finding.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 (:class:`~.securitycenter_service.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:`~.gcs_notification_config.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: + ~.gcs_notification_config.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 (:class:`~.securitycenter_service.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." + ) + + # 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.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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 (:class:`~.securitycenter_service.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: + ~.notification_config.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 (:class:`~.securitycenter_service.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: + ~.organization_settings.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 (:class:`~.securitycenter_service.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: + ~.source.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 (:class:`~.securitycenter_service.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: + ~.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: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.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_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: + ~.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 (:class:`~.securitycenter_service.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]". + 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: + ~.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 (:class:`~.securitycenter_service.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]". + To list 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. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.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 (:class:`~.securitycenter_service.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: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.run_asset_discovery_response.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.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.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:`~.securitycenter_service.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:`~.finding.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:`~.timestamp.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: + ~.finding.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.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.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: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity 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.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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.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.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.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: + ~.iam_policy.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.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + 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.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:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.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:`~.field_mask.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: + ~.gcs_finding.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.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:`~.securitycenter_service.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`~.gcs_notification_config.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:`~.field_mask.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: + ~.gcs_notification_config.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 (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.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: + ~.gcs_organization_settings.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.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:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.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:`~.field_mask.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: + ~.gcs_source.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.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:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.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:`~.field_mask.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: + ~.gcs_security_marks.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/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py new file mode 100644 index 00000000..561db76f --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py @@ -0,0 +1,804 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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 (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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:`~.securitycenter_service.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:`~.securitycenter_service.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]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.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/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..20423f2a --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py new file mode 100644 index 00000000..fb0b14ba --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -0,0 +1,573 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import 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 retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # 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() + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **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. + scope (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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + 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, + ) -> typing.Callable[ + [securitycenter_service.CreateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def create_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def create_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + typing.Union[ + gcs_notification_config.NotificationConfig, + typing.Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def delete_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.GetNotificationConfigRequest], + typing.Union[ + notification_config.NotificationConfig, + typing.Awaitable[notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + typing.Union[ + organization_settings.OrganizationSettings, + typing.Awaitable[organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def get_source( + self, + ) -> typing.Callable[ + [securitycenter_service.GetSourceRequest], + typing.Union[source.Source, typing.Awaitable[source.Source]], + ]: + raise NotImplementedError() + + @property + def group_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupAssetsRequest], + typing.Union[ + securitycenter_service.GroupAssetsResponse, + typing.Awaitable[securitycenter_service.GroupAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def group_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupFindingsRequest], + typing.Union[ + securitycenter_service.GroupFindingsResponse, + typing.Awaitable[securitycenter_service.GroupFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.ListAssetsRequest], + typing.Union[ + securitycenter_service.ListAssetsResponse, + typing.Awaitable[securitycenter_service.ListAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.ListFindingsRequest], + typing.Union[ + securitycenter_service.ListFindingsResponse, + typing.Awaitable[securitycenter_service.ListFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_notification_configs( + self, + ) -> typing.Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + typing.Union[ + securitycenter_service.ListNotificationConfigsResponse, + typing.Awaitable[securitycenter_service.ListNotificationConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_sources( + self, + ) -> typing.Callable[ + [securitycenter_service.ListSourcesRequest], + typing.Union[ + securitycenter_service.ListSourcesResponse, + typing.Awaitable[securitycenter_service.ListSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def run_asset_discovery( + self, + ) -> typing.Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def set_finding_state( + self, + ) -> typing.Callable[ + [securitycenter_service.SetFindingStateRequest], + typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def update_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + typing.Union[ + gcs_notification_config.NotificationConfig, + typing.Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + typing.Union[ + gcs_organization_settings.OrganizationSettings, + typing.Awaitable[gcs_organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def update_source( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def update_security_marks( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + typing.Union[ + gcs_security_marks.SecurityMarks, + typing.Awaitable[gcs_security_marks.SecurityMarks], + ], + ]: + raise NotImplementedError() + + +__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..b79627be --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py @@ -0,0 +1,930 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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 +from google import auth # type: ignore +from google.auth import 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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # 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: 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, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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. + 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. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "securitycenter.googleapis.com", + credentials: 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: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.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.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 "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["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.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.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.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.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.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: + /v1p1beta1/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.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.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.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.SetIamPolicyRequest], policy.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.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.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.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.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/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..f7bcf44a --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,942 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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 import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.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 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # 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: 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: + address (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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: 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, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> 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. + 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. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @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 "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["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.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.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.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.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.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: + /v1p1beta1/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.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.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.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.SetIamPolicyRequest], Awaitable[policy.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.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.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.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.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/google/cloud/securitycenter_v1p1beta1/types.py b/google/cloud/securitycenter_v1p1beta1/types.py deleted file mode 100644 index c6600d70..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types.py +++ /dev/null @@ -1,88 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.securitycenter_v1p1beta1.proto import asset_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import finding_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import notification_config_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import notification_message_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import resource_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import run_asset_discovery_response_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import options_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import duration_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import struct_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - iam_policy_pb2, - options_pb2, - policy_pb2, - operations_pb2, - any_pb2, - duration_pb2, - empty_pb2, - field_mask_pb2, - struct_pb2, - timestamp_pb2, - status_pb2, - expr_pb2, -] - -_local_modules = [ - asset_pb2, - finding_pb2, - notification_config_pb2, - notification_message_pb2, - organization_settings_pb2, - resource_pb2, - run_asset_discovery_response_pb2, - security_marks_pb2, - securitycenter_service_pb2, - source_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.securitycenter_v1p1beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/google/cloud/securitycenter_v1p1beta1/types/__init__.py new file mode 100644 index 00000000..c65c45b8 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/__init__.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .security_marks import SecurityMarks +from .asset import Asset +from .finding import Finding +from .notification_config import NotificationConfig +from .resource import Resource +from .notification_message import NotificationMessage +from .organization_settings import OrganizationSettings +from .run_asset_discovery_response import RunAssetDiscoveryResponse +from .source import Source +from .securitycenter_service import ( + 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, +) + + +__all__ = ( + "SecurityMarks", + "Asset", + "Finding", + "NotificationConfig", + "Resource", + "NotificationMessage", + "OrganizationSettings", + "RunAssetDiscoveryResponse", + "Source", + "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", +) diff --git a/google/cloud/securitycenter_v1p1beta1/types/asset.py b/google/cloud/securitycenter_v1p1beta1/types/asset.py new file mode 100644 index 00000000..9d7f0742 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/asset.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.asset.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[~.asset.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 (~.gcs_security_marks.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 (~.timestamp.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (~.timestamp.Timestamp): + The time at which the asset was last updated, + added, or deleted in Cloud SCC. + iam_policy (~.asset.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. + """ + + 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. + """ + + 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) + + 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.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + iam_policy = proto.Field(proto.MESSAGE, number=11, message=IamPolicy,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/finding.py b/google/cloud/securitycenter_v1p1beta1/types/finding.py new file mode 100644 index 00000000..1d6e12cb --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/finding.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.finding.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[~.finding.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 (~.gcs_security_marks.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 (~.timestamp.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 (~.timestamp.Timestamp): + The time at which the finding was created in + Security Command Center. + severity (~.finding.Finding.Severity): + The severity of the finding. This field is + managed by the source that writes 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.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + severity = proto.Field(proto.ENUM, number=13, enum=Severity,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/google/cloud/securitycenter_v1p1beta1/types/notification_config.py new file mode 100644 index 00000000..2be493b4 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/notification_config.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 (~.notification_config.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 (~.notification_config.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/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py new file mode 100644 index 00000000..700d68eb --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 (~.gcs_finding.Finding): + If it's a Finding based notification config, + this field will be populated. + resource (~.gcs_resource.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/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py new file mode 100644 index 00000000..70fec686 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 (~.organization_settings.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 (~.organization_settings.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/google/cloud/securitycenter_v1p1beta1/types/resource.py b/google/cloud/securitycenter_v1p1beta1/types/resource.py new file mode 100644 index 00000000..b29684ef --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/resource.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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={"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. + """ + + 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) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..9c474a45 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 as gp_duration # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", + manifest={"RunAssetDiscoveryResponse",}, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (~.gp_duration.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=gp_duration.Duration,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/google/cloud/securitycenter_v1p1beta1/types/security_marks.py new file mode 100644 index 00000000..a7671f48 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/security_marks.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 + + +__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[~.security_marks.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/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py new file mode 100644 index 00000000..bd319164 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py @@ -0,0 +1,1367 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ( + 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 as duration # type: ignore +from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # 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 (~.gcs_finding.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 (~.gcs_notification_config.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 (~.gcs_source.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]". + 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 (~.duration.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 (~.timestamp.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.Duration,) + + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.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[~.securitycenter_service.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 (~.timestamp.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.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]". 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 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 (~.timestamp.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 (~.duration.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.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.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[~.securitycenter_service.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 (~.timestamp.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.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[~.securitycenter_service.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.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[~.gcs_notification_config.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]". + 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[~.gcs_source.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 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 (~.timestamp.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 (~.duration.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 (~.gp_field_mask.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.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.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[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (~.timestamp.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 (~.gcs_asset.Asset): + Asset matching the search request. + state_change (~.securitycenter_service.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.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 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 (~.timestamp.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 (~.duration.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 (~.gp_field_mask.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.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.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[~.securitycenter_service.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (~.timestamp.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 (~.gcs_finding.Finding): + Finding matching the search request. + state_change (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (~.securitycenter_service.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. + """ + + 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) + + 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.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 (~.gcs_finding.Finding.State): + Required. The desired State of the finding. + start_time (~.timestamp.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.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 (~.gcs_finding.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 (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (~.gcs_notification_config.NotificationConfig): + Required. The notification config to update. + update_mask (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (~.gcs_organization_settings.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (~.gcs_source.Source): + Required. The source resource to update. + update_mask (~.gp_field_mask.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=gp_field_mask.FieldMask,) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (~.gcs_security_marks.SecurityMarks): + Required. The security marks resource to + update. + update_mask (~.gp_field_mask.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 (~.timestamp.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=gp_field_mask.FieldMask,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/source.py b/google/cloud/securitycenter_v1p1beta1/types/source.py new file mode 100644 index 00000000..90a4ad7d --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/source.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.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.". + """ + + 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/mypy.ini b/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/noxfile.py b/noxfile.py index 6775f51d..33b3b498 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,8 +27,8 @@ BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -70,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") @@ -139,7 +141,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=88") + session.run("coverage", "report", "--show-missing", "--fail-under=99") session.run("coverage", "erase") @@ -149,7 +151,7 @@ def docs(session): """Build the docs for this library.""" session.install("-e", ".") - session.install("sphinx<3.0.0", "alabaster", "recommonmark") + session.install("sphinx", "alabaster", "recommonmark") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/samples/snippets/snippets_findings.py b/samples/snippets/snippets_findings.py index ec465f20..a47dbacd 100644 --- a/samples/snippets/snippets_findings.py +++ b/samples/snippets/snippets_findings.py @@ -28,11 +28,13 @@ def create_source(organization_id): org_name = "organizations/{org_id}".format(org_id=organization_id) created = client.create_source( - org_name, - { - "display_name": "Customized Display Name", - "description": "A new custom source that does X", - }, + request={ + "parent": org_name, + "source": { + "display_name": "Customized Display Name", + "description": "A new custom source that does X", + }, + } ) print("Created Source: {}".format(created.name)) # [END create_source] @@ -51,7 +53,7 @@ def get_source(source_name): # source_name = "organizations/{organization_id}/sources/{source_id}" # e.g.: # source_name = "organizations/111122222444/sources/1234" - source = client.get_source(source_name) + source = client.get_source(request={"name": source_name}) print("Source: {}".format(source)) # [END get_source] @@ -76,8 +78,10 @@ def update_source(source_name): # e.g.: # source_name = "organizations/111122222444/sources/1234" updated = client.update_source( - {"name": source_name, "display_name": "Updated Display Name"}, - update_mask=field_mask, + request={ + "source": {"name": source_name, "display_name": "Updated Display Name"}, + "update_mask": field_mask, + } ) print("Updated Source: {}".format(updated)) # [END update_source] @@ -100,7 +104,7 @@ def add_user_to_source(source_name): # e.g.: # source_name = "organizations/111122222444/sources/1234" # Get the old policy so we can do an incremental update. - old_policy = client.get_iam_policy(source_name) + old_policy = client.get_iam_policy(request={"resource": source_name}) print("Old Policy: {}".format(old_policy)) # Setup a new IAM binding. @@ -112,7 +116,10 @@ def add_user_to_source(source_name): # Setting the e-tag avoids over-write existing policy updated = client.set_iam_policy( - source_name, {"etag": old_policy.etag, "bindings": [binding]} + request={ + "resource": source_name, + "policy": {"etag": old_policy.etag, "bindings": [binding]}, + } ) print("Updated Policy: {}".format(updated)) @@ -134,7 +141,7 @@ def list_source(organization_id): org_name = "organizations/{org_id}".format(org_id=organization_id) # Call the API and print out each existing source. - for i, source in enumerate(client.list_sources(org_name)): + for i, source in enumerate(client.list_sources(request={"parent": org_name})): print(i, source) # [END list_sources] return i @@ -144,15 +151,14 @@ def create_finding(source_name): """Creates a new finding.""" # [START create_finding] from google.cloud import securitycenter - from google.cloud.securitycenter_v1.proto.finding_pb2 import Finding - from google.protobuf.timestamp_pb2 import Timestamp + from google.cloud.securitycenter_v1 import CreateFindingRequest, Finding + import datetime # Create a new client. client = securitycenter.SecurityCenterClient() # Use the current time as the finding "event time". - now_proto = Timestamp() - now_proto.GetCurrentTime() + event_time = datetime.datetime.now() # source_name is the resource path for a source that has been # created previously (you can use list_sources to find a specific one). @@ -169,16 +175,21 @@ def create_finding(source_name): # if there are matches. resource_name = "//cloudresourcemanager.googleapis.com/organizations/11232" + finding = Finding( + state=Finding.State.ACTIVE, + resource_name=resource_name, + category="MEDIUM_RISK_ONE", + event_time=event_time, + ) + + request = CreateFindingRequest( + parent=source_name, + finding_id=finding_id, + finding=finding, + ) # Call The API. created_finding = client.create_finding( - source_name, - finding_id, - { - "state": Finding.ACTIVE, - "resource_name": resource_name, - "category": "MEDIUM_RISK_ONE", - "event_time": now_proto, - }, + request=request ) print(created_finding) # [END create_finding] @@ -188,9 +199,10 @@ def create_finding(source_name): def create_finding_with_source_properties(source_name): """Demonstrate creating a new finding with source properties. """ # [START create_finding_with_properties] + import datetime + from google.cloud import securitycenter - from google.cloud.securitycenter_v1.proto.finding_pb2 import Finding - from google.protobuf.timestamp_pb2 import Timestamp + from google.cloud.securitycenter_v1 import Finding from google.protobuf.struct_pb2 import Value # Create a new client. @@ -218,19 +230,22 @@ def create_finding_with_source_properties(source_name): num_value.number_value = 1234 # Use the current time as the finding "event time". - now_proto = Timestamp() - now_proto.GetCurrentTime() + event_time = datetime.datetime.now() + + finding = Finding( + state=Finding.State.ACTIVE, + resource_name=resource_name, + category="MEDIUM_RISK_ONE", + source_properties={"s_value": "string_example", "n_value": 1234}, + event_time=event_time, + ) created_finding = client.create_finding( - source_name, - finding_id, - { - "state": Finding.ACTIVE, - "resource_name": resource_name, - "category": "MEDIUM_RISK_ONE", - "source_properties": {"s_value": str_value, "n_value": num_value}, - "event_time": now_proto, - }, + request={ + "parent": source_name, + "finding_id": finding_id, + "finding": finding + } ) print(created_finding) # [END create_finding_with_properties] @@ -238,10 +253,11 @@ def create_finding_with_source_properties(source_name): def update_finding(source_name): # [START update_finding] + import datetime + from google.cloud import securitycenter - from google.protobuf.struct_pb2 import Value + from google.cloud.securitycenter_v1 import Finding from google.protobuf import field_mask_pb2 - from google.protobuf.timestamp_pb2 import Timestamp client = securitycenter.SecurityCenterClient() # Only update the specific source property and event_time. event_time @@ -249,13 +265,10 @@ def update_finding(source_name): field_mask = field_mask_pb2.FieldMask( paths=["source_properties.s_value", "event_time"] ) - value = Value() - value.string_value = "new_string" # Set the update time to Now. This must be some time greater then the # event_time on the original finding. - now_proto = Timestamp() - now_proto.GetCurrentTime() + event_time = datetime.datetime.now() # source_name is the resource path for a source that has been # created previously (you can use list_sources to find a specific one). @@ -264,18 +277,21 @@ def update_finding(source_name): # e.g.: # source_name = "organizations/111122222444/sources/1234" finding_name = "{}/findings/samplefindingid2".format(source_name) + finding = Finding( + name=finding_name, + source_properties={"s_value": "new_string"}, + event_time=event_time, + ) updated_finding = client.update_finding( - { - "name": finding_name, - "source_properties": {"s_value": value}, - "event_time": now_proto, - }, - update_mask=field_mask, + request={ + "finding": finding, + "update_mask": field_mask, + } ) print( "New Source properties: {}, Event Time {}".format( - updated_finding.source_properties, updated_finding.event_time.ToDatetime() + updated_finding.source_properties, updated_finding.event_time ) ) # [END update_finding] @@ -284,10 +300,10 @@ def update_finding(source_name): def update_finding_state(source_name): """Demonstrate updating only a finding state.""" # [START update_finding_state] - from google.cloud import securitycenter - from google.cloud.securitycenter_v1.proto.finding_pb2 import Finding - from google.protobuf.timestamp_pb2 import Timestamp + import datetime + from google.cloud import securitycenter + from google.cloud.securitycenter_v1 import Finding # Create a client. client = securitycenter.SecurityCenterClient() # source_name is the resource path for a source that has been @@ -298,14 +314,15 @@ def update_finding_state(source_name): # source_name = "organizations/111122222444/sources/1234" finding_name = "{}/findings/samplefindingid2".format(source_name) - now_proto = Timestamp() - now_proto.GetCurrentTime() - # Call the API to change the finding state to inactive as of now. new_finding = client.set_finding_state( - finding_name, Finding.INACTIVE, start_time=now_proto + request={ + "name": finding_name, + "state": Finding.State.INACTIVE, + "start_time": datetime.datetime.now(), + } ) - print("New state: {}".format(Finding.State.Name(new_finding.state))) + print(f"New state: {new_finding.state}") # [END update_finding_state] @@ -326,7 +343,10 @@ def trouble_shoot(source_name): # Check for permssions to call create_finding or update_finding. permission_response = client.test_iam_permissions( - source_name, ["securitycenter.findings.update"] + request={ + "resource": source_name, + "permissions": ["securitycenter.findings.update"], + } ) print( @@ -339,7 +359,10 @@ def trouble_shoot(source_name): # [START test_iam_permissions] # Check for permissions necessary to call set_finding_state. permission_response = client.test_iam_permissions( - source_name, ["securitycenter.findings.setState"] + request={ + "resource": source_name, + "permissions": ["securitycenter.findings.setState"], + } ) print( "Permision to update state? {}".format(len(permission_response.permissions) > 0) @@ -362,7 +385,7 @@ def list_all_findings(organization_id): # The "sources/-" suffix lists findings across all sources. You # also use a specific source_name instead. all_sources = "{org_name}/sources/-".format(org_name=org_name) - finding_result_iterator = client.list_findings(all_sources) + finding_result_iterator = client.list_findings(request={"parent": all_sources}) for i, finding_result in enumerate(finding_result_iterator): print( "{}: name: {} resource: {}".format( @@ -389,7 +412,7 @@ def list_filtered_findings(source_name): # You an also use a wild-card "-" for all sources: # source_name = "organizations/111122222444/sources/-" finding_result_iterator = client.list_findings( - source_name, filter_='category="MEDIUM_RISK_ONE"' + request={"parent": source_name, "filter": 'category="MEDIUM_RISK_ONE"'} ) # Iterate an print all finding names and the resource they are # in reference to. @@ -406,7 +429,6 @@ def list_filtered_findings(source_name): def list_findings_at_time(source_name): # [START list_findings_at_a_time] from google.cloud import securitycenter - from google.protobuf.timestamp_pb2 import Timestamp from datetime import timedelta, datetime # Create a new client. @@ -420,14 +442,14 @@ def list_findings_at_time(source_name): # source_name = "organizations/111122222444/sources/1234" # You an also use a wild-card "-" for all sources: # source_name = "organizations/111122222444/sources/-" - five_days_ago = Timestamp() - five_days_ago.FromDatetime(datetime.now() - timedelta(days=5)) + five_days_ago = str(datetime.now() - timedelta(days=5)) # [END list_findings_at_a_time] i = -1 - five_days_ago.FromDatetime(datetime(2019, 3, 5, 0, 0, 0)) # [START list_findings_at_a_time] - finding_result_iterator = client.list_findings(source_name, read_time=five_days_ago) + finding_result_iterator = client.list_findings( + request={"parent": source_name, "filter": five_days_ago} + ) for i, finding_result in enumerate(finding_result_iterator): print( "{}: name: {} resource: {}".format( @@ -452,7 +474,7 @@ def get_iam_policy(source_name): # e.g.: # source_name = "organizations/111122222444/sources/1234" # Get the old policy so we can do an incremental update. - policy = client.get_iam_policy(source_name) + policy = client.get_iam_policy(request={"resource": source_name}) print("Policy: {}".format(policy)) # [END get_source_iam] @@ -472,7 +494,9 @@ def group_all_findings(organization_id): # The "sources/-" suffix lists findings across all sources. You # also use a specific source_name instead. all_sources = "{org_name}/sources/-".format(org_name=org_name) - group_result_iterator = client.group_findings(all_sources, group_by="category") + group_result_iterator = client.group_findings( + request={"parent": all_sources, "group_by": "category"} + ) for i, group_result in enumerate(group_result_iterator): print((i + 1), group_result) # [END group_all_findings] @@ -496,7 +520,11 @@ def group_filtered_findings(source_name): # source_name = "organizations/111122222444/sources/1234" group_result_iterator = client.group_findings( - source_name, group_by="category", filter_='state="ACTIVE"' + request={ + "parent": source_name, + "group_by": "category", + "filter": 'state="ACTIVE"', + } ) for i, group_result in enumerate(group_result_iterator): print((i + 1), group_result) @@ -511,7 +539,6 @@ def group_findings_at_time(source_name): # [START group_findings_at_time] from datetime import datetime, timedelta from google.cloud import securitycenter - from google.protobuf.timestamp_pb2 import Timestamp # Create a client. client = securitycenter.SecurityCenterClient() @@ -525,11 +552,13 @@ def group_findings_at_time(source_name): # Group findings as of yesterday. read_time = datetime.utcnow() - timedelta(days=1) - timestamp_proto = Timestamp() - timestamp_proto.FromDatetime(read_time) group_result_iterator = client.group_findings( - source_name, group_by="category", read_time=timestamp_proto + request={ + "parent": source_name, + "group_by": "category", + "read_time": read_time, + } ) for i, group_result in enumerate(group_result_iterator): print((i + 1), group_result) @@ -545,7 +574,6 @@ def group_findings_and_changes(source_name): from datetime import timedelta from google.cloud import securitycenter - from google.protobuf.duration_pb2 import Duration # Create a client. client = securitycenter.SecurityCenterClient() @@ -559,12 +587,13 @@ def group_findings_and_changes(source_name): # List assets and their state change the last 30 days compare_delta = timedelta(days=30) - # Convert the timedelta to a Duration - duration_proto = Duration() - duration_proto.FromTimedelta(compare_delta) group_result_iterator = client.group_findings( - source_name, group_by="state_change", compare_duration=duration_proto + request={ + "parent": source_name, + "group_by": "state_change", + "compare_duration": compare_delta, + } ) for i, group_result in enumerate(group_result_iterator): print((i + 1), group_result) diff --git a/samples/snippets/snippets_findings_test.py b/samples/snippets/snippets_findings_test.py index 8ac01d8c..8a68117a 100644 --- a/samples/snippets/snippets_findings_test.py +++ b/samples/snippets/snippets_findings_test.py @@ -35,11 +35,13 @@ def source_name(organization_id): org_name = "organizations/{org_id}".format(org_id=organization_id) source = client.create_source( - org_name, - { - "display_name": "Unit test source", - "description": "A new custom source that does X", - }, + request={ + "parent": org_name, + "source": { + "display_name": "Unit test source", + "description": "A new custom source that does X", + }, + } ) return source.name diff --git a/samples/snippets/snippets_list_assets.py b/samples/snippets/snippets_list_assets.py index f8863802..7eb85932 100644 --- a/samples/snippets/snippets_list_assets.py +++ b/samples/snippets/snippets_list_assets.py @@ -29,7 +29,7 @@ def list_all_assets(organization_id): org_name = "organizations/{org_id}".format(org_id=organization_id) # Call the API and print results. - asset_iterator = client.list_assets(org_name) + asset_iterator = client.list_assets(request={"parent": org_name}) for i, asset_result in enumerate(asset_iterator): print(i, asset_result) # [END demo_list_all_assets] @@ -53,7 +53,9 @@ def list_assets_with_filters(organization_id): + '"google.cloud.resourcemanager.Project"' ) # Call the API and print results. - asset_iterator = client.list_assets(org_name, filter_=project_filter) + asset_iterator = client.list_assets( + request={"parent": org_name, "filter": project_filter} + ) for i, asset_result in enumerate(asset_iterator): print(i, asset_result) # [END demo_list_assets_with_filter] @@ -66,8 +68,6 @@ def list_assets_with_filters_and_read_time(organization_id): # [START demo_list_assets_with_filter_and_time] from datetime import datetime, timedelta - from google.protobuf.timestamp_pb2 import Timestamp - from google.cloud import securitycenter client = securitycenter.SecurityCenterClient() @@ -83,12 +83,14 @@ def list_assets_with_filters_and_read_time(organization_id): # Lists assets as of yesterday. read_time = datetime.utcnow() - timedelta(days=1) - timestamp_proto = Timestamp() - timestamp_proto.FromDatetime(read_time) # Call the API and print results. asset_iterator = client.list_assets( - org_name, filter_=project_filter, read_time=timestamp_proto + request={ + "parent": org_name, + "filter": project_filter, + "read_time": read_time, + } ) for i, asset_result in enumerate(asset_iterator): print(i, asset_result) @@ -102,7 +104,6 @@ def list_point_in_time_changes(organization_id): # [START demo_list_assets_changes] from datetime import timedelta - from google.protobuf.duration_pb2 import Duration from google.cloud import securitycenter client = securitycenter.SecurityCenterClient() @@ -117,12 +118,14 @@ def list_point_in_time_changes(organization_id): # List assets and their state change the last 30 days compare_delta = timedelta(days=30) - # Convert the timedelta to a Duration - duration_proto = Duration() - duration_proto.FromTimedelta(compare_delta) + # Call the API and print results. asset_iterator = client.list_assets( - org_name, filter_=project_filter, compare_duration=duration_proto + request={ + "parent": org_name, + "filter": project_filter, + "compare_duration": compare_delta, + } ) for i, asset in enumerate(asset_iterator): print(i, asset) @@ -145,7 +148,9 @@ def group_assets(organization_id): group_by_type = "security_center_properties.resource_type" - result_iterator = client.group_assets(org_name, group_by=group_by_type) + result_iterator = client.group_assets( + request={"parent": org_name, "group_by": group_by_type} + ) for i, result in enumerate(result_iterator): print((i + 1), result) # [END group_all_assets] @@ -170,7 +175,7 @@ def group_filtered_assets(organization_id): + '"google.cloud.resourcemanager.Project"' ) result_iterator = client.group_assets( - org_name, group_by=group_by_type, filter_=only_projects + request={"parent": org_name, "group_by": group_by_type, "filter": only_projects} ) for i, result in enumerate(result_iterator): print((i + 1), result) @@ -186,18 +191,20 @@ def group_assets_by_changes(organization_id): from datetime import timedelta from google.cloud import securitycenter - from google.protobuf.duration_pb2 import Duration client = securitycenter.SecurityCenterClient() - duration_proto = Duration() - duration_proto.FromTimedelta(timedelta(days=5)) + duration = timedelta(days=5) # organization_id is the numeric ID of the organization. # organization_id = "1234567777" org_name = "organizations/{org_id}".format(org_id=organization_id) result_iterator = client.group_assets( - org_name, group_by="state_change", compare_duration=duration_proto + request={ + "parent": org_name, + "group_by": "state_change", + "compare_duration": duration, + } ) for i, result in enumerate(result_iterator): print((i + 1), result) diff --git a/samples/snippets/snippets_notification_configs.py b/samples/snippets/snippets_notification_configs.py index f0a4a6df..cadbd8e0 100644 --- a/samples/snippets/snippets_notification_configs.py +++ b/samples/snippets/snippets_notification_configs.py @@ -31,13 +31,15 @@ def create_notification_config(organization_id, notification_config_id, pubsub_t org_name = "organizations/{org_id}".format(org_id=organization_id) created_notification_config = client.create_notification_config( - org_name, - notification_config_id, - { - "description": "Notification for active findings", - "pubsub_topic": pubsub_topic, - "streaming_config": {"filter": 'state = "ACTIVE"'}, - }, + request={ + "parent": org_name, + "config_id": notification_config_id, + "notification_config": { + "description": "Notification for active findings", + "pubsub_topic": pubsub_topic, + "streaming_config": {"filter": 'state = "ACTIVE"'}, + }, + } ) print(created_notification_config) @@ -59,7 +61,7 @@ def delete_notification_config(organization_id, notification_config_id): org_id=organization_id, config_id=notification_config_id ) - client.delete_notification_config(notification_config_name) + client.delete_notification_config(request={"name": notification_config_name}) print("Deleted notification config: {}".format(notification_config_name)) # [END scc_delete_notification_config] return True @@ -79,7 +81,9 @@ def get_notification_config(organization_id, notification_config_id): org_id=organization_id, config_id=notification_config_id ) - notification_config = client.get_notification_config(notification_config_name) + notification_config = client.get_notification_config( + request={"name": notification_config_name} + ) print("Got notification config: {}".format(notification_config)) # [END scc_get_notification_config] return notification_config @@ -95,7 +99,9 @@ def list_notification_configs(organization_id): # TODO: organization_id = "your-org-id" org_name = "organizations/{org_id}".format(org_id=organization_id) - notification_configs_iterator = client.list_notification_configs(org_name) + notification_configs_iterator = client.list_notification_configs( + request={"parent": org_name} + ) for i, config in enumerate(notification_configs_iterator): print("{}: notification_config: {}".format(i, config)) # [END scc_list_notification_configs] @@ -128,13 +134,15 @@ def update_notification_config(organization_id, notification_config_id, pubsub_t ) updated_notification_config = client.update_notification_config( - { - "name": notification_config_name, - "description": updated_description, - "pubsub_topic": pubsub_topic, - "streaming_config": {"filter": updated_filter}, - }, - update_mask=field_mask, + request={ + "notification_config": { + "name": notification_config_name, + "description": updated_description, + "pubsub_topic": pubsub_topic, + "streaming_config": {"filter": updated_filter}, + }, + "update_mask": field_mask, + } ) print(updated_notification_config) diff --git a/samples/snippets/snippets_notification_receiver.py b/samples/snippets/snippets_notification_receiver.py index aad6ba79..9fb9f8e4 100644 --- a/samples/snippets/snippets_notification_receiver.py +++ b/samples/snippets/snippets_notification_receiver.py @@ -22,10 +22,7 @@ def receive_notifications(project_id, subscription_name): import concurrent from google.cloud import pubsub_v1 - from google.cloud.securitycenter_v1.proto.notification_message_pb2 import ( - NotificationMessage, - ) - from google.protobuf import json_format + from google.cloud.securitycenter_v1 import NotificationMessage # TODO: project_id = "your-project-id" # TODO: subscription_name = "your-subscription-name" @@ -33,8 +30,7 @@ def receive_notifications(project_id, subscription_name): def callback(message): print("Received message") - notification_msg = NotificationMessage() - json_format.Parse(message.data, notification_msg) + notification_msg = NotificationMessage.from_json(message.data) print( "Notification config name: {}".format( diff --git a/samples/snippets/snippets_notification_test.py b/samples/snippets/snippets_notification_test.py index 73ad0060..fc129ab6 100644 --- a/samples/snippets/snippets_notification_test.py +++ b/samples/snippets/snippets_notification_test.py @@ -41,7 +41,7 @@ def cleanup_notification_config(notification_config_id): notification_config_name = "organizations/{org_id}/notificationConfigs/{config_id}".format( org_id=ORG_ID, config_id=notification_config_id ) - client.delete_notification_config(notification_config_name) + client.delete_notification_config(request={"name": notification_config_name}) @pytest.fixture @@ -51,13 +51,15 @@ def new_notification_config_for_update(): org_name = "organizations/{org_id}".format(org_id=ORG_ID) created_notification_config = client.create_notification_config( - org_name, - UPDATE_CONFIG_ID, - { - "description": "Notification for active findings", - "pubsub_topic": PUBSUB_TOPIC, - "streaming_config": {"filter": ""}, - }, + request={ + "parent": org_name, + "config_id": UPDATE_CONFIG_ID, + "notification_config": { + "description": "Notification for active findings", + "pubsub_topic": PUBSUB_TOPIC, + "streaming_config": {"filter": ""}, + }, + } ) yield created_notification_config cleanup_notification_config(UPDATE_CONFIG_ID) @@ -70,13 +72,15 @@ def new_notification_config_for_get(): org_name = "organizations/{org_id}".format(org_id=ORG_ID) created_notification_config = client.create_notification_config( - org_name, - GET_CONFIG_ID, - { - "description": "Notification for active findings", - "pubsub_topic": PUBSUB_TOPIC, - "streaming_config": {"filter": ""}, - }, + request={ + "parent": org_name, + "config_id": GET_CONFIG_ID, + "notification_config": { + "description": "Notification for active findings", + "pubsub_topic": PUBSUB_TOPIC, + "streaming_config": {"filter": ""}, + }, + } ) yield created_notification_config cleanup_notification_config(GET_CONFIG_ID) @@ -89,13 +93,15 @@ def deleted_notification_config(): org_name = "organizations/{org_id}".format(org_id=ORG_ID) created_notification_config = client.create_notification_config( - org_name, - DELETE_CONFIG_ID, - { - "description": "Notification for active findings", - "pubsub_topic": PUBSUB_TOPIC, - "streaming_config": {"filter": ""}, - }, + request={ + "parent": org_name, + "config_id": DELETE_CONFIG_ID, + "notification_config": { + "description": "Notification for active findings", + "pubsub_topic": PUBSUB_TOPIC, + "streaming_config": {"filter": ""}, + }, + } ) return created_notification_config @@ -110,10 +116,8 @@ def test_create_notification_config(): def test_delete_notification_config(deleted_notification_config): - assert ( - snippets_notification_configs.delete_notification_config( - ORG_ID, DELETE_CONFIG_ID - ) + assert snippets_notification_configs.delete_notification_config( + ORG_ID, DELETE_CONFIG_ID ) @@ -137,8 +141,6 @@ def test_update_notification_config(new_notification_config_for_update): def test_receive_notifications(): - assert ( - snippets_notification_receiver.receive_notifications( - PROJECT_ID, PUBSUB_SUBSCRIPTION - ) + assert snippets_notification_receiver.receive_notifications( + PROJECT_ID, PUBSUB_SUBSCRIPTION ) diff --git a/samples/snippets/snippets_orgs.py b/samples/snippets/snippets_orgs.py index 6b95e49e..05717345 100644 --- a/samples/snippets/snippets_orgs.py +++ b/samples/snippets/snippets_orgs.py @@ -27,7 +27,7 @@ def get_settings(organization_id): org_settings_name = client.organization_settings_path(organization_id) - org_settings = client.get_organization_settings(org_settings_name) + org_settings = client.get_organization_settings(request={"name": org_settings_name}) print(org_settings) # [END get_org_settings] @@ -50,8 +50,13 @@ def update_asset_discovery_org_settings(organization_id): field_mask = field_mask_pb2.FieldMask(paths=["enable_asset_discovery"]) # Call the service. updated = client.update_organization_settings( - {"name": org_settings_name, "enable_asset_discovery": True}, - update_mask=field_mask, + request={ + "organization_settings": { + "name": org_settings_name, + "enable_asset_discovery": True, + }, + "update_mask": field_mask, + } ) print("Asset Discovery Enabled? {}".format(updated.enable_asset_discovery)) # [END update_org_settings] diff --git a/samples/snippets/snippets_security_marks.py b/samples/snippets/snippets_security_marks.py index 88532341..96491a07 100644 --- a/samples/snippets/snippets_security_marks.py +++ b/samples/snippets/snippets_security_marks.py @@ -37,10 +37,10 @@ def add_to_asset(asset_name): marks = {"key_a": "value_a", "key_b": "value_b"} updated_marks = client.update_security_marks( - {"name": marks_name, "marks": marks}, - # If this field was left empty, all marks would be cleared before adding - # the new values. - update_mask=field_mask, + request={ + "security_marks": {"name": marks_name, "marks": marks}, + "update_mask": field_mask, + } ) print(updated_marks) # [END add_marks_to_asset] @@ -67,13 +67,14 @@ def clear_from_asset(asset_name): field_mask = field_mask_pb2.FieldMask(paths=["marks.key_a", "marks.key_b"]) updated_marks = client.update_security_marks( - { - "name": marks_name - # Note, no marks specified, so the specified values in - # the fields masks will be deleted. - }, - # If this field was left empty, all marks would be cleared. - update_mask=field_mask, + request={ + "security_marks": { + "name": marks_name + # Note, no marks specified, so the specified values in + # the fields masks will be deleted. + }, + "update_mask": field_mask, + } ) print(updated_marks) # [END clear_marks_asset] @@ -99,7 +100,10 @@ def delete_and_update_marks(asset_name): marks = {"key_a": "new_value_for_a"} updated_marks = client.update_security_marks( - {"name": marks_name, "marks": marks}, update_mask=field_mask + request={ + "security_marks": {"name": marks_name, "marks": marks}, + "update_mask": field_mask, + } ) print(updated_marks) # [END delete_and_update_marks] @@ -128,7 +132,10 @@ def add_to_finding(finding_name): marks = {"finding_key_a": "value_a", "finding_key_b": "value_b"} updated_marks = client.update_security_marks( - {"name": finding_marks_name, "marks": marks}, update_mask=field_mask + request={ + "security_marks": {"name": finding_marks_name, "marks": marks}, + "update_mask": field_mask, + } ) # [END add_marks_to_finding] return updated_marks, marks @@ -149,10 +156,14 @@ def list_assets_with_query_marks(organization_id, asset_name): marks_filter = 'security_marks.marks.key_a = "value_a"' # Call the API and print results. - asset_iterator = client.list_assets(org_name, filter_=marks_filter) + asset_iterator = client.list_assets( + request={"parent": org_name, "filter": marks_filter} + ) # Call the API and print results. - asset_iterator = client.list_assets(org_name, filter_=marks_filter) + asset_iterator = client.list_assets( + request={"parent": org_name, "filter": marks_filter} + ) for i, asset_result in enumerate(asset_iterator): print(i, asset_result) # [END demo_list_assets_with_security_marks] @@ -178,7 +189,9 @@ def list_findings_with_query_marks(source_name, finding_name): marks_filter = 'NOT security_marks.marks.finding_key_a="value_a"' # Call the API and print results. - finding_iterator = client.list_findings(source_name, filter_=marks_filter) + finding_iterator = client.list_findings( + request={"parent": source_name, "filter": marks_filter} + ) for i, finding_result in enumerate(finding_iterator): print(i, finding_result) # [END demo_list_findings_with_security_marks] diff --git a/samples/snippets/snippets_security_marks_test.py b/samples/snippets/snippets_security_marks_test.py index 18950f86..10182416 100644 --- a/samples/snippets/snippets_security_marks_test.py +++ b/samples/snippets/snippets_security_marks_test.py @@ -37,13 +37,18 @@ def asset_name(organization_id): # organization_id is the numeric ID of the organization. # organization_id=1234567777 org_name = "organizations/{org_id}".format(org_id=organization_id) - assets = list(client.list_assets(org_name)) + assets = list(client.list_assets(request={"parent": org_name})) # Select a random asset to avoid collision between integration tests. asset = (random.sample(assets, 1)[0]).asset.name # Set fresh marks. update = client.update_security_marks( - {"name": "{}/securityMarks".format(asset), "marks": {"other": "other_val"}} + request={ + "security_marks": { + "name": "{}/securityMarks".format(asset), + "marks": {"other": "other_val"}, + } + } ) assert update.marks == {"other": "other_val"} return asset @@ -57,11 +62,13 @@ def source_name(organization_id): client = securitycenter.SecurityCenterClient() org_name = "organizations/{org_id}".format(org_id=organization_id) source = client.create_source( - org_name, - { - "display_name": "Security marks Unit test source", - "description": "A new custom source that does X", - }, + request={ + "parent": org_name, + "source": { + "display_name": "Security marks Unit test source", + "description": "A new custom source that does X", + }, + } ) return source.name @@ -70,7 +77,7 @@ def source_name(organization_id): def finding_name(source_name): """Creates a new finding and returns it name.""" from google.cloud import securitycenter - from google.cloud.securitycenter_v1.proto.finding_pb2 import Finding + from google.cloud.securitycenter_v1 import Finding from google.protobuf.timestamp_pb2 import Timestamp client = securitycenter.SecurityCenterClient() @@ -79,24 +86,28 @@ def finding_name(source_name): now_proto.GetCurrentTime() finding = client.create_finding( - source_name, - "scfinding", - { - "state": Finding.ACTIVE, - "category": "C1", - "event_time": now_proto, - "resource_name": "//cloudresourcemanager.googleapis.com/organizations/1234", - }, + request={ + "parent": source_name, + "finding_id": "scfinding", + "finding": { + "state": Finding.State.ACTIVE, + "category": "C1", + "event_time": now_proto, + "resource_name": "//cloudresourcemanager.googleapis.com/organizations/1234", + }, + } ) client.create_finding( - source_name, - "untouched", - { - "state": Finding.ACTIVE, - "category": "MEDIUM_RISK_ONE", - "event_time": now_proto, - "resource_name": "//cloudresourcemanager.googleapis.com/organizations/1234", - }, + request={ + "parent": source_name, + "finding_id": "untouched", + "finding": { + "state": Finding.State.ACTIVE, + "category": "MEDIUM_RISK_ONE", + "event_time": now_proto, + "resource_name": "//cloudresourcemanager.googleapis.com/organizations/1234", + }, + } ) return finding.name diff --git a/scripts/fixup_securitycenter_v1_keywords.py b/scripts/fixup_securitycenter_v1_keywords.py new file mode 100644 index 00000000..70abd28b --- /dev/null +++ b/scripts/fixup_securitycenter_v1_keywords.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/scripts/fixup_securitycenter_v1beta1_keywords.py b/scripts/fixup_securitycenter_v1beta1_keywords.py new file mode 100644 index 00000000..e7f3f9f4 --- /dev/null +++ b/scripts/fixup_securitycenter_v1beta1_keywords.py @@ -0,0 +1,195 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/scripts/fixup_securitycenter_v1p1beta1_keywords.py b/scripts/fixup_securitycenter_v1p1beta1_keywords.py new file mode 100644 index 00000000..70abd28b --- /dev/null +++ b/scripts/fixup_securitycenter_v1p1beta1_keywords.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/setup.py b/setup.py index 0237b90a..77b5c75a 100644 --- a/setup.py +++ b/setup.py @@ -20,13 +20,14 @@ import setuptools name = "google-cloud-securitycenter" -description = "Cloud Security Command Center API API client library" +description = "Cloud Security Command Center API client library" version = "0.7.1" release_status = "Development Status :: 3 - Alpha" dependencies = [ - "google-api-core[grpc] >= 1.14.0, < 2.0.0dev", + "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", - 'enum34; python_version < "3.4"', + "proto-plus >= 1.10.0", + "libcst >= 0.2.5", ] package_root = os.path.abspath(os.path.dirname(__file__)) @@ -36,7 +37,9 @@ readme = readme_file.read() packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] namespaces = ["google"] @@ -57,12 +60,10 @@ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -70,7 +71,12 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", + scripts=[ + "scripts/fixup_securitycenter_v1_keywords.py", + "scripts/fixup_securitycenter_v1beta1_keywords.py", + "scripts/fixup_securitycenter_v1p1beta1_keywords.py", + ], include_package_data=True, zip_safe=False, ) diff --git a/synth.py b/synth.py index 576b74a6..d3514f3b 100644 --- a/synth.py +++ b/synth.py @@ -29,32 +29,44 @@ service="securitycenter", version=version, bazel_target=f"//google/cloud/securitycenter/{version}:securitycenter-{version}-py", - include_protos=True + include_protos=True, ) - s.move(library / f"google/cloud/securitycenter_{version}") - s.move(library / f"tests/unit/gapic/{version}") - s.move(library / f"docs/gapic/{version}") + s.move(library, excludes=["README.rst", "docs/index.rst", "setup.py"]) -# Use the highest version library to generate import alias. -s.move(library / "google/cloud/securitycenter.py") -# Fix bad line wrapping in docstring -s.replace("google/**/security_marks_pb2.py", -"""“organizations/\{organization_id\}/assets/\{asset_ -\s+id\}/securityMarks” “organizations/\{organization_id\}/sources/\{s -\s+ource_id\}/findings/\{finding_id\}/securityMarks”\.""", -"""``organizations/{organization_id}/assets/{asset_id}/securityMarks`` - ``organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks``.""") +# TODO(busunkim): Remove once https://github.com/googleapis/gapic-generator-python/pull/555 is merged +s.replace( + "google/**/base.py", + """from google\.api_core import gapic_v1\s+# type: ignore""", + """from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore""", +) + +# fix bad indentation +s.replace( + "google/**/*service.py", + """(\s+)settings resource. +\s+If empty all mutable fields will be updated.""", + """\g<1>settings resource. +\g<1>If empty all mutable fields will be updated.""", +) + +# fix bulleted lists +s.replace("google/**/*client.py", "\- state_change", "- state_change\n") +s.replace("google/**/*client.py", "\- parent", "- parent\n") # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=88, samples=True) -s.move(templated_files) - -python.py_samples(root="samples", skip_readmes=True) +templated_files = common.py_library( + samples=True, + microgenerator=True, # set to True only if there are samples + cov_level=99, +) +s.move( + templated_files, excludes=[".coveragerc"] +) # microgenerator has a good .coveragerc file -# TODO(busunkim): Use latest sphinx after microgenerator transition -s.replace("noxfile.py", """['"]sphinx['"]""", '"sphinx<3.0.0"') +python.py_samples(skip_readmes=True) s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/tests/unit/gapic/securitycenter_v1/__init__.py b/tests/unit/gapic/securitycenter_v1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/securitycenter_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/securitycenter_v1/test_security_center.py b/tests/unit/gapic/securitycenter_v1/test_security_center.py new file mode 100644 index 00000000..2cca9372 --- /dev/null +++ b/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -0,0 +1,6675 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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 +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.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 as iam_policy # type: ignore +from google.iam.v1 import options_pb2 as options # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +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_file(client_class): + creds = 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 + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "securitycenter.googleapis.com:443" + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + assert transport == transports.SecurityCenterGrpcTransport + + 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=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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_source( + transport: str = "grpc", request_type=securitycenter_service.CreateSourceRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.CreateSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.CreateFindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.CreateNotificationConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.DeleteNotificationConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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.GetIamPolicyRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.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) + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SecurityCenterClient(credentials=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.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient(credentials=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.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=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.GetIamPolicyRequest(), resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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=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.GetIamPolicyRequest(), resource="resource_value", + ) + + +def test_get_notification_config( + transport: str = "grpc", + request_type=securitycenter_service.GetNotificationConfigRequest, +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GetNotificationConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GetOrganizationSettingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GetSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GroupAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_group_assets_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GroupFindingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_group_findings_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_list_assets_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListFindingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_list_findings_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListNotificationConfigsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListSourcesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_sources_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.RunAssetDiscoveryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.SetFindingStateRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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.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.Timestamp( + seconds=751 + ) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient(credentials=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.Timestamp(seconds=751), + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.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.Timestamp( + seconds=751 + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient(credentials=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.Timestamp(seconds=751), + ) + + +def test_set_iam_policy( + transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.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) + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SecurityCenterClient(credentials=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.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient(credentials=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.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=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.SetIamPolicyRequest(), resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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=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.SetIamPolicyRequest(), resource="resource_value", + ) + + +def test_test_iam_permissions( + transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SecurityCenterClient(credentials=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.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=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.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=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.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.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=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.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_update_finding( + transport: str = "grpc", request_type=securitycenter_service.UpdateFindingRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateFindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateNotificationConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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.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.FieldMask(paths=["paths_value"]) + + +def test_update_notification_config_flattened_error(): + client = SecurityCenterClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.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.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +def test_update_organization_settings( + transport: str = "grpc", + request_type=securitycenter_service.UpdateOrganizationSettingsRequest, +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateSecurityMarksRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=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=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=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=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=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(auth, "default") as adc: + adc.return_value = (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=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(exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=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=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 + + +def test_security_center_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) 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 = (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(auth, "default") 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 = (credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_security_center_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.SecurityCenterGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_security_center_host_no_port(): + client = SecurityCenterClient( + credentials=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=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.insecure_channel("http://localhost/") + + # 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" + + +def test_security_center_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # 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" + + +@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", autospec=True + ) 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 = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(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=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@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", autospec=True + ) 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=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_security_center_grpc_lro_client(): + client = SecurityCenterClient( + credentials=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=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._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_finding_path(): + organization = "squid" + source = "clam" + finding = "whelk" + + 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": "octopus", + "source": "oyster", + "finding": "nudibranch", + } + 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 = "squid" + notification_config = "clam" + + 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": "whelk", + "notification_config": "octopus", + } + 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 = "squid" + + expected = "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "clam", + } + 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 = "squid" + source = "clam" + + 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": "whelk", + "source": "octopus", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_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=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=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/securitycenter_v1beta1/__init__.py b/tests/unit/gapic/securitycenter_v1beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/securitycenter_v1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py new file mode 100644 index 00000000..0f9c8bc0 --- /dev/null +++ b/tests/unit/gapic/securitycenter_v1beta1/test_security_center.py @@ -0,0 +1,5287 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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 +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.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 as iam_policy # type: ignore +from google.iam.v1 import options_pb2 as options # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +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_file(client_class): + creds = 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 + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "securitycenter.googleapis.com:443" + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + assert transport == transports.SecurityCenterGrpcTransport + + 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=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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_source( + transport: str = "grpc", request_type=securitycenter_service.CreateSourceRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.CreateSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.CreateFindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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.GetIamPolicyRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.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) + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SecurityCenterClient(credentials=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.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient(credentials=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.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=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.GetIamPolicyRequest(), resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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=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.GetIamPolicyRequest(), resource="resource_value", + ) + + +def test_get_organization_settings( + transport: str = "grpc", + request_type=securitycenter_service.GetOrganizationSettingsRequest, +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GetOrganizationSettingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GetSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GroupAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupAssetsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_group_assets_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GroupFindingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GroupFindingsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_group_findings_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_list_assets_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListFindingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_list_findings_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListSourcesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_sources_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.RunAssetDiscoveryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.SetFindingStateRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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.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.Timestamp( + seconds=751 + ) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient(credentials=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.Timestamp(seconds=751), + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.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.Timestamp( + seconds=751 + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient(credentials=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.Timestamp(seconds=751), + ) + + +def test_set_iam_policy( + transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.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) + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SecurityCenterClient(credentials=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.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient(credentials=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.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=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.SetIamPolicyRequest(), resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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=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.SetIamPolicyRequest(), resource="resource_value", + ) + + +def test_test_iam_permissions( + transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SecurityCenterClient(credentials=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.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=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.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=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.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.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=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.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_update_finding( + transport: str = "grpc", request_type=securitycenter_service.UpdateFindingRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateFindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateSecurityMarksRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=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=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=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=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=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(auth, "default") as adc: + adc.return_value = (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=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(exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=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=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 + + +def test_security_center_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) 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 = (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(auth, "default") 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 = (credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_security_center_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.SecurityCenterGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_security_center_host_no_port(): + client = SecurityCenterClient( + credentials=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=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.insecure_channel("http://localhost/") + + # 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" + + +def test_security_center_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # 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" + + +@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", autospec=True + ) 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 = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(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=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@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", autospec=True + ) 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=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_security_center_grpc_lro_client(): + client = SecurityCenterClient( + credentials=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=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._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_finding_path(): + organization = "squid" + source = "clam" + finding = "whelk" + + 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": "octopus", + "source": "oyster", + "finding": "nudibranch", + } + 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 = "squid" + + expected = "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "clam", + } + 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 = "squid" + source = "clam" + + 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": "whelk", + "source": "octopus", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_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=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=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py b/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/securitycenter_v1p1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py new file mode 100644 index 00000000..674123ab --- /dev/null +++ b/tests/unit/gapic/securitycenter_v1p1beta1/test_security_center.py @@ -0,0 +1,6897 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import 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 +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.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 as iam_policy # type: ignore +from google.iam.v1 import options_pb2 as options # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +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_file(client_class): + creds = 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 + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "securitycenter.googleapis.com:443" + + +def test_security_center_client_get_transport_class(): + transport = SecurityCenterClient.get_transport_class() + assert transport == transports.SecurityCenterGrpcTransport + + 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=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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # 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.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +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, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_source( + transport: str = "grpc", request_type=securitycenter_service.CreateSourceRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_create_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.CreateSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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, + ) + + 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 + + +def test_create_finding_from_dict(): + test_create_finding(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_finding_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.CreateFindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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, + ) + ) + + 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] == request + + # 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 + + +def test_create_finding_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_create_notification_config_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.CreateNotificationConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_delete_notification_config_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.DeleteNotificationConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_notification_config_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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.GetIamPolicyRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.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) + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SecurityCenterClient(credentials=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.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = SecurityCenterClient(credentials=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.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=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.GetIamPolicyRequest(), resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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=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.GetIamPolicyRequest(), resource="resource_value", + ) + + +def test_get_notification_config( + transport: str = "grpc", + request_type=securitycenter_service.GetNotificationConfigRequest, +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_get_notification_config_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GetNotificationConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_get_organization_settings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GetOrganizationSettingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_get_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GetSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_group_assets_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GroupAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_group_assets_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_group_findings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.GroupFindingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_group_findings_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_list_assets_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_findings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListFindingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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 + + +def test_list_findings_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_notification_configs_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListNotificationConfigsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNotificationConfigsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_notification_configs_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_list_sources_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.ListSourcesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSourcesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_sources_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=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=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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_run_asset_discovery_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.RunAssetDiscoveryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_asset_discovery_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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, + ) + + 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 + + +def test_set_finding_state_from_dict(): + test_set_finding_state(request_type=dict) + + +@pytest.mark.asyncio +async def test_set_finding_state_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.SetFindingStateRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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, + ) + ) + + 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] == request + + # 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 + + +def test_set_finding_state_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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.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.Timestamp( + seconds=751 + ) + + +def test_set_finding_state_flattened_error(): + client = SecurityCenterClient(credentials=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.Timestamp(seconds=751), + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.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.Timestamp( + seconds=751 + ) + + +@pytest.mark.asyncio +async def test_set_finding_state_flattened_error_async(): + client = SecurityCenterAsyncClient(credentials=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.Timestamp(seconds=751), + ) + + +def test_set_iam_policy( + transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.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) + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SecurityCenterClient(credentials=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.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SecurityCenterClient(credentials=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.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=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.SetIamPolicyRequest(), resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.set_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.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=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.SetIamPolicyRequest(), resource="resource_value", + ) + + +def test_test_iam_permissions( + transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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.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.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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.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.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=credentials.AnonymousCredentials(),) + + # Any value 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.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SecurityCenterClient(credentials=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.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=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.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=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.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy.TestIamPermissionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.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=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.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_update_finding( + transport: str = "grpc", request_type=securitycenter_service.UpdateFindingRequest +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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, + ) + + 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 + + +def test_update_finding_from_dict(): + test_update_finding(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_finding_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateFindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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, + ) + ) + + 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] == request + + # 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 + + +def test_update_finding_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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.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.FieldMask(paths=["paths_value"]) + + +def test_update_finding_flattened_error(): + client = SecurityCenterClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_finding_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.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.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_finding_flattened_error_async(): + client = SecurityCenterAsyncClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +def test_update_notification_config( + transport: str = "grpc", + request_type=securitycenter_service.UpdateNotificationConfigRequest, +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_notification_config_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateNotificationConfigRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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.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.FieldMask(paths=["paths_value"]) + + +def test_update_notification_config_flattened_error(): + client = SecurityCenterClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.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.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_notification_config_flattened_error_async(): + client = SecurityCenterAsyncClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +def test_update_organization_settings( + transport: str = "grpc", + request_type=securitycenter_service.UpdateOrganizationSettingsRequest, +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_organization_settings_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateOrganizationSettingsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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=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=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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=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=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_source_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateSourceRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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.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.FieldMask(paths=["paths_value"]) + + +def test_update_source_flattened_error(): + client = SecurityCenterClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_source_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.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.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_source_flattened_error_async(): + client = SecurityCenterAsyncClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +def test_update_security_marks( + transport: str = "grpc", + request_type=securitycenter_service.UpdateSecurityMarksRequest, +): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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) + + +@pytest.mark.asyncio +async def test_update_security_marks_async(transport: str = "grpc_asyncio"): + client = SecurityCenterAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = securitycenter_service.UpdateSecurityMarksRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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] == request + + # 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_field_headers(): + client = SecurityCenterClient(credentials=credentials.AnonymousCredentials(),) + + # Any value 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=credentials.AnonymousCredentials(),) + + # Any value 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._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=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.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.FieldMask(paths=["paths_value"]) + + +def test_update_security_marks_flattened_error(): + client = SecurityCenterClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_async(): + client = SecurityCenterAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._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.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.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_security_marks_flattened_error_async(): + client = SecurityCenterAsyncClient(credentials=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.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SecurityCenterClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SecurityCenterGrpcTransport( + credentials=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=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=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=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SecurityCenterGrpcAsyncIOTransport( + credentials=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(auth, "default") as adc: + adc.return_value = (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=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(exceptions.DuplicateCredentialArgs): + transport = transports.SecurityCenterTransport( + credentials=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=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 + + +def test_security_center_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) 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 = (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(auth, "default") 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 = (credentials.AnonymousCredentials(), None) + transport = transports.SecurityCenterTransport() + adc.assert_called_once() + + +def test_security_center_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + SecurityCenterClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_security_center_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.SecurityCenterGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_security_center_host_no_port(): + client = SecurityCenterClient( + credentials=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=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.insecure_channel("http://localhost/") + + # 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" + + +def test_security_center_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # 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" + + +@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", autospec=True + ) 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 = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(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=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@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", autospec=True + ) 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=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_security_center_grpc_lro_client(): + client = SecurityCenterClient( + credentials=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=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._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_finding_path(): + organization = "squid" + source = "clam" + finding = "whelk" + + 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": "octopus", + "source": "oyster", + "finding": "nudibranch", + } + 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 = "squid" + notification_config = "clam" + + 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": "whelk", + "notification_config": "octopus", + } + 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 = "squid" + + expected = "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + actual = SecurityCenterClient.organization_settings_path(organization) + assert expected == actual + + +def test_parse_organization_settings_path(): + expected = { + "organization": "clam", + } + 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 = "squid" + source = "clam" + + 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": "whelk", + "source": "octopus", + } + path = SecurityCenterClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = SecurityCenterClient.parse_source_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=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=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/v1/test_security_center_client_v1.py b/tests/unit/gapic/v1/test_security_center_client_v1.py deleted file mode 100644 index 96cf1bd2..00000000 --- a/tests/unit/gapic/v1/test_security_center_client_v1.py +++ /dev/null @@ -1,1180 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import securitycenter_v1 -from google.cloud.securitycenter_v1 import enums -from google.cloud.securitycenter_v1.proto import finding_pb2 -from google.cloud.securitycenter_v1.proto import notification_config_pb2 -from google.cloud.securitycenter_v1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1.proto import run_asset_discovery_response_pb2 -from google.cloud.securitycenter_v1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import timestamp_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestSecurityCenterClient(object): - def test_create_source(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - source = {} - - response = client.create_source(parent, source) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - source = {} - - with pytest.raises(CustomException): - client.create_source(parent, source) - - def test_create_finding(self): - # Setup Expected Response - name = "name3373707" - parent_2 = "parent21175163357" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name, - "parent": parent_2, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - finding_id = "findingId728776081" - finding = {} - - response = client.create_finding(parent, finding_id, finding) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_finding_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - finding_id = "findingId728776081" - finding = {} - - with pytest.raises(CustomException): - client.create_finding(parent, finding_id, finding) - - def test_create_notification_config(self): - # Setup Expected Response - name = "name3373707" - description = "description-1724546052" - pubsub_topic = "pubsubTopic-338126829" - service_account = "serviceAccount-1948028253" - expected_response = { - "name": name, - "description": description, - "pubsub_topic": pubsub_topic, - "service_account": service_account, - } - expected_response = notification_config_pb2.NotificationConfig( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - config_id = "configId-804450504" - notification_config = {} - - response = client.create_notification_config( - parent, config_id, notification_config - ) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.CreateNotificationConfigRequest( - parent=parent, config_id=config_id, notification_config=notification_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_notification_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - config_id = "configId-804450504" - notification_config = {} - - with pytest.raises(CustomException): - client.create_notification_config(parent, config_id, notification_config) - - def test_delete_notification_config(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - name = client.notification_config_path( - "[ORGANIZATION]", "[NOTIFICATION_CONFIG]" - ) - - client.delete_notification_config(name) - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.DeleteNotificationConfigRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_notification_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - name = client.notification_config_path( - "[ORGANIZATION]", "[NOTIFICATION_CONFIG]" - ) - - with pytest.raises(CustomException): - client.delete_notification_config(name) - - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - - def test_get_notification_config(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - pubsub_topic = "pubsubTopic-338126829" - service_account = "serviceAccount-1948028253" - expected_response = { - "name": name_2, - "description": description, - "pubsub_topic": pubsub_topic, - "service_account": service_account, - } - expected_response = notification_config_pb2.NotificationConfig( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - name = client.notification_config_path( - "[ORGANIZATION]", "[NOTIFICATION_CONFIG]" - ) - - response = client.get_notification_config(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GetNotificationConfigRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_notification_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - name = client.notification_config_path( - "[ORGANIZATION]", "[NOTIFICATION_CONFIG]" - ) - - with pytest.raises(CustomException): - client.get_notification_config(name) - - def test_get_organization_settings(self): - # Setup Expected Response - name_2 = "name2-1052831874" - enable_asset_discovery = False - expected_response = { - "name": name_2, - "enable_asset_discovery": enable_asset_discovery, - } - expected_response = organization_settings_pb2.OrganizationSettings( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - name = client.organization_settings_path("[ORGANIZATION]") - - response = client.get_organization_settings(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GetOrganizationSettingsRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_organization_settings_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - name = client.organization_settings_path("[ORGANIZATION]") - - with pytest.raises(CustomException): - client.get_organization_settings(name) - - def test_get_source(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name_2, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - name = client.source_path("[ORGANIZATION]", "[SOURCE]") - - response = client.get_source(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GetSourceRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - name = client.source_path("[ORGANIZATION]", "[SOURCE]") - - with pytest.raises(CustomException): - client.get_source(name) - - def test_group_assets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_group_findings(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_assets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - list_assets_results_element = {} - list_assets_results = [list_assets_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "list_assets_results": list_assets_results, - } - expected_response = securitycenter_service_pb2.ListAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_assets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.list_assets_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListAssetsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_assets(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_findings(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - list_findings_results_element = {} - list_findings_results = [list_findings_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "list_findings_results": list_findings_results, - } - expected_response = securitycenter_service_pb2.ListFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - - paged_list_response = client.list_findings(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.list_findings_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListFindingsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - - paged_list_response = client.list_findings(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_notification_configs(self): - # Setup Expected Response - next_page_token = "" - notification_configs_element = {} - notification_configs = [notification_configs_element] - expected_response = { - "next_page_token": next_page_token, - "notification_configs": notification_configs, - } - expected_response = securitycenter_service_pb2.ListNotificationConfigsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_notification_configs(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.notification_configs[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListNotificationConfigsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_notification_configs_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_notification_configs(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_sources(self): - # Setup Expected Response - next_page_token = "" - sources_element = {} - sources = [sources_element] - expected_response = {"next_page_token": next_page_token, "sources": sources} - expected_response = securitycenter_service_pb2.ListSourcesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_sources(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.sources[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListSourcesRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_sources_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_sources(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_run_asset_discovery(self): - # Setup Expected Response - expected_response = {} - expected_response = run_asset_discovery_response_pb2.RunAssetDiscoveryResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_run_asset_discovery", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - response = client.run_asset_discovery(parent) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.RunAssetDiscoveryRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_run_asset_discovery_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_run_asset_discovery_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - response = client.run_asset_discovery(parent) - exception = response.exception() - assert exception.errors[0] == error - - def test_set_finding_state(self): - # Setup Expected Response - name_2 = "name2-1052831874" - parent = "parent-995424086" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name_2, - "parent": parent, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - name = client.finding_path("[ORGANIZATION]", "[SOURCE]", "[FINDING]") - state = enums.Finding.State.STATE_UNSPECIFIED - start_time = {} - - response = client.set_finding_state(name, state, start_time) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.SetFindingStateRequest( - name=name, state=state, start_time=start_time - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_finding_state_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - name = client.finding_path("[ORGANIZATION]", "[SOURCE]", "[FINDING]") - state = enums.Finding.State.STATE_UNSPECIFIED - start_time = {} - - with pytest.raises(CustomException): - client.set_finding_state(name, state, start_time) - - def test_set_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - policy = {} - - response = client.set_iam_policy(resource, policy) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.SetIamPolicyRequest( - resource=resource, policy=policy - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - policy = {} - - with pytest.raises(CustomException): - client.set_iam_policy(resource, policy) - - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions) - - def test_update_finding(self): - # Setup Expected Response - name = "name3373707" - parent = "parent-995424086" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name, - "parent": parent, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - finding = {} - - response = client.update_finding(finding) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateFindingRequest( - finding=finding - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_finding_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - finding = {} - - with pytest.raises(CustomException): - client.update_finding(finding) - - def test_update_notification_config(self): - # Setup Expected Response - name = "name3373707" - description = "description-1724546052" - pubsub_topic = "pubsubTopic-338126829" - service_account = "serviceAccount-1948028253" - expected_response = { - "name": name, - "description": description, - "pubsub_topic": pubsub_topic, - "service_account": service_account, - } - expected_response = notification_config_pb2.NotificationConfig( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - notification_config = {} - - response = client.update_notification_config(notification_config) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateNotificationConfigRequest( - notification_config=notification_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_notification_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - notification_config = {} - - with pytest.raises(CustomException): - client.update_notification_config(notification_config) - - def test_update_organization_settings(self): - # Setup Expected Response - name = "name3373707" - enable_asset_discovery = False - expected_response = { - "name": name, - "enable_asset_discovery": enable_asset_discovery, - } - expected_response = organization_settings_pb2.OrganizationSettings( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - organization_settings = {} - - response = client.update_organization_settings(organization_settings) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateOrganizationSettingsRequest( - organization_settings=organization_settings - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_organization_settings_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - organization_settings = {} - - with pytest.raises(CustomException): - client.update_organization_settings(organization_settings) - - def test_update_source(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - source = {} - - response = client.update_source(source) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateSourceRequest(source=source) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - source = {} - - with pytest.raises(CustomException): - client.update_source(source) - - def test_update_security_marks(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = security_marks_pb2.SecurityMarks(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - security_marks = {} - - response = client.update_security_marks(security_marks) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateSecurityMarksRequest( - security_marks=security_marks - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_security_marks_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - security_marks = {} - - with pytest.raises(CustomException): - client.update_security_marks(security_marks) diff --git a/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py b/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py deleted file mode 100644 index 3cc4f388..00000000 --- a/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py +++ /dev/null @@ -1,925 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import securitycenter_v1beta1 -from google.cloud.securitycenter_v1beta1 import enums -from google.cloud.securitycenter_v1beta1.proto import finding_pb2 -from google.cloud.securitycenter_v1beta1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1beta1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1beta1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1beta1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import timestamp_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestSecurityCenterClient(object): - def test_create_source(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - source = {} - - response = client.create_source(parent, source) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - source = {} - - with pytest.raises(CustomException): - client.create_source(parent, source) - - def test_create_finding(self): - # Setup Expected Response - name = "name3373707" - parent_2 = "parent21175163357" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name, - "parent": parent_2, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - finding_id = "findingId728776081" - finding = {} - - response = client.create_finding(parent, finding_id, finding) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_finding_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - finding_id = "findingId728776081" - finding = {} - - with pytest.raises(CustomException): - client.create_finding(parent, finding_id, finding) - - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - - def test_get_organization_settings(self): - # Setup Expected Response - name_2 = "name2-1052831874" - enable_asset_discovery = False - expected_response = { - "name": name_2, - "enable_asset_discovery": enable_asset_discovery, - } - expected_response = organization_settings_pb2.OrganizationSettings( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - name = client.organization_settings_path("[ORGANIZATION]") - - response = client.get_organization_settings(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GetOrganizationSettingsRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_organization_settings_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - name = client.organization_settings_path("[ORGANIZATION]") - - with pytest.raises(CustomException): - client.get_organization_settings(name) - - def test_get_source(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name_2, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - name = client.source_path("[ORGANIZATION]", "[SOURCE]") - - response = client.get_source(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GetSourceRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - name = client.source_path("[ORGANIZATION]", "[SOURCE]") - - with pytest.raises(CustomException): - client.get_source(name) - - def test_group_assets(self): - # Setup Expected Response - next_page_token = "" - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_group_findings(self): - # Setup Expected Response - next_page_token = "" - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_assets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - list_assets_results_element = {} - list_assets_results = [list_assets_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "list_assets_results": list_assets_results, - } - expected_response = securitycenter_service_pb2.ListAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_assets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.list_assets_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListAssetsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_assets(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_findings(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - findings_element = {} - findings = [findings_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "findings": findings, - } - expected_response = securitycenter_service_pb2.ListFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - - paged_list_response = client.list_findings(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.findings[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListFindingsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - - paged_list_response = client.list_findings(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_sources(self): - # Setup Expected Response - next_page_token = "" - sources_element = {} - sources = [sources_element] - expected_response = {"next_page_token": next_page_token, "sources": sources} - expected_response = securitycenter_service_pb2.ListSourcesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_sources(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.sources[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListSourcesRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_sources_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_sources(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_run_asset_discovery(self): - # Setup Expected Response - expected_response = {} - expected_response = empty_pb2.Empty(**expected_response) - operation = operations_pb2.Operation( - name="operations/test_run_asset_discovery", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - response = client.run_asset_discovery(parent) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.RunAssetDiscoveryRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_run_asset_discovery_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_run_asset_discovery_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - response = client.run_asset_discovery(parent) - exception = response.exception() - assert exception.errors[0] == error - - def test_set_finding_state(self): - # Setup Expected Response - name_2 = "name2-1052831874" - parent = "parent-995424086" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name_2, - "parent": parent, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - name = client.finding_path("[ORGANIZATION]", "[SOURCE]", "[FINDING]") - state = enums.Finding.State.STATE_UNSPECIFIED - start_time = {} - - response = client.set_finding_state(name, state, start_time) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.SetFindingStateRequest( - name=name, state=state, start_time=start_time - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_finding_state_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - name = client.finding_path("[ORGANIZATION]", "[SOURCE]", "[FINDING]") - state = enums.Finding.State.STATE_UNSPECIFIED - start_time = {} - - with pytest.raises(CustomException): - client.set_finding_state(name, state, start_time) - - def test_set_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - policy = {} - - response = client.set_iam_policy(resource, policy) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.SetIamPolicyRequest( - resource=resource, policy=policy - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - policy = {} - - with pytest.raises(CustomException): - client.set_iam_policy(resource, policy) - - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions) - - def test_update_finding(self): - # Setup Expected Response - name = "name3373707" - parent = "parent-995424086" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name, - "parent": parent, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - finding = {} - - response = client.update_finding(finding) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateFindingRequest( - finding=finding - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_finding_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - finding = {} - - with pytest.raises(CustomException): - client.update_finding(finding) - - def test_update_organization_settings(self): - # Setup Expected Response - name = "name3373707" - enable_asset_discovery = False - expected_response = { - "name": name, - "enable_asset_discovery": enable_asset_discovery, - } - expected_response = organization_settings_pb2.OrganizationSettings( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - organization_settings = {} - - response = client.update_organization_settings(organization_settings) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateOrganizationSettingsRequest( - organization_settings=organization_settings - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_organization_settings_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - organization_settings = {} - - with pytest.raises(CustomException): - client.update_organization_settings(organization_settings) - - def test_update_source(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - source = {} - - response = client.update_source(source) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateSourceRequest(source=source) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - source = {} - - with pytest.raises(CustomException): - client.update_source(source) - - def test_update_security_marks(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = security_marks_pb2.SecurityMarks(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup Request - security_marks = {} - - response = client.update_security_marks(security_marks) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateSecurityMarksRequest( - security_marks=security_marks - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_security_marks_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1beta1.SecurityCenterClient() - - # Setup request - security_marks = {} - - with pytest.raises(CustomException): - client.update_security_marks(security_marks) diff --git a/tests/unit/gapic/v1p1beta1/test_security_center_client_v1p1beta1.py b/tests/unit/gapic/v1p1beta1/test_security_center_client_v1p1beta1.py deleted file mode 100644 index 616284bb..00000000 --- a/tests/unit/gapic/v1p1beta1/test_security_center_client_v1p1beta1.py +++ /dev/null @@ -1,1180 +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 -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import securitycenter_v1p1beta1 -from google.cloud.securitycenter_v1p1beta1 import enums -from google.cloud.securitycenter_v1p1beta1.proto import finding_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import notification_config_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import organization_settings_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import run_asset_discovery_response_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import security_marks_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import securitycenter_service_pb2 -from google.cloud.securitycenter_v1p1beta1.proto import source_pb2 -from google.iam.v1 import iam_policy_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import timestamp_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestSecurityCenterClient(object): - def test_create_source(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - source = {} - - response = client.create_source(parent, source) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - source = {} - - with pytest.raises(CustomException): - client.create_source(parent, source) - - def test_create_finding(self): - # Setup Expected Response - name = "name3373707" - parent_2 = "parent21175163357" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name, - "parent": parent_2, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - finding_id = "findingId728776081" - finding = {} - - response = client.create_finding(parent, finding_id, finding) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_finding_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - finding_id = "findingId728776081" - finding = {} - - with pytest.raises(CustomException): - client.create_finding(parent, finding_id, finding) - - def test_create_notification_config(self): - # Setup Expected Response - name = "name3373707" - description = "description-1724546052" - pubsub_topic = "pubsubTopic-338126829" - service_account = "serviceAccount-1948028253" - expected_response = { - "name": name, - "description": description, - "pubsub_topic": pubsub_topic, - "service_account": service_account, - } - expected_response = notification_config_pb2.NotificationConfig( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - config_id = "configId-804450504" - notification_config = {} - - response = client.create_notification_config( - parent, config_id, notification_config - ) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.CreateNotificationConfigRequest( - parent=parent, config_id=config_id, notification_config=notification_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_notification_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - config_id = "configId-804450504" - notification_config = {} - - with pytest.raises(CustomException): - client.create_notification_config(parent, config_id, notification_config) - - def test_delete_notification_config(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - name = client.notification_config_path( - "[ORGANIZATION]", "[NOTIFICATION_CONFIG]" - ) - - client.delete_notification_config(name) - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.DeleteNotificationConfigRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_notification_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - name = client.notification_config_path( - "[ORGANIZATION]", "[NOTIFICATION_CONFIG]" - ) - - with pytest.raises(CustomException): - client.delete_notification_config(name) - - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - - def test_get_notification_config(self): - # Setup Expected Response - name_2 = "name2-1052831874" - description = "description-1724546052" - pubsub_topic = "pubsubTopic-338126829" - service_account = "serviceAccount-1948028253" - expected_response = { - "name": name_2, - "description": description, - "pubsub_topic": pubsub_topic, - "service_account": service_account, - } - expected_response = notification_config_pb2.NotificationConfig( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - name = client.notification_config_path( - "[ORGANIZATION]", "[NOTIFICATION_CONFIG]" - ) - - response = client.get_notification_config(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GetNotificationConfigRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_notification_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - name = client.notification_config_path( - "[ORGANIZATION]", "[NOTIFICATION_CONFIG]" - ) - - with pytest.raises(CustomException): - client.get_notification_config(name) - - def test_get_organization_settings(self): - # Setup Expected Response - name_2 = "name2-1052831874" - enable_asset_discovery = False - expected_response = { - "name": name_2, - "enable_asset_discovery": enable_asset_discovery, - } - expected_response = organization_settings_pb2.OrganizationSettings( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - name = client.organization_settings_path("[ORGANIZATION]") - - response = client.get_organization_settings(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GetOrganizationSettingsRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_organization_settings_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - name = client.organization_settings_path("[ORGANIZATION]") - - with pytest.raises(CustomException): - client.get_organization_settings(name) - - def test_get_source(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name_2, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - name = client.source_path("[ORGANIZATION]", "[SOURCE]") - - response = client.get_source(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GetSourceRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - name = client.source_path("[ORGANIZATION]", "[SOURCE]") - - with pytest.raises(CustomException): - client.get_source(name) - - def test_group_assets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_group_findings(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_assets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - list_assets_results_element = {} - list_assets_results = [list_assets_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "list_assets_results": list_assets_results, - } - expected_response = securitycenter_service_pb2.ListAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_assets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.list_assets_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListAssetsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_assets(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_findings(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - list_findings_results_element = {} - list_findings_results = [list_findings_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "list_findings_results": list_findings_results, - } - expected_response = securitycenter_service_pb2.ListFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - - paged_list_response = client.list_findings(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.list_findings_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListFindingsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - - paged_list_response = client.list_findings(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_notification_configs(self): - # Setup Expected Response - next_page_token = "" - notification_configs_element = {} - notification_configs = [notification_configs_element] - expected_response = { - "next_page_token": next_page_token, - "notification_configs": notification_configs, - } - expected_response = securitycenter_service_pb2.ListNotificationConfigsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_notification_configs(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.notification_configs[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListNotificationConfigsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_notification_configs_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_notification_configs(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_list_sources(self): - # Setup Expected Response - next_page_token = "" - sources_element = {} - sources = [sources_element] - expected_response = {"next_page_token": next_page_token, "sources": sources} - expected_response = securitycenter_service_pb2.ListSourcesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_sources(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.sources[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.ListSourcesRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_sources_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - - paged_list_response = client.list_sources(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_run_asset_discovery(self): - # Setup Expected Response - expected_response = {} - expected_response = run_asset_discovery_response_pb2.RunAssetDiscoveryResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_run_asset_discovery", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - response = client.run_asset_discovery(parent) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.RunAssetDiscoveryRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_run_asset_discovery_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_run_asset_discovery_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - - response = client.run_asset_discovery(parent) - exception = response.exception() - assert exception.errors[0] == error - - def test_set_finding_state(self): - # Setup Expected Response - name_2 = "name2-1052831874" - parent = "parent-995424086" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name_2, - "parent": parent, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - name = client.finding_path("[ORGANIZATION]", "[SOURCE]", "[FINDING]") - state = enums.Finding.State.STATE_UNSPECIFIED - start_time = {} - - response = client.set_finding_state(name, state, start_time) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.SetFindingStateRequest( - name=name, state=state, start_time=start_time - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_finding_state_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - name = client.finding_path("[ORGANIZATION]", "[SOURCE]", "[FINDING]") - state = enums.Finding.State.STATE_UNSPECIFIED - start_time = {} - - with pytest.raises(CustomException): - client.set_finding_state(name, state, start_time) - - def test_set_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - policy = {} - - response = client.set_iam_policy(resource, policy) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.SetIamPolicyRequest( - resource=resource, policy=policy - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_set_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - policy = {} - - with pytest.raises(CustomException): - client.set_iam_policy(resource, policy) - - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions) - - def test_update_finding(self): - # Setup Expected Response - name = "name3373707" - parent = "parent-995424086" - resource_name = "resourceName979421212" - category = "category50511102" - external_uri = "externalUri-1385596168" - expected_response = { - "name": name, - "parent": parent, - "resource_name": resource_name, - "category": category, - "external_uri": external_uri, - } - expected_response = finding_pb2.Finding(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - finding = {} - - response = client.update_finding(finding) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateFindingRequest( - finding=finding - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_finding_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - finding = {} - - with pytest.raises(CustomException): - client.update_finding(finding) - - def test_update_notification_config(self): - # Setup Expected Response - name = "name3373707" - description = "description-1724546052" - pubsub_topic = "pubsubTopic-338126829" - service_account = "serviceAccount-1948028253" - expected_response = { - "name": name, - "description": description, - "pubsub_topic": pubsub_topic, - "service_account": service_account, - } - expected_response = notification_config_pb2.NotificationConfig( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - notification_config = {} - - response = client.update_notification_config(notification_config) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateNotificationConfigRequest( - notification_config=notification_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_notification_config_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - notification_config = {} - - with pytest.raises(CustomException): - client.update_notification_config(notification_config) - - def test_update_organization_settings(self): - # Setup Expected Response - name = "name3373707" - enable_asset_discovery = False - expected_response = { - "name": name, - "enable_asset_discovery": enable_asset_discovery, - } - expected_response = organization_settings_pb2.OrganizationSettings( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - organization_settings = {} - - response = client.update_organization_settings(organization_settings) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateOrganizationSettingsRequest( - organization_settings=organization_settings - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_organization_settings_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - organization_settings = {} - - with pytest.raises(CustomException): - client.update_organization_settings(organization_settings) - - def test_update_source(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - } - expected_response = source_pb2.Source(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - source = {} - - response = client.update_source(source) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateSourceRequest(source=source) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_source_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - source = {} - - with pytest.raises(CustomException): - client.update_source(source) - - def test_update_security_marks(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = security_marks_pb2.SecurityMarks(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup Request - security_marks = {} - - response = client.update_security_marks(security_marks) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.UpdateSecurityMarksRequest( - security_marks=security_marks - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_security_marks_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1p1beta1.SecurityCenterClient() - - # Setup request - security_marks = {} - - with pytest.raises(CustomException): - client.update_security_marks(security_marks)